Initial commit

This commit is contained in:
Local Administrator
2025-04-18 10:32:42 +02:00
commit b83134aca3
29643 changed files with 3045897 additions and 0 deletions

View File

@@ -0,0 +1,445 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
class Client
{
public const WRAPPER_VERSION = Config::WRAPPER_VERSION;
/**
* connect_timeout: (float, default=2) Float describing the number of
* seconds to wait while trying to connect to a server. Use 0 to wait
* indefinitely (the default behavior).
*/
public const CONNECT_TIMEOUT = 'connect_timeout';
/**
* timeout: (float, default=15) Float describing the timeout of the
* request in seconds. Use 0 to wait indefinitely (the default behavior).
*/
public const TIMEOUT = 'timeout';
/**
* proxy: (array, default=none) Array describing the proxy options used by guzzle client
* See guzzle-http for specification.
*/
public const PROXY = 'proxy';
private $apikey;
private $apisecret;
private $apitoken;
private $version = Config::MAIN_VERSION;
private $url = Config::MAIN_URL;
private $secure = Config::SECURED;
private $call = true;
private $settings = [];
private $changed = false;
/**
* @var int[]
*/
private $requestOptions = [
self::TIMEOUT => 15,
self::CONNECT_TIMEOUT => 2,
];
/**
* @var string[]
*/
private $smsResources = [
'send',
'sms',
'sms-send',
];
/**
* @var string[]
*/
private $dataAction = [
'csverror/text:csv',
'csvdata/text:plain',
'JSONError/application:json/LAST',
];
/**
* Client constructor requires:.
*
* @param string $key Mailjet API Key
* @param string|null $secret Mailjet API Secret
* @param bool $call performs the call or not
* @param array $settings
*/
public function __construct(string $key, string $secret = null, bool $call = true, array $settings = [])
{
$this->setAuthentication($key, $secret, $call, $settings);
}
/**
* Trigger a POST request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function post(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('POST', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a GET request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function get(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('GET', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a POST request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function put(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('PUT', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a GET request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function delete(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('DELETE', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Sets if we need to use https or http protocol while using API Url.
*
* @param bool|mixed $bIsSecured True use https / false use http
* @return bool true if we set value false otherwise
*/
public function setSecureProtocol($bIsSecured = null): bool
{
if (\is_bool($bIsSecured)) {
$this->secure = $bIsSecured;
return true;
}
return false;
}
/**
* Set HTTP request Timeout.
*
* @param int $timeout
*/
public function setTimeout(int $timeout): void
{
$this->requestOptions[self::TIMEOUT] = $timeout;
}
/**
* Set HTTP proxy options
* See: http://docs.guzzlephp.org/en/stable/request-options.html#proxy.
*
* @param array $proxyArray
*/
public function setHttpProxy(array $proxyArray): void
{
$this->requestOptions[self::PROXY] = $proxyArray;
}
/**
* Set HTTP connection Timeout.
*
* @param int $timeout
*/
public function setConnectionTimeout(int $timeout): void
{
$this->requestOptions[self::CONNECT_TIMEOUT] = $timeout;
}
/**
* Get HTTP request Timeout
* $return int|null.
*/
public function getTimeout(): ?int
{
return $this->requestOptions[self::TIMEOUT];
}
/**
* Get HTTP connection Timeout
* $return int|null.
*/
public function getConnectionTimeout(): ?int
{
return $this->requestOptions[self::CONNECT_TIMEOUT];
}
/**
* Add a HTTP request option.
*
* @param string $key
* @param mixed $value
* [IMPORTANT]Default options will be overwritten
* if such option is provided
* @see \GuzzleHttp\RequestOptions for a list of available request options.
*/
public function addRequestOption(string $key, $value): void
{
if ($key && (null !== $value)) {
$this->requestOptions[$key] = $value;
}
}
/**
* Get HTTP connection options
* $return array.
*/
public function getRequestOptions(): array
{
return $this->requestOptions;
}
/**
* Set auth.
*
* @param string $key
* @param string|null $secret
* @param bool $call
* @param array $settings
*/
public function setAuthentication(string $key, ?string $secret, bool $call, array $settings = []): void
{
$isBasicAuth = $this->isBasicAuthentication($key, $secret);
if ($isBasicAuth) {
$this->apikey = $key;
$this->apisecret = $secret;
} else {
$this->apitoken = $key;
$this->version = Config::SMS_VERSION;
}
$this->initSettings($call, $settings);
$this->setSettings();
}
// phpcs:disable
/**
* Magic method to call a mailjet resource.
* @param string $method Http method
* @param string $resource mailjet resource
* @param string $action mailjet resource action
* @param array $args Request arguments
* @return Response server response
*/
private function _call(string $method, string $resource, string $action, array $args): Response
{
$args = array_merge([
'id' => '',
'actionid' => '',
'filters' => [],
'body' => 'GET' === $method ? null : '{}',
], array_change_key_case($args));
$url = $this->buildURL($resource, $action, (string)$args['id'], $args['actionid']);
$contentType = 'application/json';
if ('csvdata/text:plain' === $action) {
$contentType = 'text/plain';
} elseif ('csverror/text:csv' === $action) {
$contentType = 'text/csv';
}
$isBasicAuth = $this->isBasicAuthentication($this->apikey, $this->apisecret);
$auth = $isBasicAuth ? [$this->apikey, $this->apisecret] : [$this->apitoken];
$request = new Request(
$auth,
$method,
$url,
$args['filters'],
$args['body'],
$contentType,
$this->requestOptions
);
return $request->call($this->call);
}
// phpcs:enable
/**
* Build the base API url depending on wether user need a secure connection
* or not.
*
* @return string the API url;
*/
private function getApiUrl(): string
{
$h = true === $this->secure ? 'https' : 'http';
return sprintf('%s://%s/%s/', $h, $this->url, $this->version);
}
/**
* Checks that both parameters are strings, which means
* that basic authentication will be required.
*
* @param mixed $key
* @param mixed $secret
* @return bool flag
*/
private function isBasicAuthentication($key, $secret): bool
{
return !empty($key) && !empty($secret);
}
/**
* Build the final call url without query strings.
*
* @param string $resource Mailjet resource
* @param string $action Mailjet resource action
* @param string $id mailjet resource id
* @param string $actionid mailjet resource actionid
* @return string final call url
*/
private function buildURL(string $resource, string $action, string $id, string $actionid): string
{
$path = 'REST';
if (\in_array($resource, $this->smsResources, true)) {
$path = '';
} elseif (\in_array($action, $this->dataAction, true)) {
$path = 'DATA';
} elseif ('v4' === $this->version) {
$path = '';
}
$arrayFilter = [$path, $resource, $id, $action, $actionid];
return $this->getApiUrl() . implode('/', array_filter($arrayFilter));
}
/**
* Temporary set the variables generating the url.
*
* @param array $options contain temporary modifications for the client
* @param array $resource may contain the version linked to the resource
*/
private function setOptions(array $options, array $resource): void
{
if (isset($options['version'])) {
$this->version = $options['version'];
} elseif (isset($resource[2])) {
$this->version = $resource[2];
}
$this->url = (string)($options['url'] ?? Config::MAIN_URL);
$this->secure = $options['secured'] ?? Config::SECURED;
$this->call = $options['call'] ?? true;
$this->changed = true;
}
/**
* set back the variables generating the url.
*/
private function setSettings(): void
{
if (!empty($this->settings['url']) && \is_string($this->settings['url'])) {
$this->url = $this->settings['url'];
}
if (!empty($this->settings['version']) && \is_string($this->settings['version'])) {
$this->version = $this->settings['version'];
}
if (isset($this->settings['call']) && \is_bool($this->settings['call'])) {
$this->call = $this->settings['call'];
}
if (isset($this->settings['secured']) && \is_bool($this->settings['secured'])) {
$this->secure = $this->settings['secured'];
}
$this->changed = false;
}
/**
* Set a backup if the variables generating the url are change during a call.
*
* @param bool $call
* @param array $settings
*/
private function initSettings(bool $call, array $settings = []): void
{
$this->settings['url'] = $settings['url'] ?? $this->url;
$this->settings['version'] = $settings['version'] ?? $this->version;
$this->settings['call'] = $call;
$this->settings['secured'] = $settings['secured'] ?? $this->secure;
$this->changed = false;
}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
class Config
{
public const WRAPPER_VERSION = 'v2.0.0';
public const USER_AGENT = 'mailjet-apiv3-php/';
public const MAIN_VERSION = 'v3';
public const MAIN_URL = 'api.mailjet.com';
public const SECURED = true;
public const SMS_VERSION = 'v4';
}

View File

@@ -0,0 +1,250 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\ClientTrait as GuzzleClientTrait;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
class Request
{
use GuzzleClientTrait;
/**
* @var string
*/
private $method;
/**
* @var string
*/
private $url;
/**
* @var array
*/
private $filters;
/**
* @var array
*/
private $body;
/**
* @var array
*/
private $auth;
/**
* @var string
*/
private $type;
/**
* @var array
*/
private $requestOptions = [];
/**
* @var GuzzleClient
*/
private $guzzleClient;
/**
* Build a new Http request.
*
* @param array $auth [apikey, apisecret]
* @param string $method http method
* @param string $url call url
* @param array $filters Mailjet resource filters
* @param mixed $body Mailjet resource body
* @param string $type Request Content-type
* @param array $requestOptions
*/
public function __construct(
array $auth,
string $method,
string $url,
array $filters,
$body,
string $type,
array $requestOptions = []
) {
$this->type = $type;
$this->auth = $auth;
$this->method = $method;
$this->url = $url;
$this->filters = $filters;
$this->body = $body;
$this->requestOptions = $requestOptions;
$this->guzzleClient = new GuzzleClient(
['defaults' => [
'headers' => [
'user-agent' => Config::USER_AGENT . PHP_VERSION . '/' . Client::WRAPPER_VERSION,
],
],
]
);
}
/**
* Trigger the actual call
*
* @param $call
* @return Response the call response
*/
public function call($call): Response
{
$payload = [
'query' => $this->filters,
('application/json' === $this->type ? 'json' : 'body') => $this->body,
];
$authArgsCount = \count($this->auth);
$headers = [
'content-type' => $this->type,
];
if ($authArgsCount > 1) {
$payload['auth'] = $this->auth;
} else {
$headers['Authorization'] = 'Bearer ' . $this->auth[0];
}
$payload['headers'] = $headers;
if ((!empty($this->requestOptions)) && (\is_array($this->requestOptions))) {
$payload = array_merge_recursive($payload, $this->requestOptions);
}
$response = null;
if ($call) {
try {
$response = call_user_func([$this, strtolower($this->method)], $this->url, $payload);
} catch (ClientException|ServerException $e) {
$response = $e->getResponse();
}
}
return new Response($this, $response);
}
/**
* Filters getters.
*
* @return array Request filters
*/
public function getFilters(): array
{
return $this->filters;
}
/**
* Http method getter.
*
* @return string Request method
*/
public function getMethod(): string
{
return $this->method;
}
/**
* Call Url getter.
*
* @return string Request Url
*/
public function getUrl(): string
{
return $this->url;
}
/**
* Request body getter.
*
* @return array request body
*/
public function getBody(): array
{
return $this->body;
}
/**
* Auth getter. to discuss.
*
* @return array Request auth
*/
public function getAuth(): array
{
return $this->auth;
}
/**
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []): ResponseInterface
{
return $this->guzzleClient->send($request, $options);
}
/**
* @param RequestInterface $request
* @return ResponseInterface
* @throws ClientExceptionInterface
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
return $this->guzzleClient->sendRequest($request);
}
/**
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
{
return $this->guzzleClient->sendAsync($request, $options);
}
/**
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
* @throws GuzzleException
*/
public function request(string $method, $uri, array $options = []): ResponseInterface
{
return $this->guzzleClient->request($method, $uri, $options);
}
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface
{
return $this->guzzleClient->requestAsync($method, $uri, $options);
}
}

View File

@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
/**
* PHP version 7.2.
*
* This is the Mailjet Resources Class
*
* @category Mailjet_API
*
* @author Guillaume Badi <gbadi@mailjet.com>
* @license MIT https://opensource.org/licenses/MIT
*
* @see dev.mailjet.com
*/
class Resources
{
public static $Email = ['send', ''/*, 'v3.1'*/];
public static $Aggregategraphstatistics = ['aggregategraphstatistics', ''];
public static $Apikey = ['apikey', ''];
public static $Apikeyaccess = ['apikeyaccess', ''];
public static $Apikeytotals = ['apikeytotals', ''];
public static $Apitoken = ['apitoken', ''];
public static $Axtesting = ['axtesting', ''];
public static $Batchjob = ['batchjob', ''];
public static $BatchjobCsverror = ['batchjob', 'csverror/text:csv'];
public static $BatchjobJsonerror = ['batchjob', 'JSONError/application:json/LAST'];
public static $Bouncestatistics = ['bouncestatistics', ''];
public static $Campaign = ['campaign', ''];
public static $Campaignaggregate = ['campaignaggregate', ''];
public static $Campaigndraft = ['campaigndraft', ''];
public static $CampaigndraftSchedule = ['campaigndraft', 'schedule'];
public static $CampaigndraftStatus = ['campaigndraft', 'status'];
public static $CampaigndraftSend = ['campaigndraft', 'send'];
public static $CampaigndraftTest = ['campaigndraft', 'test'];
public static $CampaigndraftDetailcontent = ['campaigndraft', 'detailcontent'];
public static $Campaigngraphstatistics = ['campaigngraphstatistics', ''];
public static $Campaignoverview = ['campaignoverview', ''];
public static $Campaignstatistics = ['campaignstatistics', ''];
public static $Clickstatistics = ['clickstatistics', ''];
public static $Contact = ['contact', ''];
public static $ContactManagecontactslists = ['contact', 'managecontactslists'];
public static $ContactGetcontactslists = ['contact', 'getcontactslists'];
public static $ContactManagemanycontacts = ['contact', 'managemanycontacts'];
public static $Contactdata = ['contactdata', ''];
public static $Contactfilter = ['contactfilter', ''];
public static $Contacthistorydata = ['contacthistorydata', ''];
public static $Contactmetadata = ['contactmetadata', ''];
public static $Contactslist = ['contactslist', ''];
public static $ContactslistCsvdata = ['contactslist', 'csvdata/text:plain'];
public static $ContactslistManagecontact = ['contactslist', 'ManageContact'];
public static $ContactslistManagemanycontacts = ['contactslist', 'ManageManyContacts'];
public static $ContactslistImportlist = ['contactslist', 'ImportList'];
public static $Contactslistsignup = ['contactslistsignup', ''];
public static $Contactstatistics = ['contactstatistics', ''];
public static $Csvimport = ['csvimport', ''];
public static $Dns = ['dns', ''];
public static $DnsCheck = ['dns', 'check'];
public static $Domainstatistics = ['domainstatistics', ''];
public static $Eventcallbackurl = ['eventcallbackurl', ''];
public static $Geostatistics = ['geostatistics', ''];
public static $Graphstatistics = ['graphstatistics', ''];
public static $Listrecipient = ['listrecipient', ''];
public static $Listrecipientstatistics = ['listrecipientstatistics', ''];
public static $Liststatistics = ['liststatistics', ''];
public static $Message = ['message', ''];
public static $Messagehistory = ['messagehistory', ''];
public static $Messageinformation = ['messageinformation', ''];
public static $Messagesentstatistics = ['messagesentstatistics', ''];
public static $Messagestate = ['messagestate', ''];
public static $Messagestatistics = ['messagestatistics', ''];
public static $Metadata = ['metadata', ''];
public static $Metasender = ['metasender', ''];
public static $Myprofile = ['myprofile', ''];
public static $Newsletter = ['newsletter', ''];
public static $NewsletterSchedule = ['newsletter', 'schedule'];
public static $NewsletterStatus = ['newsletter', 'status'];
public static $NewsletterSend = ['newsletter', 'send'];
public static $NewsletterTest = ['newsletter', 'test'];
public static $NewsletterDetailcontent = ['newsletter', 'detailcontent'];
public static $Newslettertemplate = ['newslettertemplate', ''];
public static $Newslettertemplatecategory = ['newslettertemplatecategory', ''];
public static $Openinformation = ['openinformation', ''];
public static $Openstatistics = ['openstatistics', ''];
public static $Parseroute = ['parseroute', ''];
public static $Preferences = ['preferences', ''];
public static $Preset = ['preset', ''];
public static $Sender = ['sender', ''];
public static $SenderValidate = ['sender', 'validate'];
public static $Senderstatistics = ['senderstatistics', ''];
public static $Template = ['template', ''];
public static $TemplateDetailcontent = ['template', 'detailcontent'];
public static $TemplateDetailpreviews = ['template', 'detailpreviews'];
public static $TemplateDisplaypreview = ['template', 'displaypreview'];
public static $TemplateDetailthumbnail = ['template', 'detailthumbnail'];
public static $TemplateDisplaythumbnail = ['template', 'displaythumbnail'];
public static $Toplinkclicked = ['toplinkclicked', ''];
public static $Trigger = ['trigger', ''];
public static $User = ['user', ''];
public static $UserActivate = ['user', 'activate'];
public static $Useragentstatistics = ['useragentstatistics', ''];
public static $Widget = ['widget', ''];
public static $Widgetcustomvalue = ['widgetcustomvalue', ''];
public static $Statcounters = ['statcounters', ''];
public static $StatisticsLinkclick = ['statistics', 'link-click'];
public static $StatisticsRecipientesp = ['statistics', 'recipient-esp'];
public static $Sms = ['sms', ''];
public static $SmsSend = ['sms-send', ''];
public static $SmsExport = ['sms', 'export'];
public static $SmsCount = ['sms', 'count'];
}

View File

@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use Psr\Http\Message\ResponseInterface;
class Response
{
/**
* @var int|null
*/
private $status = null;
/**
* @var bool|null
*/
private $success = null;
/**
* @var array
*/
private $body = [];
/**
* @var ResponseInterface|null
*/
private $rawResponse = null;
/**
* @var Request
*/
private $request;
/**
* Construct a Mailjet response.
*
* @param Request $request Mailjet actual request
* @param ResponseInterface|null $response Guzzle response
*/
public function __construct(Request $request, ?ResponseInterface $response)
{
$this->request = $request;
if ($response) {
$this->rawResponse = $response;
$this->status = $response->getStatusCode();
$this->body = $this->decodeBody($response->getBody()->getContents());
$this->success = 2 == floor($this->status / 100);
}
}
/**
* Status Getter
* return the http status code.
*
* @return int|null status
*/
public function getStatus(): ?int
{
return $this->status;
}
/**
* Status Getter
* return the entire response array.
*/
public function getBody(): array
{
return $this->body;
}
/**
* Data Getter
* The data returned by the mailjet call.
*
* @return array data
*/
public function getData(): array
{
return $this->body['Data'] ?? $this->body;
}
/**
* Count getter
* return the resulting array size.
*/
public function getCount(): ?int
{
return $this->body['Count'] ?? null;
}
/**
* Error Reason getter
* return the resulting error message.
*
* @return string|null
*/
public function getReasonPhrase(): ?string
{
return $this->rawResponse ? $this->rawResponse->getReasonPhrase() : null;
}
/**
* Total getter
* return the total count of all results.
*
* @return int|null count
*/
public function getTotal(): ?int
{
return $this->body['Total'] ?? null;
}
/**
* Success getter.
*
* @return bool|null true is return code is 2**
*/
public function success(): ?bool
{
return $this->success;
}
public function getRequest(): Request
{
return $this->request;
}
/**
* Decodes a mailjet string response to an object representing that response.
*
* @param string $body The mailjet response as string
* @return array Object representing the mailjet response
*/
protected function decodeBody(string $body): array
{
return json_decode($body, true, 512, JSON_BIGINT_AS_STRING) ?: [];
}
}