This commit is contained in:
Kilian Hofmann 2021-07-25 18:20:49 +02:00
parent 644f3697c7
commit 5f6f382ace
10 changed files with 1723 additions and 0 deletions

View File

@ -0,0 +1,219 @@
# Changelog
## 7.0.1
* [FIXED] Infinite recursion in `presence_auth`.
## 7.0.0
* [DEPRECATED] `get_channel_info`, `get_channels`, `socket_auth`, `presence_auth` in favour of camelCased versions
* [DEPRECATED] `get_users_info` in favour of `getPresenceUsers`
* [DEPRECATED] `ensure_valid_signature` in favour of `verifySignature`
* [CHANGED] Restrict `$app_id` parameter of the `Pusher()` object to `string` (`int` was possible).
* [ADDED] Return types.
* [ADDED] Namespacing, PSR-12 formatting.
## 6.1.0
* [ADDED] triggerAsync and triggerBatchAsync using the Guzzle async interface.
## 6.0.1
* [CHANGED] Use type hints where possible (mixed type not available in PHP7).
* [CHANGED] Document that functions can throw GuzzleException.
## 6.0.0
* [CHANGED] internal HTTP client to Guzzle
* [ADDED] optional client parameter to constructor
* [CHANGED] useTLS is true by default
* [REMOVED] `curl_options` from options
* [REMOVED] customer logger
* [REMOVED] host, port and timeout constructor parameters
* [REMOVED] support for PHP 7.1
* [CHANGED] lower severity level of logging to DEBUG level
## 5.0.3
* [CHANGED] Ensure version in Pusher.php is bumped on release.
## 5.0.2
* [CHANGED] Add release automation actions.
## 5.0.1
* [FIXED] Notice raised due to reference to potentially missing object property in `trigger` method
## 5.0.0
* [CHANGED] The methods that make HTTP requests now throw an `ApiErrorException` instead of returning `false` for non-2xx responses
* [CHANGED] `trigger` now accepts a `$params` associative array instead of a `$socket_id` as the third parameter
* [ADDED] Support for requesting channel attributes as part of a `trigger` and `triggerBatch` request via an `info` parameter
* [REMOVED] `debug` parameter from methods that make HTTP requests and from the constructor options
* [REMOVED] Support for legacy push notifications (this has been superseded by https://github.com/pusher/push-notifications-php)
## 4.1.5
* [ADDED] Support for PHP 8.
## 4.1.4
* [FIXED] Errors in the failure path of `get_...` methods revealed by stricter type checking in PHP7.4
## 4.1.3
* No functional change, previous release was only partially successful
## 4.1.2
* [ADDED] option `encryption_master_key_base64`
* [DEPRECATED] option `encryption_master_key`
## 4.1.1
* [ADDED] Support for PHP 7.4.
## 4.1.0
* [ADDED] `path` configuration option.
## 4.0.0
* [REMOVED] Support for PHP 5.x, PHP 7.0 and HHVM.
## 3.4.1
* [ADDED] Support for PHP 7.3.
## 3.4.0
* [ADDED] `get_users_info` method.
## 3.3.1
* [FIXED] PHP Notice for Undefined `socket_id` in triggerBatch
## 3.3.0
* [ADDED] Support for End-to-end encrypted channels for triggerbatch
* [FIXED] trigger behavior with mixtures of encrypted and non-encrypted channels
## 3.2.0
* [ADDED] This release adds support for end to end encrypted channels, a new feature for Channels. Read more [in our docs](https://pusher.com/docs/client_api_guide/client_encrypted_channels).
* [DEPRECATED] Renamed `encrypted` option to `useTLS` - `encrypted` will still work!
## 3.1.0
* [ADDED] This release adds Webhook validation as well as a data structure to store Webhook payloads.
## 3.0.4
* [FIXED] Non zero indexed arrays of channels no longer get serialized as an object.
## 3.0.3
* [ADDED] PSR-3 logger compatibility.
* [CHANGED] Improved PHP docs.
## 3.0.2
* [FIXED] Insufficient check for un-initialized curl resource.
* [FIXED] Acceptance tests.
## 3.0.1
* [CHANGED] Info messages are now prefixed with INFO and errors are now prefixed with ERROR.
## 3.0.0
* [NEW] Added namespaces (thanks [@vinkla](https://github.com/vinkla)).
## 2.6.4
* [FIXED] Log the curl error in more circumstances
## 2.6.1
* [FIXED] Check for correct status code when POSTing to native push notifications API.
## 2.6.0
* [ADDED] support for publishing push notifications on up to 10 interests.
## 2.5.0
* [REMOVED] Native push notifications payload validation in the client.
## 2.5.0-rc2
* [FIXED] DDN and Native Push endpoints were not assembled correctly.
## 2.5.0-rc1
* [NEW] Native push notifications
## 2.4.2
* [CHANGED] One curl instance per Pusher instance
## 2.4.1
* [FIXED] Presence data could not be submitted after the style changes
## 2.4.0
* [ADDED] Support for batch events
* [ADDED] Curl options
* [FIXED] Applied fixes from StyleCI
## 2.3.0
* [ADDED] A new `cluster` option for the Pusher constructor.
## 2.2.2
* [FIXED] Fixed a PHP 5.2 incompatibility caused by referencing a private method in array_walk.
## 2.2.1
* [FIXED] Channel name and socket_id values are now validated.
* [BROKE] Inadvertently broke PHP 5.2 compatibility by referencing a private method in array_walk.
## 2.2.0
* [CHANGED] `new Pusher($app_key, $app_secret, $app_id, $options)` - The `$options` parameter
has been added as the forth parameter to the constructor and other additional
parameters are now deprecated.
## 2.1.3
* [NEW] `$pusher->trigger` can now take an `array` of channel names as a first parameter to allow the same event to be published on multiple channels.
* [NEW] `$pusher->get` generic function can be used to make `GET` calls to the REST API
* [NEW] `$pusher->set_logger` to allow internal logging to be exposed and logged in your own logs.
## 2.1.2
* [CHANGED] Debug response from `$pusher->trigger` call is now an associative array in the form `array( 'body' => '{String} body text of response', 'status' => '{Number} http status of the response' )`
## 2.1.1
* [CHANGED] Added optional $options parameter to get_channel_info. get_channel_info($channel, $options = array() )
## 2.1.0
* [CHANGED] Renamed get_channel_stats to get_channel_info
* [CHANGED] get_channels now takes and $options parameter. get_channels( $options = array() )
* [REMOVED] get_presence_channels
## 2.0.1
* [FIXED] Overwritten socket_id parameter in trigger: https://github.com/pusher/pusher-php-server/pull/3
## 2.0.0
* [NEW] Versioning introduced at 2.0.0
* [NEW] Added composer.json for submission to http://packagist.org/
* [CHANGED] `get_channels()` now returns an object which has a `channels` property. This must be accessed to get the Array of channels in an application.
* [CHANGED] `get_presence_channels()` now returns an object which has a `channels` property. This must be accessed to get the Array of channels in an application.

View File

@ -0,0 +1,36 @@
{
"name": "pusher/pusher-php-server",
"description" : "Library for interacting with the Pusher REST API",
"keywords": ["php-pusher-server", "pusher", "rest", "realtime", "real-time", "real time", "messaging", "push", "trigger", "publish", "events"],
"license": "MIT",
"require": {
"php": "^7.3|^8.0",
"ext-curl": "*",
"ext-json": "*",
"guzzlehttp/guzzle": "^7.2",
"psr/log": "^1.0",
"paragonie/sodium_compat": "^1.6"
},
"require-dev": {
"phpunit/phpunit": "^8.5|^9.3",
"overtrue/phplint": "^2.3"
},
"autoload": {
"psr-4": {
"Pusher\\": "src/"
}
},
"autoload-dev": {
"psr-4": { "": "tests/" }
},
"config": {
"preferred-install": "dist"
},
"extra": {
"branch-alias": {
"dev-master": "5.0-dev"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}

View File

@ -0,0 +1,7 @@
## Description
Add a short description of the change. If this is related to an issue, please add a reference to the issue.
## CHANGELOG
* [CHANGED] Describe your change here. Look at CHANGELOG.md to see the format.

View File

@ -0,0 +1,21 @@
<?php
namespace Pusher;
/**
* HTTP error responses.
* getCode() will return the response HTTP status code,
* and getMessage() will return the response body.
*/
class ApiErrorException extends PusherException
{
/**
* Returns the string representation of the exception.
*
* @return string
*/
public function __toString(): string
{
return "(Status {$this->getCode()}) {$this->getMessage()}";
}
}

915
vendor/pusher/pusher-php-server/src/Pusher.php vendored Executable file
View File

@ -0,0 +1,915 @@
<?php
namespace Pusher;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise\PromiseInterface;
class Pusher implements LoggerAwareInterface, PusherInterface
{
use LoggerAwareTrait;
/**
* @var string Version
*/
public static $VERSION = '7.0.1';
/**
* @var null|PusherCrypto
*/
private $crypto;
/**
* @var array Settings
*/
private $settings = [
'scheme' => 'http',
'port' => 80,
'path' => '',
'timeout' => 30,
];
/**
* @var null|resource
*/
private $client = null; // Guzzle client
/**
* Initializes a new Pusher instance with key, secret, app ID and channel.
*
* @param string $auth_key
* @param string $secret
* @param string $app_id
* @param array $options [optional]
* Options to configure the Pusher instance.
* scheme - e.g. http or https
* host - the host e.g. api-mt1.pusher.com. No trailing forward slash.
* port - the http port
* timeout - the http timeout
* useTLS - quick option to use scheme of https and port 443 (default is true).
* cluster - cluster name to connect to.
* encryption_master_key_base64 - a 32 byte key, encoded as base64. This key, along with the channel name, are used to derive per-channel encryption keys. Per-channel keys are used to encrypt event data on encrypted channels.
* @param ClientInterface|null $client [optional] - a Guzzle client to use for all HTTP requests
*
* @throws PusherException Throws exception if any required dependencies are missing
*/
public function __construct(string $auth_key, string $secret, string $app_id, array $options = [], ClientInterface $client = null)
{
$this->check_compatibility();
if (!is_null($client)) {
$this->client = $client;
} else {
$this->client = new \GuzzleHttp\Client();
}
$useTLS = true;
if (isset($options['useTLS'])) {
$useTLS = $options['useTLS'] === true;
}
if (
$useTLS &&
!isset($options['scheme']) &&
!isset($options['port'])
) {
$options['scheme'] = 'https';
$options['port'] = 443;
}
$this->settings['auth_key'] = $auth_key;
$this->settings['secret'] = $secret;
$this->settings['app_id'] = $app_id;
$this->settings['base_path'] = '/apps/' . $this->settings['app_id'];
foreach ($options as $key => $value) {
// only set if valid setting/option
if (isset($this->settings[$key])) {
$this->settings[$key] = $value;
}
}
// handle the case when 'host' and 'cluster' are specified in the options.
if (!array_key_exists('host', $this->settings)) {
if (array_key_exists('host', $options)) {
$this->settings['host'] = $options['host'];
} elseif (array_key_exists('cluster', $options)) {
$this->settings['host'] = 'api-' . $options['cluster'] . '.pusher.com';
} else {
$this->settings['host'] = 'api-mt1.pusher.com';
}
}
// ensure host doesn't have a scheme prefix
$this->settings['host'] = preg_replace('/http[s]?\:\/\//', '', $this->settings['host'], 1);
if (!array_key_exists('encryption_master_key_base64', $options)) {
$options['encryption_master_key_base64'] = '';
}
if ($options['encryption_master_key_base64'] !== '') {
$parsedKey = PusherCrypto::parse_master_key(
$options['encryption_master_key_base64']
);
$this->crypto = new PusherCrypto($parsedKey);
}
}
/**
* Fetch the settings.
*
* @return array
*/
public function getSettings(): array
{
return $this->settings;
}
/**
* Log a string.
*
* @param string $msg The message to log
* @param array|\Exception $context [optional] Any extraneous information that does not fit well in a string.
* @param string $level [optional] Importance of log message, highly recommended to use Psr\Log\LogLevel::{level}
*/
private function log(string $msg, array $context = [], string $level = LogLevel::DEBUG): void
{
if (is_null($this->logger)) {
return;
}
if ($this->logger instanceof LoggerInterface) {
$this->logger->log($level, $msg, $context);
return;
}
// Support old style logger (deprecated)
$msg = sprintf('Pusher: %s: %s', strtoupper($level), $msg);
$replacement = [];
foreach ($context as $k => $v) {
$replacement['{' . $k . '}'] = $v;
}
$this->logger->log($level, strtr($msg, $replacement));
}
/**
* Check if the current PHP setup is sufficient to run this class.
*
* @throws PusherException If any required dependencies are missing
*/
private function check_compatibility(): void
{
if (!extension_loaded('json')) {
throw new PusherException('The Pusher library requires the PHP JSON module. Please ensure it is installed');
}
if (!in_array('sha256', hash_algos(), true)) {
throw new PusherException('SHA256 appears to be unsupported - make sure you have support for it, or upgrade your version of PHP.');
}
}
/**
* Validate number of channels and channel name format.
*
* @param string[] $channels An array of channel names to validate
*
* @throws PusherException If $channels is too big or any channel is invalid
*/
private function validate_channels(array $channels): void
{
if (count($channels) > 100) {
throw new PusherException('An event can be triggered on a maximum of 100 channels in a single call.');
}
foreach ($channels as $channel) {
$this->validate_channel($channel);
}
}
/**
* Ensure a channel name is valid based on our spec.
*
* @param string $channel The channel name to validate
*
* @throws PusherException If $channel is invalid
*/
private function validate_channel(string $channel): void
{
if (!preg_match('/\A[-a-zA-Z0-9_=@,.;]+\z/', $channel)) {
throw new PusherException('Invalid channel name ' . $channel);
}
}
/**
* Ensure a socket_id is valid based on our spec.
*
* @param string $socket_id The socket ID to validate
*
* @throws PusherException If $socket_id is invalid
*/
private function validate_socket_id(string $socket_id): void
{
if ($socket_id !== null && !preg_match('/\A\d+\.\d+\z/', $socket_id)) {
throw new PusherException('Invalid socket ID ' . $socket_id);
}
}
/**
* Utility function used to generate signing headers
*
* @param string $path
* @param string $request_method
* @param array $query_params [optional]
*
* @return array
*/
private function sign(string $path, string $request_method = 'GET', array $query_params = []): array
{
return self::build_auth_query_params(
$this->settings['auth_key'],
$this->settings['secret'],
$request_method,
$path,
$query_params
);
}
/**
* Build the Channels url prefix.
*
* @return string
*/
private function channels_url_prefix(): string
{
return $this->settings['scheme'] . '://' . $this->settings['host'] . ':' . $this->settings['port'] . $this->settings['path'];
}
/**
* Build the required HMAC'd auth string.
*
* @param string $auth_key
* @param string $auth_secret
* @param string $request_method
* @param string $request_path
* @param array $query_params [optional]
* @param string $auth_version [optional]
* @param string|null $auth_timestamp [optional]
* @return array
*/
public static function build_auth_query_params(
string $auth_key,
string $auth_secret,
string $request_method,
string $request_path,
array $query_params = [],
string $auth_version = '1.0',
string $auth_timestamp = null
): array {
$params = [];
$params['auth_key'] = $auth_key;
$params['auth_timestamp'] = (is_null($auth_timestamp) ? time() : $auth_timestamp);
$params['auth_version'] = $auth_version;
$params = array_merge($params, $query_params);
ksort($params);
$string_to_sign = "$request_method\n" . $request_path . "\n" . self::array_implode('=', '&', $params);
$auth_signature = hash_hmac('sha256', $string_to_sign, $auth_secret, false);
$params['auth_signature'] = $auth_signature;
return $params;
}
/**
* Implode an array with the key and value pair giving
* a glue, a separator between pairs and the array
* to implode.
*
* @param string $glue The glue between key and value
* @param string $separator Separator between pairs
* @param array|string $array The array to implode
*
* @return string The imploded array
*/
public static function array_implode(string $glue, string $separator, $array): string
{
if (!is_array($array)) {
return $array;
}
$string = [];
foreach ($array as $key => $val) {
if (is_array($val)) {
$val = implode(',', $val);
}
$string[] = "{$key}{$glue}{$val}";
}
return implode($separator, $string);
}
/**
* Helper function to prepare trigger request. Takes the same
* parameters as the public trigger functions.
*
* @param array|string $channels A channel name or an array of channel names to publish the event on.
* @param string $event
* @param mixed $data Event data
* @param array $params [optional]
* @param bool $already_encoded [optional]
*
* @return Request
* @throws PusherException Throws PusherException if $channels is an array of size 101 or above or $socket_id is invalid
*/
public function make_request($channels, string $event, $data, array $params = [], bool $already_encoded = false): Request
{
if (is_string($channels) === true) {
$channels = [$channels];
}
$this->validate_channels($channels);
if (isset($params['socket_id'])) {
$this->validate_socket_id($params['socket_id']);
}
$has_encrypted_channel = false;
foreach ($channels as $chan) {
if (PusherCrypto::is_encrypted_channel($chan)) {
$has_encrypted_channel = true;
break;
}
}
if ($has_encrypted_channel) {
if (count($channels) > 1) {
// For rationale, see limitations of end-to-end encryption in the README
throw new PusherException('You cannot trigger to multiple channels when using encrypted channels');
} else {
try {
$data_encoded = $this->crypto->encrypt_payload(
$channels[0],
$already_encoded ? $data : json_encode($data, JSON_THROW_ON_ERROR)
);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
}
} else {
try {
$data_encoded = $already_encoded ? $data : json_encode($data, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
}
$query_params = [];
$path = $this->settings['base_path'] . '/events';
// json_encode might return false on failure
if (!$data_encoded) {
$this->log('Failed to perform json_encode on the the provided data: {error}', [
'error' => print_r($data, true),
], LogLevel::ERROR);
}
$post_params = [];
$post_params['name'] = $event;
$post_params['data'] = $data_encoded;
$post_params['channels'] = array_values($channels);
$all_params = array_merge($post_params, $params);
try {
$post_value = json_encode($all_params, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
$query_params['body_md5'] = md5($post_value);
$signature = $this->sign($path, 'POST', $query_params);
$this->log('trigger POST: {post_value}', compact('post_value'));
$headers = [
'Content-Type' => 'application/json',
'X-Pusher-Library' => 'pusher-http-php ' . self::$VERSION
];
$params = array_merge($signature, $query_params);
$query_string = self::array_implode('=', '&', $params);
$full_path = $path . "?" . $query_string;
return new Request('POST', $full_path, $headers, $post_value);
}
/**
* Trigger an event by providing event name and payload.
* Optionally provide a socket ID to exclude a client (most likely the sender).
*
* @param array|string $channels A channel name or an array of channel names to publish the event on.
* @param string $event
* @param mixed $data Event data
* @param array $params [optional]
* @param bool $already_encoded [optional]
*
* @return object
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
* @throws PusherException Throws PusherException if $channels is an array of size 101 or above or $socket_id is invalid
*/
public function trigger($channels, string $event, $data, array $params = [], bool $already_encoded = false): object
{
$request = $this->make_request($channels, $event, $data, $params, $already_encoded);
$response = $this->client->send($request, [
'http_errors' => false,
'base_uri' => $this->channels_url_prefix()
]);
$status = $response->getStatusCode();
if ($status !== 200) {
$body = (string) $response->getBody();
throw new ApiErrorException($body, $status);
}
try {
$result = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
if (property_exists($result, 'channels')) {
$result->channels = get_object_vars($result->channels);
}
return $result;
}
/**
* Asynchronously trigger an event by providing event name and payload.
* Optionally provide a socket ID to exclude a client (most likely the sender).
*
* @param array|string $channels A channel name or an array of channel names to publish the event on.
* @param string $event
* @param mixed $data Event data
* @param array $params [optional]
* @param bool $already_encoded [optional]
*
* @return PromiseInterface
* @throws PusherException
*/
public function triggerAsync($channels, string $event, $data, array $params = [], bool $already_encoded = false): PromiseInterface
{
$request = $this->make_request($channels, $event, $data, $params, $already_encoded);
$promise = $this->client->sendAsync($request, [
'http_errors' => false,
'base_uri' => $this->channels_url_prefix()
])->then(function ($response) {
$status = $response->getStatusCode();
if ($status !== 200) {
$body = (string) $response->getBody();
throw new ApiErrorException($body, $status);
}
$result = json_decode($response->getBody(), null, 512, JSON_THROW_ON_ERROR);
if (property_exists($result, 'channels')) {
$result->channels = get_object_vars($result->channels);
}
return $result;
});
return $promise;
}
/**
* Helper function to prepare batch trigger request. Takes the same * parameters as the public batch trigger functions.
*
* @param array $batch [optional] An array of events to send
* @param bool $already_encoded [optional]
*
* @return Request
* @throws PusherException
*/
public function make_batch_request(array $batch = [], bool $already_encoded = false): Request
{
foreach ($batch as $key => $event) {
$this->validate_channel($event['channel']);
if (isset($event['socket_id'])) {
$this->validate_socket_id($event['socket_id']);
}
$data = $event['data'];
if (!is_string($data)) {
try {
$data = $already_encoded ? $data : json_encode($data, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
}
if (PusherCrypto::is_encrypted_channel($event['channel'])) {
$batch[$key]['data'] = $this->crypto->encrypt_payload($event['channel'], $data);
} else {
$batch[$key]['data'] = $data;
}
}
$post_params = [];
$post_params['batch'] = $batch;
try {
$post_value = json_encode($post_params, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
$query_params = [];
$query_params['body_md5'] = md5($post_value);
$path = $this->settings['base_path'] . '/batch_events';
$signature = $this->sign($path, 'POST', $query_params);
$this->log('trigger POST: {post_value}', compact('post_value'));
$headers = [
'Content-Type' => 'application/json',
'X-Pusher-Library' => 'pusher-http-php ' . self::$VERSION
];
$params = array_merge($signature, $query_params);
$query_string = self::array_implode('=', '&', $params);
$full_path = $path . "?" . $query_string;
return new Request('POST', $full_path, $headers, $post_value);
}
/**
* Trigger multiple events at the same time.
*
* @param array $batch [optional] An array of events to send
* @param bool $already_encoded [optional]
*
* @return object
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
* @throws PusherException
*/
public function triggerBatch(array $batch = [], bool $already_encoded = false): object
{
$request = $this->make_batch_request($batch, $already_encoded);
$response = $this->client->send($request, [
'http_errors' => false,
'base_uri' => $this->channels_url_prefix()
]);
$status = $response->getStatusCode();
if ($status !== 200) {
$body = (string) $response->getBody();
throw new ApiErrorException($body, $status);
}
try {
$result = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
if (property_exists($result, 'channels')) {
$result->channels = get_object_vars($result->channels);
}
return $result;
}
/**
* Asynchronously trigger multiple events at the same time.
*
* @param array $batch [optional] An array of events to send
* @param bool $already_encoded [optional]
*
* @return PromiseInterface
* @throws PusherException
*/
public function triggerBatchAsync(array $batch = [], bool $already_encoded = false): PromiseInterface
{
$request = $this->make_batch_request($batch, $already_encoded);
$promise = $this->client->sendAsync($request, [
'http_errors' => false,
'base_uri' => $this->channels_url_prefix()
])->then(function ($response) {
$status = $response->getStatusCode();
if ($status !== 200) {
$body = (string) $response->getBody();
throw new ApiErrorException($body, $status);
}
$result = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
if (property_exists($result, 'channels')) {
$result->channels = get_object_vars($result->channels);
}
return $result;
});
return $promise;
}
/**
* Fetch channel information for a specific channel.
*
* @param string $channel The name of the channel
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException If $channel is invalid
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getChannelInfo(string $channel, array $params = []): object
{
$this->validate_channel($channel);
return $this->get('/channels/' . $channel, $params);
}
/**
* @deprecated in favour of getChannelInfo
*/
public function get_channel_info(string $channel, array $params = []): object
{
return $this->getChannelInfo($channel, $params);
}
/**
* Fetch a list containing all channels.
*
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getChannels(array $params = []): object
{
$result = $this->get('/channels', $params);
$result->channels = get_object_vars($result->channels);
return $result;
}
/**
* @deprecated in favour of getChannels
*/
public function get_channels(array $params = []): object
{
return $this->getChannels($params);
}
/**
* Fetch user ids currently subscribed to a presence channel.
*
* @param string $channel The name of the channel
*
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getPresenceUsers(string $channel): object
{
return $this->get('/channels/' . $channel . '/users');
}
/**
* @deprecated in favour of getPresenceUsers
*/
public function get_users_info(string $channel): object
{
return $this->getPresenceUsers($channel);
}
/**
* GET arbitrary REST API resource using a synchronous http client.
* All request signing is handled automatically.
*
* @param string $path Path excluding /apps/APP_ID
* @param array $params API params (see http://pusher.com/docs/rest_api)
* @param bool $associative When true, return the response body as an associative array, else return as an object
*
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
* @throws PusherException
*
* @return mixed See Pusher API docs
*/
public function get(string $path, array $params = [], $associative = false)
{
$path = $this->settings['base_path'] . $path;
$signature = $this->sign($path, 'GET', $params);
$headers = [
'Content-Type' => 'application/json',
'X-Pusher-Library' => 'pusher-http-php ' . self::$VERSION
];
$response = $this->client->get($path, [
'query' => $signature,
'http_errors' => false,
'headers' => $headers,
'base_uri' => $this->channels_url_prefix()
]);
$status = $response->getStatusCode();
if ($status !== 200) {
$body = (string) $response->getBody();
throw new ApiErrorException($body, $status);
}
try {
$body = json_decode($response->getBody(), $associative, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data decoding error.');
}
return $body;
}
/**
* Creates a socket signature.
*
* @param string $channel
* @param string $socket_id
* @param string|null $custom_data
*
* @return string Json encoded authentication string.
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*/
public function socketAuth(string $channel, string $socket_id, string $custom_data = null): string
{
$this->validate_channel($channel);
$this->validate_socket_id($socket_id);
if ($custom_data) {
$signature = hash_hmac('sha256', $socket_id . ':' . $channel . ':' . $custom_data, $this->settings['secret'], false);
} else {
$signature = hash_hmac('sha256', $socket_id . ':' . $channel, $this->settings['secret'], false);
}
$signature = ['auth' => $this->settings['auth_key'] . ':' . $signature];
// add the custom data if it has been supplied
if ($custom_data) {
$signature['channel_data'] = $custom_data;
}
if (PusherCrypto::is_encrypted_channel($channel)) {
if (!is_null($this->crypto)) {
$signature['shared_secret'] = base64_encode($this->crypto->generate_shared_secret($channel));
} else {
throw new PusherException('You must specify an encryption master key to authorize an encrypted channel');
}
}
try {
$response = json_encode($signature, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
return $response;
}
/**
* @deprecated in favour of socketAuth
*/
public function socket_auth(string $channel, string $socket_id, string $custom_data = null): string
{
return $this->socketAuth($channel, $socket_id, $custom_data);
}
/**
* Creates a presence signature (an extension of socket signing).
*
* @param string $channel
* @param string $socket_id
* @param string $user_id
* @param mixed $user_info
*
* @return string
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*/
public function presenceAuth(string $channel, string $socket_id, string $user_id, $user_info = null): string
{
$user_data = ['user_id' => $user_id];
if ($user_info) {
$user_data['user_info'] = $user_info;
}
try {
return $this->socket_auth($channel, $socket_id, json_encode($user_data, JSON_THROW_ON_ERROR));
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
}
/**
* @deprecated in favour of presenceAuth
*/
public function presence_auth(string $channel, string $socket_id, string $user_id, $user_info = null): string
{
return $this->presenceAuth($channel, $socket_id, $user_id, $user_info);
}
/**
* Verify that a webhook actually came from Pusher, decrypts any encrypted events, and marshals them into a PHP object.
*
* @param array $headers a array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException
*
* @return Webhook marshalled object with the properties time_ms (an int) and events (an array of event objects)
*/
public function webhook(array $headers, string $body): object
{
$this->ensure_valid_signature($headers, $body);
$decoded_events = [];
try {
$decoded_json = json_decode($body, false, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this->log('Unable to decrypt webhook event payload.', null, LogLevel::WARNING);
throw new PusherException('Data encoding error.');
}
foreach ($decoded_json->events as $key => $event) {
if (PusherCrypto::is_encrypted_channel($event->channel)) {
if (!is_null($this->crypto)) {
$decryptedEvent = $this->crypto->decrypt_event($event);
if ($decryptedEvent === false) {
$this->log('Unable to decrypt webhook event payload. Wrong key? Ignoring.', null, LogLevel::WARNING);
continue;
}
$decoded_events[] = $decryptedEvent;
} else {
$this->log('Got an encrypted webhook event payload, but no master key specified. Ignoring.', null, LogLevel::WARNING);
continue;
}
} else {
$decoded_events[] = $event;
}
}
return new Webhook($decoded_json->time_ms, $decoded_events);
}
/**
* Verify that a given Pusher Signature is valid.
*
* @param array $headers an array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException if signature is incorrect.
*/
public function verifySignature(array $headers, string $body): void
{
$x_pusher_key = $headers['X-Pusher-Key'];
$x_pusher_signature = $headers['X-Pusher-Signature'];
if ($x_pusher_key === $this->settings['auth_key']) {
$expected = hash_hmac('sha256', $body, $this->settings['secret']);
if ($expected === $x_pusher_signature) {
return;
}
}
throw new PusherException(sprintf('Received WebHook with invalid signature: got %s.', $x_pusher_signature));
}
/**
* @deprecated in favour of verifySignature
*/
public function ensure_valid_signature(array $headers, string $body): void
{
$this->verifySignature($headers, $body);
}
}

View File

@ -0,0 +1,200 @@
<?php
namespace Pusher;
class PusherCrypto
{
private $encryption_master_key;
// The prefix any e2e channel must have
public const ENCRYPTED_PREFIX = 'private-encrypted-';
/**
* Checks if a given channel is an encrypted channel.
*
* @param string $channel the name of the channel
*
* @return bool true if channel is an encrypted channel
*/
public static function is_encrypted_channel(string $channel): bool
{
return strpos($channel, self::ENCRYPTED_PREFIX) === 0;
}
/**
* @param $encryption_master_key_base64
* @return string
* @throws PusherException
*/
public static function parse_master_key($encryption_master_key_base64): string
{
if (!function_exists('sodium_crypto_secretbox')) {
throw new PusherException('To use end to end encryption, you must either be using PHP 7.2 or greater or have installed the libsodium-php extension for php < 7.2.');
}
if ($encryption_master_key_base64 !== '') {
$decoded_key = base64_decode($encryption_master_key_base64, true);
if ($decoded_key === false) {
throw new PusherException('encryption_master_key_base64 must be a valid base64 string');
}
if (strlen($decoded_key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
throw new PusherException('encryption_master_key_base64 must encode a key which is 32 bytes long');
}
return $decoded_key;
}
return '';
}
/**
* Initialises a PusherCrypto instance.
*
* @param string $encryption_master_key the SECRET_KEY_LENGTH key that will be used for key derivation.
*/
public function __construct(string $encryption_master_key)
{
$this->encryption_master_key = $encryption_master_key;
}
/**
* Decrypts a given event.
*
* @param object $event an object that has an encrypted data property and a channel property.
*
* @return object the event with a decrypted payload, or false if decryption was unsuccessful.
* @throws PusherException
*/
public function decrypt_event(object $event): object
{
$parsed_payload = $this->parse_encrypted_message($event->data);
$shared_secret = $this->generate_shared_secret($event->channel);
$decrypted_payload = $this->decrypt_payload($parsed_payload->ciphertext, $parsed_payload->nonce, $shared_secret);
if (!$decrypted_payload) {
throw new PusherException('Decryption of the payload failed. Wrong key?');
}
$event->data = $decrypted_payload;
return $event;
}
/**
* Derives a shared secret from the secret key and the channel to broadcast to.
*
* @param string $channel the name of the channel
*
* @return string a SHA256 hash (encoded as base64) of the channel name appended to the encryption key
* @throws PusherException
*/
public function generate_shared_secret(string $channel): string
{
if (!self::is_encrypted_channel($channel)) {
throw new PusherException('You must specify a channel of the form private-encrypted-* for E2E encryption. Got ' . $channel);
}
return hash('sha256', $channel . $this->encryption_master_key, true);
}
/**
* Encrypts a given plaintext for broadcast on a particular channel.
*
* @param string $channel the name of the channel the payloads event will be broadcast on
* @param string $plaintext the data to encrypt
*
* @return string a string ready to be sent as the data of an event.
* @throws PusherException
* @throws \SodiumException
*/
public function encrypt_payload(string $channel, string $plaintext): string
{
if (!self::is_encrypted_channel($channel)) {
throw new PusherException('Cannot encrypt plaintext for a channel that is not of the form private-encrypted-*. Got ' . $channel);
}
$nonce = $this->generate_nonce();
$shared_secret = $this->generate_shared_secret($channel);
$cipher_text = sodium_crypto_secretbox($plaintext, $nonce, $shared_secret);
try {
return $this->format_encrypted_message($nonce, $cipher_text);
} catch (\JsonException $e) {
throw new PusherException('Data encoding error.');
}
}
/**
* Decrypts a given payload using the nonce and shared secret.
*
* @param string $payload the ciphertext
* @param string $nonce the nonce used in the encryption
* @param string $shared_secret the shared_secret used in the encryption
*
* @return string plaintext
* @throws \SodiumException
*/
public function decrypt_payload(string $payload, string $nonce, string $shared_secret)
{
$plaintext = sodium_crypto_secretbox_open($payload, $nonce, $shared_secret);
if (empty($plaintext)) {
return false;
}
return $plaintext;
}
/**
* Formats an encrypted message ready for broadcast.
*
* @param string $nonce the nonce used in the encryption process (bytes)
* @param string $ciphertext the ciphertext (bytes)
*
* @return string JSON with base64 encoded nonce and ciphertext`
* @throws \JsonException
*/
private function format_encrypted_message(string $nonce, string $ciphertext): string
{
$encrypted_message = new \stdClass();
$encrypted_message->nonce = base64_encode($nonce);
$encrypted_message->ciphertext = base64_encode($ciphertext);
return json_encode($encrypted_message, JSON_THROW_ON_ERROR);
}
/**
* Parses an encrypted message into its nonce and ciphertext components.
*
*
* @param string $payload the encrypted message payload
*
* @return object php object with decoded nonce and ciphertext
* @throws PusherException
*/
private function parse_encrypted_message(string $payload): object
{
try {
$decoded_payload = json_decode($payload, false, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new PusherException('Data decoding error.');
}
$decoded_payload->nonce = base64_decode($decoded_payload->nonce);
$decoded_payload->ciphertext = base64_decode($decoded_payload->ciphertext);
if ($decoded_payload->ciphertext === '' || strlen($decoded_payload->nonce) !== SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
throw new PusherException('Received a payload that cannot be parsed.');
}
return $decoded_payload;
}
/**
* Generates a nonce that is SODIUM_CRYPTO_SECRETBOX_NONCEBYTES long.
* @return string
* @throws \Exception
*/
private function generate_nonce(): string
{
return random_bytes(
SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
);
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace Pusher;
use Exception;
class PusherException extends Exception
{
}

View File

@ -0,0 +1,32 @@
<?php
namespace Pusher;
class PusherInstance
{
private static $instance = null;
private static $app_id = '';
private static $secret = '';
private static $api_key = '';
/**
* Get the pusher singleton instance.
*
* @return Pusher
* @throws PusherException
*/
public static function get_pusher()
{
if (self::$instance !== null) {
return self::$instance;
}
self::$instance = new Pusher(
self::$api_key,
self::$secret,
self::$app_id
);
return self::$instance;
}
}

View File

@ -0,0 +1,257 @@
<?php
namespace Pusher;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
interface PusherInterface
{
/**
* Fetch the settings.
*
* @return array
*/
public function getSettings();
/**
* Trigger an event by providing event name and payload.
* Optionally provide a socket ID to exclude a client (most likely the sender).
*
* @param array|string $channels A channel name or an array of channel names to publish the event on.
* @param string $event
* @param mixed $data Event data
* @param array $params [optional]
* @param bool $already_encoded [optional]
*
* @throws PusherException Throws exception if $channels is an array of size 101 or above or $socket_id is invalid
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function trigger($channels, string $event, $data, array $params = [], bool $already_encoded = false): object;
/**
* Asynchronously trigger an event by providing event name and payload.
* Optionally provide a socket ID to exclude a client (most likely the sender).
*
* @param array|string $channels A channel name or an array of channel names to publish the event on.
* @param mixed $data Event data
* @param array $params [optional]
* @param bool $already_encoded [optional]
*
*/
public function triggerAsync($channels, string $event, $data, array $params = [], bool $already_encoded = false): PromiseInterface;
/**
* Trigger multiple events at the same time.
*
* @param array $batch [optional] An array of events to send
* @param bool $already_encoded [optional]
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function triggerBatch(array $batch = [], bool $already_encoded = false): object;
/**
* Asynchronously trigger multiple events at the same time.
*
* @param array $batch [optional] An array of events to send
* @param bool $already_encoded [optional]
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
*
*/
public function triggerBatchAsync(array $batch = [], bool $already_encoded = false): PromiseInterface;
/**
* Get information, such as subscriber and user count, for a channel.
*
* @param string $channel The name of the channel
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException If $channel is invalid or if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getChannelInfo(string $channel, array $params = []): object;
/**
* Fetch a list containing all channels.
*
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getChannels(array $params = []): object;
/**
* Fetch user ids currently subscribed to a presence channel.
*
* @param string $channel The name of the channel
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function getPresenceUsers(string $channel): object;
/**
* GET arbitrary REST API resource using a synchronous http client.
* All request signing is handled automatically.
*
* @param string $path Path excluding /apps/APP_ID
* @param array $params API params (see http://pusher.com/docs/rest_api)
* @param bool $associative When true, return the response body as an associative array, else return as an object
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
* @return mixed See Pusher API docs
*/
public function get(string $path, array $params = [], bool $associative = false);
/**
* Creates a socket signature.
*
* @param string $channel
* @param string $socket_id
* @param string|null $custom_data
* @return string Json encoded authentication string.
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*/
public function socketAuth(string $channel, string $socket_id, string $custom_data = null): string;
/**
* Creates a presence signature (an extension of socket signing).
*
* @param mixed $user_info
*
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*
*/
public function presenceAuth(string $channel, string $socket_id, string $user_id, $user_info = null): string;
/**
* Verify that a webhook actually came from Pusher, decrypts any
* encrypted events, and marshals them into a PHP object.
*
* @param array $headers a array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException
*
* @return Webhook marshalled object with the properties time_ms (an int) and events (an array of event objects)
*/
public function webhook(array $headers, string $body): object;
/**
* Verify that a given Pusher Signature is valid.
*
* @param array $headers an array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException if signature is incorrect.
*/
public function verifySignature(array $headers, string $body);
/*******************************************************************
*
* DEPRECATION WARNING:
*
* all the functions below have been deprecated in favour of their
* camelCased variants. They will be removed in the next major
* update.
*/
/**
* Get information, such as subscriber and user count, for a channel.
*
* @deprecated in favour of getChannelInfo
*
* @param string $channel The name of the channel
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException If $channel is invalid or if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function get_channel_info(string $channel, array $params = []): object;
/**
* Fetch a list containing all channels.
*
* @deprecated in favour of getChannels
*
* @param array $params Additional parameters for the query e.g. $params = array( 'info' => 'connection_count' )
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function get_channels(array $params = []): object;
/**
* Fetch user ids currently subscribed to a presence channel.
*
* @deprecated in favour of getPresenceUsers
*
* @param string $channel The name of the channel
*
* @throws PusherException Throws exception if curl wasn't initialized correctly
* @throws ApiErrorException Throws ApiErrorException if the Channels HTTP API responds with an error
* @throws GuzzleException
*
*/
public function get_users_info(string $channel): object;
/**
* Creates a socket signature.
*
* @deprecated in favour of socketAuth
*
* @param string $channel
* @param string $socket_id
* @param string|null $custom_data
* @return string Json encoded authentication string.
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*/
public function socket_auth(string $channel, string $socket_id, string $custom_data = null): string;
/**
* Creates a presence signature (an extension of socket signing).
*
* @deprecated in favour of presenceAuth
*
* @param mixed $user_info
*
* @throws PusherException Throws exception if $channel is invalid or above or $socket_id is invalid
*
*/
public function presence_auth(string $channel, string $socket_id, string $user_id, $user_info = null): string;
/**
* Verify that a given Pusher Signature is valid.
*
* @deprecated in favour of verifySignature
*
* @param array $headers an array of headers from the request (for example, from getallheaders())
* @param string $body the body of the request (for example, from file_get_contents('php://input'))
*
* @throws PusherException if signature is incorrect.
*/
public function ensure_valid_signature(array $headers, string $body);
}

View File

@ -0,0 +1,27 @@
<?php
namespace Pusher;
class Webhook
{
/** @var int $time_ms */
private $time_ms;
/** @var array $events */
private $events;
public function __construct($time_ms, $events)
{
$this->time_ms = $time_ms;
$this->events = $events;
}
public function get_events(): array
{
return $this->events;
}
public function get_time_ms(): int
{
return $this->time_ms;
}
}