Нет описания

AmazonSES.php 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. <?php
  2. namespace MailPoet\Mailer\Methods;
  3. if (!defined('ABSPATH')) exit;
  4. use MailPoet\Mailer\Mailer;
  5. use MailPoet\Mailer\Methods\Common\BlacklistCheck;
  6. use MailPoet\Mailer\Methods\ErrorMappers\AmazonSESMapper;
  7. use MailPoet\WP\Functions as WPFunctions;
  8. use MailPoetVendor\Swift_Message;
  9. class AmazonSES {
  10. public $awsAccessKey;
  11. public $awsSecretKey;
  12. public $awsRegion;
  13. public $awsEndpoint;
  14. public $awsSigningAlgorithm;
  15. public $awsService;
  16. public $awsTerminationString;
  17. public $hashAlgorithm;
  18. public $url;
  19. public $sender;
  20. public $replyTo;
  21. public $returnPath;
  22. public $message;
  23. public $date;
  24. public $dateWithoutTime;
  25. private $availableRegions = [
  26. 'US East (N. Virginia)' => 'us-east-1',
  27. 'US East (Ohio)' => 'us-east-2',
  28. 'US West (N. California)' => 'us-west-1',
  29. 'US West (Oregon)' => 'us-west-2',
  30. 'EU (Ireland)' => 'eu-west-1',
  31. 'EU (London)' => 'eu-west-2',
  32. 'EU (Frankfurt)' => 'eu-central-1',
  33. 'EU (Paris)' => 'eu-west-3',
  34. 'EU (Stockholm)' => 'eu-north-1',
  35. 'Canada (Central)' => 'ca-central-1',
  36. 'Asia Pacific (Mumbai)' => 'ap-south-1',
  37. 'Asia Pacific (Seoul)' => 'ap-northeast-2',
  38. 'Asia Pacific (Singapore)' => 'ap-southeast-1',
  39. 'Asia Pacific (Sydney)' => 'ap-southeast-2',
  40. 'Asia Pacific (Tokyo)' => 'ap-northeast-1',
  41. 'South America (Sao Paulo)' => 'sa-east-1',
  42. 'AWS GovCloud (US)' => 'us-gov-west-1',
  43. ];
  44. /** @var AmazonSESMapper */
  45. private $errorMapper;
  46. /** @var BlacklistCheck */
  47. private $blacklist;
  48. private $wp;
  49. public function __construct(
  50. $region,
  51. $accessKey,
  52. $secretKey,
  53. $sender,
  54. $replyTo,
  55. $returnPath,
  56. AmazonSESMapper $errorMapper
  57. ) {
  58. $this->awsAccessKey = $accessKey;
  59. $this->awsSecretKey = $secretKey;
  60. $this->awsRegion = (in_array($region, $this->availableRegions)) ? $region : false;
  61. if (!$this->awsRegion) {
  62. throw new \Exception(__('Unsupported Amazon SES region', 'mailpoet'));
  63. }
  64. $this->awsEndpoint = sprintf('email.%s.amazonaws.com', $this->awsRegion);
  65. $this->awsSigningAlgorithm = 'AWS4-HMAC-SHA256';
  66. $this->awsService = 'ses';
  67. $this->awsTerminationString = 'aws4_request';
  68. $this->hashAlgorithm = 'sha256';
  69. $this->url = 'https://' . $this->awsEndpoint;
  70. $this->sender = $sender;
  71. $this->replyTo = $replyTo;
  72. $this->returnPath = ($returnPath) ?
  73. $returnPath :
  74. $this->sender['from_email'];
  75. $this->date = gmdate('Ymd\THis\Z');
  76. $this->dateWithoutTime = gmdate('Ymd');
  77. $this->errorMapper = $errorMapper;
  78. $this->wp = new WPFunctions();
  79. $this->blacklist = new BlacklistCheck();
  80. }
  81. public function send($newsletter, $subscriber, $extraParams = []) {
  82. if ($this->blacklist->isBlacklisted($subscriber)) {
  83. $error = $this->errorMapper->getBlacklistError($subscriber);
  84. return Mailer::formatMailerErrorResult($error);
  85. }
  86. try {
  87. $result = $this->wp->wpRemotePost(
  88. $this->url,
  89. $this->request($newsletter, $subscriber, $extraParams)
  90. );
  91. } catch (\Exception $e) {
  92. $error = $this->errorMapper->getErrorFromException($e, $subscriber);
  93. return Mailer::formatMailerErrorResult($error);
  94. }
  95. if (is_wp_error($result)) {
  96. $error = $this->errorMapper->getConnectionError($result->get_error_message());
  97. return Mailer::formatMailerErrorResult($error);
  98. }
  99. if ($this->wp->wpRemoteRetrieveResponseCode($result) !== 200) {
  100. $response = simplexml_load_string($this->wp->wpRemoteRetrieveBody($result));
  101. $error = $this->errorMapper->getErrorFromResponse($response, $subscriber);
  102. return Mailer::formatMailerErrorResult($error);
  103. }
  104. return Mailer::formatMailerSendSuccessResult();
  105. }
  106. public function getBody($newsletter, $subscriber, $extraParams = []) {
  107. $this->message = $this->createMessage($newsletter, $subscriber, $extraParams);
  108. $body = [
  109. 'Action' => 'SendRawEmail',
  110. 'Version' => '2010-12-01',
  111. 'Source' => $this->sender['from_name_email'],
  112. 'RawMessage.Data' => $this->encodeMessage($this->message),
  113. ];
  114. return $body;
  115. }
  116. public function createMessage($newsletter, $subscriber, $extraParams = []) {
  117. $message = (new Swift_Message())
  118. ->setTo($this->processSubscriber($subscriber))
  119. ->setFrom([
  120. $this->sender['from_email'] => $this->sender['from_name'],
  121. ])
  122. ->setSender($this->sender['from_email'])
  123. ->setReplyTo([
  124. $this->replyTo['reply_to_email'] => $this->replyTo['reply_to_name'],
  125. ])
  126. ->setReturnPath($this->returnPath)
  127. ->setSubject($newsletter['subject']);
  128. if (!empty($extraParams['unsubscribe_url'])) {
  129. $headers = $message->getHeaders();
  130. $headers->addTextHeader('List-Unsubscribe', '<' . $extraParams['unsubscribe_url'] . '>');
  131. }
  132. if (!empty($newsletter['body']['html'])) {
  133. $message = $message->setBody($newsletter['body']['html'], 'text/html');
  134. }
  135. if (!empty($newsletter['body']['text'])) {
  136. $message = $message->addPart($newsletter['body']['text'], 'text/plain');
  137. }
  138. return $message;
  139. }
  140. public function encodeMessage(Swift_Message $message) {
  141. return base64_encode($message->toString());
  142. }
  143. public function processSubscriber($subscriber) {
  144. preg_match('!(?P<name>.*?)\s<(?P<email>.*?)>!', $subscriber, $subscriberData);
  145. if (!isset($subscriberData['email'])) {
  146. $subscriberData = [
  147. 'email' => $subscriber,
  148. ];
  149. }
  150. return [
  151. $subscriberData['email'] =>
  152. (isset($subscriberData['name'])) ? $subscriberData['name'] : '',
  153. ];
  154. }
  155. public function request($newsletter, $subscriber, $extraParams = []) {
  156. $body = array_map('urlencode', $this->getBody($newsletter, $subscriber, $extraParams));
  157. return [
  158. 'timeout' => 10,
  159. 'httpversion' => '1.1',
  160. 'method' => 'POST',
  161. 'headers' => [
  162. 'Host' => $this->awsEndpoint,
  163. 'Authorization' => $this->signRequest($body),
  164. 'X-Amz-Date' => $this->date,
  165. ],
  166. 'body' => urldecode(http_build_query($body, '', '&')),
  167. ];
  168. }
  169. public function signRequest($body) {
  170. $stringToSign = $this->createStringToSign(
  171. $this->getCredentialScope(),
  172. $this->getCanonicalRequest($body)
  173. );
  174. $signature = hash_hmac(
  175. $this->hashAlgorithm,
  176. $stringToSign,
  177. $this->getSigningKey()
  178. );
  179. return sprintf(
  180. '%s Credential=%s/%s, SignedHeaders=host;x-amz-date, Signature=%s',
  181. $this->awsSigningAlgorithm,
  182. $this->awsAccessKey,
  183. $this->getCredentialScope(),
  184. $signature);
  185. }
  186. public function getCredentialScope() {
  187. return sprintf(
  188. '%s/%s/%s/%s',
  189. $this->dateWithoutTime,
  190. $this->awsRegion,
  191. $this->awsService,
  192. $this->awsTerminationString);
  193. }
  194. public function getCanonicalRequest($body) {
  195. return implode("\n", [
  196. 'POST',
  197. '/',
  198. '',
  199. 'host:' . $this->awsEndpoint,
  200. 'x-amz-date:' . $this->date,
  201. '',
  202. 'host;x-amz-date',
  203. hash($this->hashAlgorithm, urldecode(http_build_query($body, '', '&'))),
  204. ]);
  205. }
  206. public function createStringToSign($credentialScope, $canonicalRequest) {
  207. return implode("\n", [
  208. $this->awsSigningAlgorithm,
  209. $this->date,
  210. $credentialScope,
  211. hash($this->hashAlgorithm, $canonicalRequest),
  212. ]);
  213. }
  214. public function getSigningKey() {
  215. $dateKey = hash_hmac(
  216. $this->hashAlgorithm,
  217. $this->dateWithoutTime,
  218. 'AWS4' . $this->awsSecretKey,
  219. true
  220. );
  221. $regionKey = hash_hmac(
  222. $this->hashAlgorithm,
  223. $this->awsRegion,
  224. $dateKey,
  225. true
  226. );
  227. $serviceKey = hash_hmac(
  228. $this->hashAlgorithm,
  229. $this->awsService,
  230. $regionKey,
  231. true
  232. );
  233. return hash_hmac(
  234. $this->hashAlgorithm,
  235. $this->awsTerminationString,
  236. $serviceKey,
  237. true
  238. );
  239. }
  240. }