diff --git a/assets/js/src/cron.jsx b/assets/js/src/cron.jsx index 82cb4e267d..435a66ab11 100644 --- a/assets/js/src/cron.jsx +++ b/assets/js/src/cron.jsx @@ -15,10 +15,10 @@ define( status: 'loading' }; }, - getDaemonData: function() { + getCronData: function() { MailPoet.Ajax.post({ endpoint: 'cron', - action: 'getDaemonStatus' + action: 'getStatus' }) .done(function(response) { jQuery('.button-primary') @@ -32,25 +32,23 @@ define( }, componentDidMount: function() { if(this.isMounted()) { - this.getDaemonData(); - setInterval(this.getDaemonData, 5000); + this.getCronData(); + setInterval(this.getCronData, 5000); } }, - controlDaemon: function(action) { + controlCron: function(action) { + if (jQuery('.button-primary').hasClass('disabled')) { + return; + } jQuery('.button-primary') .addClass('disabled'); MailPoet.Ajax.post({ endpoint: 'cron', - action: 'controlDaemon', - data: { - 'action': action - } + action: action, }) .done(function(response) { if(!response.result) { - //this.replaceState(); - } else { - //this.setState(response); + MailPoet.Notice.error(MailPoetI18n.daemonControlError); } }.bind(this)); }, @@ -71,19 +69,25 @@ define( {this.state.counter} times (once every 30 seconds, unless it was interrupted and restarted).

- Stop   - Pause + Stop + + ); + break; + case 'starting': + case 'stopping': + return( +
+ Daemon is {this.state.status}
); break; - case 'paused': case 'stopped': return(
Daemon is {this.state.status}

- Start + Start
); break; diff --git a/assets/js/src/newsletters/send.jsx b/assets/js/src/newsletters/send.jsx index 29952d8f81..94a3534917 100644 --- a/assets/js/src/newsletters/send.jsx +++ b/assets/js/src/newsletters/send.jsx @@ -16,7 +16,7 @@ define( Breadcrumb ) { - var settings = window.mailpoet_settings || {}; + var settings = window.mailpoet_settings || {}; var fields = [ { @@ -24,14 +24,17 @@ define( label: 'Subject line', tip: "Be creative! It's the first thing your subscribers see."+ "Tempt them to open your email.", - type: 'text' + type: 'text', + validation: { + 'data-parsley-required': true + } }, { name: 'segments', - label: 'Lists', - tip: "The subscriber list that will be used for this campaign.", + label: 'Segments', + tip: "The subscriber segment that will be used for this campaign.", type: 'selection', - placeholder: "Select a list", + placeholder: "Select a segment", id: "mailpoet_segments", endpoint: "segments", multiple: true, @@ -111,12 +114,19 @@ define( action: 'add', data: { newsletter_id: this.props.params.id, - segments: jQuery('#mailpoet_segments').val() + segments: jQuery('#mailpoet_segments').val(), + sender: { + 'name': jQuery('#mailpoet_newsletter [name="sender_name"]').val(), + 'address': jQuery('#mailpoet_newsletter [name="sender_address"]').val() + }, + reply_to: { + 'name': jQuery('#mailpoet_newsletter [name="reply_to_name"]').val(), + 'address': jQuery('#mailpoet_newsletter [name="reply_to_address"]').val() + } } }).done(function(response) { if(response.result === true) { this.history.pushState(null, '/'); - MailPoet.Notice.success( 'The newsletter is being sent...' ); diff --git a/lib/Config/Initializer.php b/lib/Config/Initializer.php index a29e978616..df7bbdee4f 100644 --- a/lib/Config/Initializer.php +++ b/lib/Config/Initializer.php @@ -75,7 +75,7 @@ class Initializer { define('MP_SUBSCRIBER_CUSTOM_FIELD_TABLE', $subscriber_custom_field); define('MP_NEWSLETTER_OPTION_FIELDS_TABLE', $newsletter_option_fields); define('MP_NEWSLETTER_OPTION_TABLE', $newsletter_option); - define('MP_SENDING_QUEUE_TABLE', $sending_queues); + define('MP_SENDING_QUEUES_TABLE', $sending_queues); define('MP_NEWSLETTER_STATISTICS_TABLE', $newsletter_statistics); } @@ -113,7 +113,6 @@ class Initializer { } function setupAnalytics() { - $widget = new Analytics(); $widget->init(); } @@ -143,13 +142,15 @@ class Initializer { } function runQueueSupervisor() { + if (php_sapi_name() === 'cli') return; try { $supervisor = new Supervisor(); $supervisor->checkDaemon(); - } catch (\Exception $e) {} + } catch (\Exception $e) { + } } function setupImages() { add_image_size('mailpoet_newsletter_max', 1320); } -} +} \ No newline at end of file diff --git a/lib/Config/PublicAPI.php b/lib/Config/PublicAPI.php index 91344bf4b2..39ea81e906 100644 --- a/lib/Config/PublicAPI.php +++ b/lib/Config/PublicAPI.php @@ -8,14 +8,14 @@ if(!defined('ABSPATH')) exit; class PublicAPI { function __construct() { - # http://example.com/?mailpoet-api§ion=&action=&payload= + # http://example.com/?mailpoet-api§ion=&action=&request_payload= $this->api = isset($_GET['mailpoet-api']) ? true : false; $this->section = isset($_GET['section']) ? $_GET['section'] : false; $this->action = isset($_GET['action']) ? Helpers::underscoreToCamelCase($_GET['action']) : false; - $this->payload = isset($_GET['payload']) ? - json_decode(urldecode($_GET['payload']), true) : + $this->requestPayload = isset($_GET['request_payload']) ? + json_decode(urldecode($_GET['request_payload']), true) : false; } @@ -26,10 +26,9 @@ class PublicAPI { function queue() { try { - $queue = new Daemon($this->payload); + $queue = new Daemon($this->requestPayload); $this->_checkAndCallMethod($queue, $this->action); } catch(\Exception $e) { - // mailer configuration error } } diff --git a/lib/Cron/Daemon.php b/lib/Cron/Daemon.php index 9320dbcff5..e5309e0d9e 100644 --- a/lib/Cron/Daemon.php +++ b/lib/Cron/Daemon.php @@ -10,18 +10,18 @@ require_once(ABSPATH . 'wp-includes/pluggable.php'); if(!defined('ABSPATH')) exit; class Daemon { - function __construct($payload = array()) { + function __construct($requestPayload = array()) { set_time_limit(0); ignore_user_abort(); list ($this->daemon, $this->daemonData) = $this->getDaemon(); $this->refreshedToken = $this->refreshToken(); - $this->payload = $payload; + $this->requestPayload = $requestPayload; $this->timer = microtime(true); } function start() { - if(!isset($this->payload['session'])) { - $this->abortWithError('missing session ID'); + if(!isset($this->requestPayload['session'])) { + $this->abortWithError(__('Missing session ID.')); } $this->manageSession('start'); $daemon = $this->daemon; @@ -30,58 +30,63 @@ class Daemon { $daemon = Setting::create(); $daemon->name = 'cron_daemon'; $daemonData = array( - 'status' => null, + 'status' => 'starting', 'counter' => 0 ); $daemon->value = json_encode($daemonData); $daemon->save(); } - if($daemonData['status'] !== 'started') { + if($daemonData['status'] === 'started') { + $_SESSION['cron_daemon'] = array( + 'result' => false, + 'errors' => array(__('Daemon already running.')) + ); + } + if($daemonData['status'] === 'starting') { $_SESSION['cron_daemon'] = 'started'; + $_SESSION['cron_daemon'] = array('result' => true); $daemonData['status'] = 'started'; $daemonData['token'] = $this->refreshedToken; - $_SESSION['cron_daemon'] = array('result' => true); $this->manageSession('end'); $daemon->value = json_encode($daemonData); $daemon->save(); $this->callSelf(); - } else { - $_SESSION['cron_daemon'] = array( - 'result' => false, - 'error' => 'already started' - ); } $this->manageSession('end'); } function run() { - if(!$this->daemon || $this->daemonData['status'] !== 'started') { - $this->abortWithError('not running'); + $allowedStatuses = array( + 'stopping', + 'starting', + 'started' + ); + if(!$this->daemon || !in_array($this->daemonData['status'], $allowedStatuses)) { + $this->abortWithError(__('Invalid daemon status.')); } - if(!isset($this->payload['token']) || - $this->payload['token'] !== $this->daemonData['token'] + if(!isset($this->requestPayload['token']) || + $this->requestPayload['token'] !== $this->daemonData['token'] ) { - $this->abortWithError('invalid token'); + $this->abortWithError('Invalid token.'); } - try { $sendingQueue = new SendingQueue($this->timer); $sendingQueue->process(); } catch(Exception $e) { } - $elapsedTime = microtime(true) - $this->timer; if($elapsedTime < 30) { sleep(30 - $elapsedTime); } - // after each execution, read daemon in case it's status was modified list($daemon, $daemonData) = $this->getDaemon(); - $daemonData['counter']++; + if($daemonData['status'] === 'stopping') $daemonData['status'] = 'stopped'; + if($daemonData['status'] === 'starting') $daemonData['status'] = 'started'; $daemonData['token'] = $this->refreshedToken; + $daemonData['counter']++; $daemon->value = json_encode($daemonData); $daemon->save(); - if($daemonData['status'] === 'strated') $this->callSelf(); + if($daemonData['status'] === 'started') $this->callSelf(); } function getDaemon() { @@ -99,24 +104,23 @@ class Daemon { function manageSession($action) { switch($action) { - case 'start': - if(session_id()) { - session_write_close(); - } - session_id($this->payload['session']); - session_start(); - break; - case 'end': + case 'start': + if(session_id()) { session_write_close(); - break; + } + session_id($this->requestPayload['session']); + session_start(); + break; + case 'end': + session_write_close(); + break; } } function callSelf() { $payload = json_encode(array('token' => $this->refreshedToken)); - Supervisor::getRemoteUrl( - '/?mailpoet-api§ion=queue&action=run&payload=' . urlencode($payload) - + Supervisor::accessRemoteUrl( + '/?mailpoet-api§ion=queue&action=run&request_payload=' . urlencode($payload) ); exit; } @@ -125,7 +129,7 @@ class Daemon { wp_send_json( array( 'result' => false, - 'error' => $error + 'errors' => array($error) )); exit; } diff --git a/lib/Cron/Supervisor.php b/lib/Cron/Supervisor.php index eae5e2b263..e852ff627b 100644 --- a/lib/Cron/Supervisor.php +++ b/lib/Cron/Supervisor.php @@ -11,7 +11,7 @@ class Supervisor { function __construct($forceStart = false) { $this->forceStart = $forceStart; if(!Env::isPluginActivated()) { - throw new \Exception('Database has not been configured.'); + throw new \Exception(__('MailPoet is not activated.')); } list ($this->daemon, $this->daemonData) = $this->getDaemon(); } @@ -20,17 +20,24 @@ class Supervisor { if(!$this->daemon) { return $this->startDaemon(); } - if(!$this->forceStart && $this->daemonData['status'] === 'stopped') { - return; + if(!$this->forceStart && ( + $this->daemonData['status'] === 'stopped' || + $this->daemonData['status'] === 'stopping') + ) { + return $this->daemonData['status']; } - $currentTime = Carbon::now('UTC'); - $lastUpdateTime = Carbon::createFromFormat( - 'Y-m-d H:i:s', - $this->daemon->updated_at, 'UTC' - ); - $timeSinceLastStart = $currentTime->diffInSeconds($lastUpdateTime); - if($timeSinceLastStart < 40) return; - $this->daemonData['status'] = null; + $timeSinceLastRun = $this->getDaemonLastRunTime(); + if($timeSinceLastRun < 40) { + if(!$this->forceStart) { + return; + } + if($this->daemonData['status'] === 'stopping' || + $this->daemonData['status'] === 'starting' + ) { + return $this->daemonData['status']; + } + } + $this->daemonData['status'] = 'starting'; $this->daemon->value = json_encode($this->daemonData); $this->daemon->save(); return $this->startDaemon(); @@ -41,9 +48,9 @@ class Supervisor { $sessionId = session_id(); session_write_close(); $_SESSION['cron_daemon'] = null; - $payload = json_encode(array('session' => $sessionId)); - self::getRemoteUrl( - '/?mailpoet-api§ion=queue&action=start&payload=' . urlencode($payload) + $requestPayload = json_encode(array('session' => $sessionId)); + self::accessRemoteUrl( + '/?mailpoet-api§ion=queue&action=start&request_payload=' . urlencode($requestPayload) ); session_start(); $daemonStatus = $_SESSION['cron_daemon']; @@ -62,10 +69,10 @@ class Supervisor { ); } - static function getRemoteUrl($url) { + static function accessRemoteUrl($url) { $args = array( 'timeout' => 1, - 'user-agent' => 'MailPoet (www.mailpoet.com)' + 'user-agent' => 'MailPoet (www.mailpoet.com) Cron' ); wp_remote_get( self::getSiteUrl() . $url, @@ -74,11 +81,28 @@ class Supervisor { } static function getSiteUrl() { - if(preg_match('!:\d+/!', site_url())) return site_url(); - preg_match('!http://(?P.*?):(?P\d+)!', site_url(), $server); + // additional check for some sites running on a virtual machine or behind + // proxy where there could be different ports (e.g., host:8080 => guest:80) + + // if the site URL does not contain a port, return the URL + if(!preg_match('!^https?://.*?:\d+!', site_url())) return site_url(); + preg_match('!://(?P.*?):(?P\d+)!', site_url(), $server); + // connect to the URL with port $fp = @fsockopen($server['host'], $server['port'], $errno, $errstr, 1); - return ($fp) ? - site_url() : - preg_replace('/(?=:\d+):\d+/', '$1', site_url()); + if($fp) return site_url(); + // connect to the URL without port + $fp = @fsockopen($server['host'], $server['port'], $errno, $errstr, 1); + if($fp) return preg_replace('!(?=:\d+):\d+!', '$1', site_url()); + // throw an error if all connections fail + throw new \Exception(__('Site URL is unreachable.')); + } + + function getDaemonLastRunTime() { + $currentTime = Carbon::now('UTC'); + $lastUpdateTime = Carbon::createFromFormat( + 'Y-m-d H:i:s', + $this->daemon->updated_at, 'UTC' + ); + return $currentTime->diffInSeconds($lastUpdateTime); } } \ No newline at end of file diff --git a/lib/Cron/Workers/SendingQueue.php b/lib/Cron/Workers/SendingQueue.php index 7060b180b7..f41fb5aed8 100644 --- a/lib/Cron/Workers/SendingQueue.php +++ b/lib/Cron/Workers/SendingQueue.php @@ -1,11 +1,11 @@ whereNull('deleted_at') - ->whereNull('status') - ->findResultSet(); - foreach($queues as $queue) { - $newsletter = Newsletter::findOne($queue->newsletter_id); + foreach($this->getQueues() as $queue) { + $newsletter = Newsletter::findOne($queue->newsletter_id) + ->asArray(); if(!$newsletter) { continue; }; - $newsletter = $newsletter->asArray(); - $mailer = new Mailer($httpRequest = false); - if(!empty($newsletter['sender_address']) && - !empty($newsletter['sender_name']) - ) { - $mailer->fromName = $newsletter['sender_name']; - $mailer->fromEmail = $newsletter['sender_address']; - $mailer->fromNameEmail = sprintf( - '%s <%s>', - $mailer->fromName, - $mailer->fromEmail - ); - } - if(!empty($newsletter['reply_to_address']) && - !empty($newsletter['reply_to_name']) - ) { - $mailer->replyToName = $newsletter['reply_to_name']; - $mailer->replyToEmail = $newsletter['reply_to_address']; - $mailer->replyToNameEmail = sprintf( - '%s <%s>', - $mailer->replyToName, - $mailer->replyToEmail - ); - } - $mailer->mailer = $mailer->buildMailer(); - $renderer = new Renderer(json_decode($newsletter['body'], true)); - $newsletter = array( - 'subject' => $newsletter['subject'], - 'id' => $newsletter['id'], - 'body' => array( - 'html' => $renderer->renderAll(), - 'text' => '' - // TODO: add text body - ) - ); + $newsletter = $this->renderNewsletter($newsletter); + $mailer = $this->configureMailerForNewsletter($newsletter); $subscribers = json_decode($queue->subscribers, true); $subscribersToProcess = $subscribers['to_process']; - if(!isset($subscribers['failed'])) $subscribers['failed'] = array(); if(!isset($subscribers['processed'])) $subscribers['processed'] = array(); + if(!isset($subscribers['failed'])) $subscribers['failed'] = array(); foreach(array_chunk($subscribersToProcess, 200) as $subscriberIds) { $dbSubscribers = Subscriber::whereIn('id', $subscriberIds) ->findArray(); - foreach($dbSubscribers as $i => $dbSubscriber) { + foreach($dbSubscribers as $dbSubscriber) { $this->checkExecutionTimer(); - // TODO: replace shortcodes in the newsletter - $result = $mailer->mailer->send( - $newsletter, - $mailer->transformSubscriber($dbSubscriber) - ); - $newsletterStatistics = NewsletterStatistics::create(); - $newsletterStatistics->subscriber_id = $dbSubscriber['id']; - $newsletterStatistics->newsletter_id = $newsletter['id']; - $newsletterStatistics->queue_id = $queue->id; - $newsletterStatistics->save(); + $result = $this->sendNewsletter( + $mailer, + $this->processNewsletter($newsletter), + $dbSubscriber); if($result) { + $this->updateStatistics($newsletter['id'], $dbSubscriber['id'], $queue->id); $subscribers['processed'][] = $dbSubscriber['id']; - } else { - $subscribers['failed'][] = $dbSubscriber['id']; - } - $subscribers['to_process'] = array_values( - array_diff( - $subscribers['to_process'], - array_merge($subscribers['processed'], $subscribers['failed']) - ) - ); - $queue->count_processed = - count($subscribers['processed']) + count($subscribers['failed']); - $queue->count_to_process = count($subscribers['to_process']); - $queue->count_failed = count($subscribers['failed']); - $queue->count_total = - $queue->count_processed + $queue->count_to_process; - if(!$queue->count_to_process) { - $queue->processed_at = date('Y-m-d H:i:s'); - $queue->status = 'completed'; - } - $queue->subscribers = json_encode($subscribers); - $queue->save(); + } else $subscribers['failed'][] = $dbSubscriber['id']; + $this->updateQueue($queue, $subscribers); } } } } + function processNewsletter($newsletter) { + // TODO: replace shortcodes, etc.. + return $newsletter; + } + + function sendNewsletter($mailer, $newsletter, $subscriber) { + return $mailer->mailerInstance->send( + $newsletter, + $mailer->transformSubscriber($subscriber) + ); + } + + function updateStatistics($newsletterId, $subscriberId, $queueId) { + $newsletterStatistics = NewsletterStatistics::create(); + $newsletterStatistics->subscriber_id = $newsletterId; + $newsletterStatistics->newsletter_id = $subscriberId; + $newsletterStatistics->queue_id = $queueId; + $newsletterStatistics->save(); + } + + function updateQueue($queue, $subscribers) { + $subscribers['to_process'] = array_values( + array_diff( + $subscribers['to_process'], + array_merge($subscribers['processed'], $subscribers['failed']) + ) + ); + $queue->count_processed = + count($subscribers['processed']) + count($subscribers['failed']); + $queue->count_to_process = count($subscribers['to_process']); + $queue->count_failed = count($subscribers['failed']); + $queue->count_total = + $queue->count_processed + $queue->count_to_process; + if(!$queue->count_to_process) { + $queue->processed_at = date('Y-m-d H:i:s'); + $queue->status = 'completed'; + } + $queue->subscribers = json_encode($subscribers); + $queue->save(); + } + + function configureMailerForNewsletter($newsletter) { + if(!empty($newsletter['sender_address']) && !empty($newsletter['sender_name'])) { + $sender = array( + 'name' => $newsletter['sender_name'], + 'address' => $newsletter['sender_address'] + ); + } else $sender = false; + if(!empty($newsletter['reply_to_address']) && !empty($newsletter['reply_to_name'])) { + $replyTo = array( + 'name' => $newsletter['reply_to_name'], + 'address' => $newsletter['reply_to_address'] + ); + } else $replyTo = false; + $mailer = new Mailer($method = false, $sender, $replyTo); + return $mailer; + } + function checkExecutionTimer() { $elapsedTime = microtime(true) - $this->timer; - if($elapsedTime >= 28) throw new \Exception('Maximum execution time reached.'); + if($elapsedTime >= 30) throw new \Exception('Maximum execution time reached.'); + } + + function getQueues() { + return \MailPoet\Models\SendingQueue::orderByDesc('priority') + ->whereNull('deleted_at') + ->whereNull('status') + ->findResultSet(); + } + + function renderNewsletter($newsletter) { + $renderer = new Renderer(json_decode($newsletter['body'], true)); + $newsletter['body'] = $renderer->renderAll(); + return $newsletter; } } \ No newline at end of file diff --git a/lib/Mailer/Mailer.php b/lib/Mailer/Mailer.php new file mode 100644 index 0000000000..961711a2d8 --- /dev/null +++ b/lib/Mailer/Mailer.php @@ -0,0 +1,141 @@ +mailer = $this->getMailer($mailer); + $this->sender = $this->getSender($sender); + $this->replyTo = $this->getReplyTo($reply_to); + $this->mailerInstance = $this->buildMailer(); + } + + function send($newsletter, $subscriber) { + $subscriber = $this->transformSubscriber($subscriber); + return $this->mailerInstance->send($newsletter, $subscriber); + } + + function buildMailer() { + switch($this->mailer['method']) { + case 'AmazonSES': + $mailerInstance = new $this->mailer['class']( + $this->mailer['region'], + $this->mailer['access_key'], + $this->mailer['secret_key'], + $this->sender['fromNameEmail'] + ); + break; + case 'ElasticEmail': + $mailerInstance = new $this->mailer['class']( + $this->mailer['api_key'], + $this->sender['fromEmail'], + $this->sender['fromName'] + ); + break; + case 'MailGun': + $mailerInstance = new $this->mailer['class']( + $this->mailer['domain'], + $this->mailer['api_key'], + $this->sender['fromNameEmail'] + ); + break; + case 'MailPoet': + $mailerInstance = new $this->mailer['class']( + $this->mailer['mailpoet_api_key'], + $this->sender['fromEmail'], + $this->sender['fromName'] + ); + break; + case 'Mandrill': + $mailerInstance = new $this->mailer['class']( + $this->mailer['api_key'], + $this->sender['fromEmail'], + $this->sender['fromName'] + ); + break; + case 'SendGrid': + $mailerInstance = new $this->mailer['class']( + $this->mailer['api_key'], + $this->sender['fromEmail'], + $this->sender['fromName'] + ); + break; + case 'WPMail': + $mailerInstance = new $this->mailer['class']( + $this->sender['fromEmail'], + $this->sender['fromName'] + ); + break; + case 'SMTP': + $mailerInstance = new $this->mailer['class']( + $this->mailer['host'], + $this->mailer['port'], + $this->mailer['authentication'], + $this->mailer['login'], + $this->mailer['password'], + $this->mailer['encryption'], + $this->sender['fromEmail'], + $this->sender['fromName'] + ); + break; + default: + throw new \Exception(__('Mailing method does not exist.')); + break; + } + return $mailerInstance; + } + + function getMailer($mailer = false) { + if(!$mailer) { + $mailer = Setting::getValue('mta', null); + if(!$mailer || !isset($mailer['method'])) throw new \Exception(__('Mailer is not configured.')); + } + $mailer['class'] = 'MailPoet\\Mailer\\Methods\\' . $mailer['method']; + return $mailer; + } + + function getSender($sender = false) { + if(!$sender) { + $sender = Setting::getValue('sender', null); + if(!$sender) throw new \Exception(__('Sender name and email are not configured.')); + } + return array( + 'fromName' => $sender['name'], + 'fromEmail' => $sender['address'], + 'fromNameEmail' => sprintf('%s <%s>', $sender['name'], $sender['address']) + ); + } + + function getReplyTo($replyTo = false) { + if(!$replyTo) { + $replyTo = Setting::getValue('replyTo', null); + if(!$replyTo) { + $replyTo = array( + 'name' => $this->sender['fromName'], + 'address' => $this->sender['fromEmail'] + ); + } + } + return array( + 'replyToName' => $replyTo['name'], + 'replyToEmail' => $replyTo['address'], + 'replyToNameEmail' => sprintf('%s <%s>', $replyTo['name'], $replyTo['address']) + ); + } + + function transformSubscriber($subscriber) { + if(!is_array($subscriber)) return $subscriber; + if(isset($subscriber['address'])) $subscriber['email'] = $subscriber['address']; + $first_name = (isset($subscriber['first_name'])) ? $subscriber['first_name'] : ''; + $last_name = (isset($subscriber['last_name'])) ? $subscriber['last_name'] : ''; + if(!$first_name && !$last_name) return $subscriber['email']; + $subscriber = sprintf('%s %s <%s>', $first_name, $last_name, $subscriber['email']); + $subscriber = trim(preg_replace('!\s\s+!', ' ', $subscriber)); + return $subscriber; + } +} \ No newline at end of file diff --git a/lib/Mailer/API/AmazonSES.php b/lib/Mailer/Methods/AmazonSES.php similarity index 98% rename from lib/Mailer/API/AmazonSES.php rename to lib/Mailer/Methods/AmazonSES.php index 08e678a930..4cbd969257 100644 --- a/lib/Mailer/API/AmazonSES.php +++ b/lib/Mailer/Methods/AmazonSES.php @@ -1,5 +1,5 @@ $supervisor->checkDaemon() - ) - ); - exit; - break; - case 'stop': - $status = 'stopped'; - break; - default: - $status = 'paused'; - break; - } - $daemon = new \MailPoet\Cron\Daemon(); - if(!$daemon->daemon || $daemon->daemonData['status'] !== 'started') { + function start() { + $supervisor = new Supervisor($forceStart = true); + wp_send_json( + array( + 'result' => $supervisor->checkDaemon() ? true : false + ) + ); + } + + function stop() { + $daemon = new Daemon(); + if(!$daemon->daemon || + $daemon->daemonData['status'] !== 'started' + ) { $result = false; } else { - $daemon->daemonData['status'] = $status; + $daemon->daemonData['status'] = 'stopping'; $daemon->daemon->value = json_encode($daemon->daemonData); $result = $daemon->daemon->save(); } @@ -41,153 +34,8 @@ class Cron { ); } - function getDaemonStatus() { + function getStatus() { $daemon = new \MailPoet\Cron\BootStrapMenu(); wp_send_json($daemon->bootStrap()); } - - function addQueue($data) { - $queue = SendingQueue::where('newsletter_id', $data['newsletter_id']) - ->whereNull('status') - ->findArray(); - - !d($queue); - exit; - $queue = SendingQueue::create(); - - $queue->newsletter_id = $data['newsletter_id']; - - - $subscriber_ids = array(); - $segments = Segment::whereIn('id', $data['segments']) - ->findMany(); - foreach($segments as $segment) { - $subscriber_ids = array_merge($subscriber_ids, Helpers::arrayColumn( - $segment->subscribers() - ->findArray(), - 'id' - )); - } - - $subscriber_ids = array_unique($subscriber_ids); - $queue->subscribers = json_encode( - array( - 'to_process' => $subscriber_ids - ) - ); - - $queue->count_total = $queue->count_to_process = count($subscriber_ids); - $queue->save(); - wp_send_json( - !$queue->save() ? - array( - 'result' => false, - 'error' => 'Queue could not be created.' - ) : - array( - 'result' => true, - 'data' => array($queue->id) - ) - ); - } - - function addQueues($data) { - $result = array_map(function ($queueData) { - $queue = SendingQueue::create(); - $queue->newsletter_id = $queueData['newsletter_id']; - $queue->subscribers = json_encode( - array( - 'to_process' => $queueData['subscribers'] - ) - ); - $queue->count_total = $queue->count_to_process = count($queueData['subscribers']); - $queue->save(); - return array( - 'newsletter_id' => $queue->newsletter_id, - 'queue_id' => $queue->id - ); - }, $data); - $result = Helpers::arrayColumn($result, 'queue_id', 'newsletter_id'); - wp_send_json( - count($data) != count($result) ? - array( - 'result' => false, - 'error' => __('Some queues could not be created.'), - 'data' => $result - ) : - array( - 'result' => true, - 'data' => $result - ) - ); - } - - function deleteQueue($data) { - $queue = SendingQueue::whereNull('deleted_at') - ->findOne($data['queue_id']); - if(!$queue) { - wp_send_json( - array( - 'result' => false, - 'error' => __('Queue not found.') - ) - ); - } - $queue->deleted_at = 'Y-m-d H:i:s'; - $queue->save(); - wp_send_json(array('result' => true)); - } - - function deleteQueues($data) { - $queues = SendingQueue::whereNull('deleted_at') - ->whereIn('id', $data['queue_ids']) - ->findResultSet(); - if(!$queues->count()) { - wp_send_json( - array( - 'result' => false, - 'error' => __('Queues not found.') - ) - ); - } - foreach($queues as $queue) { - $queue->deleted_at = 'Y-m-d H:i:s'; - $queue->save(); - } - wp_send_json(array('result' => true)); - } - - function getQueueStatus($data) { - $queue = SendingQueue::whereNull('deleted_at') - ->findOne($data['queue_id']) - ->asArray(); - wp_send_json( - !$queue ? - array( - 'result' => false, - 'error' => __('Queue not found.') - ) : - array( - 'result' => true, - 'data' => $queue - ) - ); - } - - function getQueuesStatus($data) { - $queues = SendingQueue::whereNull('deleted_at') - ->whereIn('id', $data['queue_ids']) - ->findArray(); - wp_send_json( - !$queues ? - array( - 'result' => false, - 'error' => __('Queue not found.') - ) : - array( - 'result' => true, - 'data' => $queues - ) - ); - } } \ No newline at end of file diff --git a/lib/Router/Mailer.php b/lib/Router/Mailer.php index 490417c592..248c8da98a 100644 --- a/lib/Router/Mailer.php +++ b/lib/Router/Mailer.php @@ -1,191 +1,20 @@ mailerType = array( - 'AmazonSES' => 'API', - 'ElasticEmail' => 'API', - 'MailGun' => 'API', - 'Mandrill' => 'API', - 'SendGrid' => 'API', - 'MailPoet' => null, - 'SMTP' => null, - 'WPMail' => null - ); - if(!$httpRequest) { - list($this->fromName, $this->fromEmail, $this->fromNameEmail) - = $this->getSetting('sender'); - $this->mailer = $this->getSetting('mailer'); - } - } - function send($data) { - $subscriber = $this->transformSubscriber($data['subscriber']); - list($fromName, $fromEmail, $fromNameEmail) - = $this->getSetting('sender'); - if(!$fromName && !$fromEmail) { - wp_send_json( - array( - 'result' => false, - 'errors' => array(__('Please configure your name and e-mail address.')) - ) - ); - } - $data['mailer']['class'] = 'MailPoet\\Mailer\\' . - (($this->mailerType[$data['mailer']['method']]) ? - $this->mailerType[$data['mailer']['method']] . '\\' . $data['mailer']['method'] : - $data['mailer']['method'] - ); - $mailer = $this->buildMailer( - $data['mailer'], - $fromName, - $fromEmail, - $fromNameEmail + $mailer = new \MailPoet\Mailer\Mailer( + (isset($data['mailer'])) ? $data['mailer'] : false, + (isset($data['sender'])) ? $data['sender'] : false, + (isset($data['reply_to'])) ? $data['reply_to'] : false ); - if(!empty($newsletter['sender_address']) && - !empty($newsletter['sender_name']) - ) { - $mailer->fromName = $newsletter['sender_name']; - $mailer->fromEmail = $newsletter['sender_address']; - $mailer->fromNameEmail = sprintf( - '%s <%s>', - $mailer->fromName, - $mailer->fromEmail - ); - } - if(!empty($newsletter['reply_to_address']) && - !empty($newsletter['reply_to_name']) - ) { - $mailer->replyToName = $newsletter['reply_to_name']; - $mailer->replyToEmail = $newsletter['reply_to_address']; - $mailer->replyToNameEmail = sprintf( - '%s <%s>', - $mailer->replyToName, - $mailer->replyToEmail - ); - } - $result = $mailer->send($data['newsletter'], $subscriber); + $result = $mailer->send($data['newsletter'], $data['subscriber']); wp_send_json( array( 'result' => ($result) ? true : false ) ); } - - function buildMailer($mailer = false, $fromName = false, $fromEmail = false, $fromNameEmail = false) { - if(!$mailer) $mailer = $this->mailer; - if(!$fromName) $fromName = $this->fromName; - if(!$fromEmail) $fromEmail = $this->fromEmail; - if(!$fromNameEmail) $fromNameEmail = $this->fromNameEmail; - switch($mailer['method']) { - case 'AmazonSES': - $mailerInstance = new $mailer['class']( - $mailer['region'], - $mailer['access_key'], - $mailer['secret_key'], - $fromNameEmail - ); - break; - case 'ElasticEmail': - $mailerInstance = new $mailer['class']( - $mailer['api_key'], - $fromEmail, $fromName - ); - break; - case 'MailGun': - $mailerInstance = new $mailer['class']( - $mailer['domain'], - $mailer['api_key'], - $fromNameEmail - ); - break; - case 'MailPoet': - $mailerInstance = new $mailer['class']( - $mailer['mailpoet_api_key'], - $fromEmail, - $fromName - ); - break; - case 'Mandrill': - $mailerInstance = new $mailer['class']( - $mailer['api_key'], - $fromEmail, $fromName - ); - break; - case 'SendGrid': - $mailerInstance = new $mailer['class']( - $mailer['api_key'], - $fromEmail, - $fromName - ); - break; - case 'WPMail': - $mailerInstance = new $mailer['class']( - $fromEmail, - $fromName - ); - break; - case 'SMTP': - $mailerInstance = new $mailer['class']( - $mailer['host'], - $mailer['port'], - $mailer['authentication'], - $mailer['login'], - $mailer['password'], - $mailer['encryption'], - $fromEmail, - $fromName - ); - break; - default: - throw new \Exception('Mailing method does not exist.'); - break; - } - return $mailerInstance; - } - - function transformSubscriber($subscriber) { - if(!is_array($subscriber)) return $subscriber; - if(isset($subscriber['address'])) $subscriber['email'] = $subscriber['address']; - $first_name = (isset($subscriber['first_name'])) ? $subscriber['first_name'] : ''; - $last_name = (isset($subscriber['last_name'])) ? $subscriber['last_name'] : ''; - if(!$first_name && !$last_name) return $subscriber['email']; - $subscriber = sprintf('%s %s <%s>', $first_name, $last_name, $subscriber['email']); - $subscriber = trim(preg_replace('!\s\s+!', ' ', $subscriber)); - return $subscriber; - } - - function getSetting($setting) { - switch($setting) { - case 'mailer': - $mailer = Setting::getValue('mta', null); - if(!$mailer || !isset($mailer['method'])) throw new \Exception('Mailing method is not configured.'); - $mailer['class'] = 'MailPoet\\Mailer\\' . - (($this->mailerType[$mailer['method']]) ? - $this->mailerType[$mailer['method']] . '\\' . $mailer['method'] : - $mailer['method'] - ); - return $mailer; - break; - case 'sender': - $sender = Setting::getValue($setting, null); - if(!$sender) throw new \Exception('Sender name and email are not configured.'); - return array( - $sender['name'], - $sender['address'], - sprintf('%s <%s>', $sender['name'], $sender['address']) - ); - break; - default: - return Setting::getValue($setting, null); - break; - } - } } \ No newline at end of file diff --git a/lib/Router/Queue.php b/lib/Router/Queue.php deleted file mode 100644 index c20eacd7f7..0000000000 --- a/lib/Router/Queue.php +++ /dev/null @@ -1,196 +0,0 @@ - $supervisor->checkDaemon() ? - true : - false - ) - ); - break; - case 'stop': - $status = 'stopped'; - break; - default: - $status = 'paused'; - break; - } - $daemon = new Daemon(); - if(!$daemon->daemon || $daemon->daemonData['status'] !== 'started') { - $result = false; - } else { - $daemon->daemonData['status'] = $status; - $daemon->daemon->value = json_encode($daemon->daemonData); - $result = $daemon->daemon->save(); - } - wp_send_json( - array( - 'result' => $result - ) - ); - } - - function getDaemonStatus() { - $daemon = new \MailPoet\Cron\BootStrapMenu(); - wp_send_json($daemon->bootStrap()); - } - - function addQueue($data) { - $queue = SendingQueue::where('newsletter_id', $data['newsletter_id']) - ->whereNull('status') - ->findArray(); - - !d($queue); - exit; - $queue = SendingQueue::create(); - - $queue->newsletter_id = $data['newsletter_id']; - - - $subscriber_ids = array(); - $segments = Segment::whereIn('id', $data['segments']) - ->findMany(); - foreach($segments as $segment) { - $subscriber_ids = array_merge($subscriber_ids, Helpers::arrayColumn( - $segment->subscribers() - ->findArray(), - 'id' - )); - } - - $subscriber_ids = array_unique($subscriber_ids); - $queue->subscribers = json_encode( - array( - 'to_process' => $subscriber_ids - ) - ); - - $queue->count_total = $queue->count_to_process = count($subscriber_ids); - $queue->save(); - wp_send_json( - !$queue->save() ? - array( - 'result' => false, - 'error' => 'Queue could not be created.' - ) : - array( - 'result' => true, - 'data' => array($queue->id) - ) - ); - } - - - - function addQueues($data) { - $result = array_map(function ($queueData) { - $queue = SendingQueue::create(); - $queue->newsletter_id = $queueData['newsletter_id']; - $queue->subscribers = json_encode( - array( - 'to_process' => $queueData['subscribers'] - ) - ); - $queue->count_total = $queue->count_to_process = count($queueData['subscribers']); - $queue->save(); - return array( - 'newsletter_id' => $queue->newsletter_id, - 'queue_id' => $queue->id - ); - }, $data); - $result = Helpers::arrayColumn($result, 'queue_id', 'newsletter_id'); - wp_send_json( - count($data) != count($result) ? - array( - 'result' => false, - 'error' => __('Some queues could not be created.'), - 'data' => $result - ) : - array( - 'result' => true, - 'data' => $result - ) - ); - } - - function deleteQueue($data) { - $queue = SendingQueue::whereNull('deleted_at') - ->findOne($data['queue_id']); - if(!$queue) { - wp_send_json( - array( - 'result' => false, - 'error' => __('Queue not found.') - ) - ); - } - $queue->deleted_at = 'Y-m-d H:i:s'; - $queue->save(); - wp_send_json(array('result' => true)); - } - - function deleteQueues($data) { - $queues = SendingQueue::whereNull('deleted_at') - ->whereIn('id', $data['queue_ids']) - ->findResultSet(); - if(!$queues->count()) { - wp_send_json( - array( - 'result' => false, - 'error' => __('Queues not found.') - ) - ); - } - foreach($queues as $queue) { - $queue->deleted_at = 'Y-m-d H:i:s'; - $queue->save(); - } - wp_send_json(array('result' => true)); - } - - function getQueueStatus($data) { - $queue = SendingQueue::whereNull('deleted_at') - ->findOne($data['queue_id']) - ->asArray(); - wp_send_json( - !$queue ? - array( - 'result' => false, - 'error' => __('Queue not found.') - ) : - array( - 'result' => true, - 'data' => $queue - ) - ); - } - - function getQueuesStatus($data) { - $queues = SendingQueue::whereNull('deleted_at') - ->whereIn('id', $data['queue_ids']) - ->findArray(); - wp_send_json( - !$queues ? - array( - 'result' => false, - 'error' => __('Queue not found.') - ) : - array( - 'result' => true, - 'data' => $queues - ) - ); - } -} \ No newline at end of file diff --git a/lib/Router/SendingQueue.php b/lib/Router/SendingQueue.php index 2078d4d190..d742211912 100644 --- a/lib/Router/SendingQueue.php +++ b/lib/Router/SendingQueue.php @@ -19,7 +19,6 @@ class SendingQueue { 'errors' => array($e->getMessage()) ) ); - exit; } $queue = \MailPoet\Models\SendingQueue::where('newsletter_id', $data['newsletter_id']) diff --git a/tests/unit/Mailer/MailerCest.php b/tests/unit/Mailer/MailerCest.php new file mode 100644 index 0000000000..ccc94b768f --- /dev/null +++ b/tests/unit/Mailer/MailerCest.php @@ -0,0 +1,100 @@ +sender = array( + 'name' => 'Sender', + 'address' => 'staff@mailinator.com' + ); + $this->replyTo = array( + 'name' => 'Reply To', + 'address' => 'staff@mailinator.com' + ); + $this->mailer = array( + 'method' => 'MailPoet', + 'mailpoet_api_key' => 'dhNSqj1XHkVltIliyQDvMiKzQShOA5rs0m_DdRUVZHU' + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing Mailer', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itRequiresMailerMethod() { + try { + $mailer = new Mailer(); + } catch (Exception $e) { + expect($e->getMessage())->equals('Mailer is not configured.'); + } + } + + function itRequiresSender() { + try { + $mailer = new Mailer($mailer = $this->mailer); + } catch (Exception $e) { + expect($e->getMessage())->equals('Sender name and email are not configured.'); + } + } + + function itCanConstruct() { + $mailer = new Mailer($this->mailer, $this->sender, $this->replyTo); + expect($mailer->sender['fromName'])->equals($this->sender['name']); + expect($mailer->sender['fromEmail'])->equals($this->sender['address']); + expect($mailer->replyTo['replyToName'])->equals($this->replyTo['name']); + expect($mailer->replyTo['replyToEmail'])->equals($this->replyTo['address']); + } + + function itCanBuildMailerInstance() { + $mailer = new Mailer($this->mailer, $this->sender); + expect(get_class($mailer->mailerInstance)) + ->equals('MailPoet\Mailer\Methods\MailPoet'); + } + + function itCanAbortWhenMethodDoesNotExist() { + try { + $mailer = new Mailer(array('method' => 'test'), $this->sender); + } catch (Exception $e) { + expect($e->getMessage())->equals('Mailing method does not exist.'); + } + } + + function itCanTransformSubscriber() { + $mailer = new Mailer($this->mailer, $this->sender, $this->replyTo); + expect($mailer->transformSubscriber('test@email.com')) + ->equals('test@email.com'); + expect($mailer->transformSubscriber( + array( + 'email' => 'test@email.com' + )) + )->equals('test@email.com'); + expect($mailer->transformSubscriber( + array( + 'first_name' => 'First', + 'email' => 'test@email.com' + )) + )->equals('First '); + expect($mailer->transformSubscriber( + array( + 'last_name' => 'Last', + 'email' => 'test@email.com' + )) + )->equals('Last '); + expect($mailer->transformSubscriber( + array( + 'first_name' => 'First', + 'last_name' => 'Last', + 'email' => 'test@email.com' + )) + )->equals('First Last '); + } + + function itCanSend() { + $mailer = new Mailer($this->mailer, $this->sender, $this->replyTo); + expect($mailer->send($this->newsletter, $this->subscriber))->true(); + } +} \ No newline at end of file diff --git a/tests/unit/Mailer/API/AmazonSESCest.php b/tests/unit/Mailer/Methods/AmazonSESCest.php similarity index 96% rename from tests/unit/Mailer/API/AmazonSESCest.php rename to tests/unit/Mailer/Methods/AmazonSESCest.php index 219ac64917..675b32d148 100644 --- a/tests/unit/Mailer/API/AmazonSESCest.php +++ b/tests/unit/Mailer/Methods/AmazonSESCest.php @@ -1,155 +1,154 @@ -settings = array( - 'method' => 'AmazonSES', - 'type' => 'API', - 'access_key' => 'AKIAJM6Y5HMGXBLDNSRA', - 'secret_key' => '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', - 'region' => 'us-east-1', - ); - $this->from = 'Sender '; - $this->mailer = new AmazonSES( - $this->settings['region'], - $this->settings['access_key'], - $this->settings['secret_key'], - $this->from); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing AmazonSES', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itsConstructorWorks() { - expect($this->mailer->awsEndpoint) - ->equals( - sprintf('email.%s.amazonaws.com', $this->settings['region']) - ); - expect($this->mailer->url) ->equals( - sprintf('https://email.%s.amazonaws.com', $this->settings['region']) - ); - expect(preg_match('!^\d{8}T\d{6}Z$!', $this->mailer->date))->equals(1); - expect(preg_match('!^\d{8}$!', $this->mailer->dateWithoutTime))->equals(1); - } - - function itCanGenerateBody() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - expect($body['Action'])->equals('SendEmail'); - expect($body['Version'])->equals('2010-12-01'); - expect($body['Source'])->equals($this->from); - expect($body['Destination.ToAddresses.member.1']) - ->contains($this->subscriber); - expect($body['Message.Subject.Data']) - ->equals($this->newsletter['subject']); - expect($body['Message.Body.Html.Data']) - ->equals($this->newsletter['body']['html']); - expect($body['Message.Body.Text.Data']) - ->equals($this->newsletter['body']['text']); - expect($body['ReturnPath'])->equals($this->from); - } - - function itCanCreateRequest() { - $request = $this->mailer->request($this->newsletter, $this->subscriber); - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - expect($request['timeout'])->equals(10); - expect($request['httpversion'])->equals('1.1'); - expect($request['method'])->equals('POST'); - expect($request['headers']['Host'])->equals($this->mailer->awsEndpoint); - expect($request['headers']['Authorization']) - ->equals($this->mailer->signRequest($body)); - expect($request['headers']['X-Amz-Date'])->equals($this->mailer->date); - expect($request['body'])->equals(urldecode(http_build_query($body))); - } - - function itCanCreateCanonicalRequest() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - $canonicalRequest = explode( - "\n", - $this->mailer->getCanonicalRequest($body) - ); - expect($canonicalRequest) - ->equals( - array( - 'POST', - '/', - '', - 'host:' . $this->mailer->awsEndpoint, - 'x-amz-date:' . $this->mailer->date, - '', - 'host;x-amz-date', - hash($this->mailer->hashAlgorithm, - urldecode(http_build_query($body)) - ) - ) - ); - } - - function itCanCreateCredentialScope() { - $credentialScope = $this->mailer->getCredentialScope(); - expect($credentialScope) - ->equals( - $this->mailer->dateWithoutTime . '/' . - $this->mailer->awsRegion . '/' . - $this->mailer->awsService . '/' . - $this->mailer->awsTerminationString - ); - } - - function itCanCreateStringToSign() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - $credentialScope = $this->mailer->getCredentialScope(); - $canonicalRequest = $this->mailer->getCanonicalRequest($body); - $stringToSing = $this->mailer->createStringToSign( - $credentialScope, - $canonicalRequest - ); - $stringToSing = explode("\n", $stringToSing); - expect($stringToSing) - ->equals( - array( - $this->mailer->awsSigningAlgorithm, - $this->mailer->date, - $credentialScope, - hash($this->mailer->hashAlgorithm, $canonicalRequest) - ) - ); - } - - function itCanSignRequest() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - $signedRequest = $this->mailer->signRequest($body); - expect($signedRequest) - ->contains( - $this->mailer->awsSigningAlgorithm . ' Credential=' . - $this->mailer->awsAccessKey . '/' . - $this->mailer->getCredentialScope() . ', ' . - 'SignedHeaders=host;x-amz-date, Signature=' - ); - expect(preg_match('!Signature=[A-Fa-f0-9]{64}$!', $signedRequest)) - ->equals(1); - } - - function itCannotSendWithoutProperAccessKey() { - $this->mailer->awsAccessKey = 'somekey'; - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCanSend() { - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->true(); - } -} +settings = array( + 'method' => 'AmazonSES', + 'access_key' => 'AKIAJM6Y5HMGXBLDNSRA', + 'secret_key' => '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', + 'region' => 'us-east-1', + ); + $this->from = 'Sender '; + $this->mailer = new AmazonSES( + $this->settings['region'], + $this->settings['access_key'], + $this->settings['secret_key'], + $this->from); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing AmazonSES', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itsConstructorWorks() { + expect($this->mailer->awsEndpoint) + ->equals( + sprintf('email.%s.amazonaws.com', $this->settings['region']) + ); + expect($this->mailer->url) ->equals( + sprintf('https://email.%s.amazonaws.com', $this->settings['region']) + ); + expect(preg_match('!^\d{8}T\d{6}Z$!', $this->mailer->date))->equals(1); + expect(preg_match('!^\d{8}$!', $this->mailer->dateWithoutTime))->equals(1); + } + + function itCanGenerateBody() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + expect($body['Action'])->equals('SendEmail'); + expect($body['Version'])->equals('2010-12-01'); + expect($body['Source'])->equals($this->from); + expect($body['Destination.ToAddresses.member.1']) + ->contains($this->subscriber); + expect($body['Message.Subject.Data']) + ->equals($this->newsletter['subject']); + expect($body['Message.Body.Html.Data']) + ->equals($this->newsletter['body']['html']); + expect($body['Message.Body.Text.Data']) + ->equals($this->newsletter['body']['text']); + expect($body['ReturnPath'])->equals($this->from); + } + + function itCanCreateRequest() { + $request = $this->mailer->request($this->newsletter, $this->subscriber); + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + expect($request['timeout'])->equals(10); + expect($request['httpversion'])->equals('1.1'); + expect($request['method'])->equals('POST'); + expect($request['headers']['Host'])->equals($this->mailer->awsEndpoint); + expect($request['headers']['Authorization']) + ->equals($this->mailer->signRequest($body)); + expect($request['headers']['X-Amz-Date'])->equals($this->mailer->date); + expect($request['body'])->equals(urldecode(http_build_query($body))); + } + + function itCanCreateCanonicalRequest() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + $canonicalRequest = explode( + "\n", + $this->mailer->getCanonicalRequest($body) + ); + expect($canonicalRequest) + ->equals( + array( + 'POST', + '/', + '', + 'host:' . $this->mailer->awsEndpoint, + 'x-amz-date:' . $this->mailer->date, + '', + 'host;x-amz-date', + hash($this->mailer->hashAlgorithm, + urldecode(http_build_query($body)) + ) + ) + ); + } + + function itCanCreateCredentialScope() { + $credentialScope = $this->mailer->getCredentialScope(); + expect($credentialScope) + ->equals( + $this->mailer->dateWithoutTime . '/' . + $this->mailer->awsRegion . '/' . + $this->mailer->awsService . '/' . + $this->mailer->awsTerminationString + ); + } + + function itCanCreateStringToSign() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + $credentialScope = $this->mailer->getCredentialScope(); + $canonicalRequest = $this->mailer->getCanonicalRequest($body); + $stringToSing = $this->mailer->createStringToSign( + $credentialScope, + $canonicalRequest + ); + $stringToSing = explode("\n", $stringToSing); + expect($stringToSing) + ->equals( + array( + $this->mailer->awsSigningAlgorithm, + $this->mailer->date, + $credentialScope, + hash($this->mailer->hashAlgorithm, $canonicalRequest) + ) + ); + } + + function itCanSignRequest() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + $signedRequest = $this->mailer->signRequest($body); + expect($signedRequest) + ->contains( + $this->mailer->awsSigningAlgorithm . ' Credential=' . + $this->mailer->awsAccessKey . '/' . + $this->mailer->getCredentialScope() . ', ' . + 'SignedHeaders=host;x-amz-date, Signature=' + ); + expect(preg_match('!Signature=[A-Fa-f0-9]{64}$!', $signedRequest)) + ->equals(1); + } + + function itCannotSendWithoutProperAccessKey() { + $this->mailer->awsAccessKey = 'somekey'; + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCanSend() { + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->true(); + } +} diff --git a/tests/unit/Mailer/API/ElasticEmailCest.php b/tests/unit/Mailer/Methods/ElasticEmailCest.php similarity index 94% rename from tests/unit/Mailer/API/ElasticEmailCest.php rename to tests/unit/Mailer/Methods/ElasticEmailCest.php index 047a12f306..6e01469a7f 100644 --- a/tests/unit/Mailer/API/ElasticEmailCest.php +++ b/tests/unit/Mailer/Methods/ElasticEmailCest.php @@ -1,65 +1,64 @@ -settings = array( - 'method' => 'ElasticEmail', - 'type' => 'API', - 'api_key' => '997f1f7f-41de-4d7f-a8cb-86c8481370fa' - ); - $this->fromEmail = 'staff@mailpoet.com'; - $this->fromName = 'Sender'; - $this->mailer = new ElasticEmail( - $this->settings['api_key'], - $this->fromEmail, - $this->fromName - ); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing ElasticEmail', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itCanGenerateBody() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - expect($body['api_key'])->equals($this->settings['api_key']); - expect($body['from'])->equals($this->fromEmail); - expect($body['from_name'])->equals($this->fromName); - expect($body['to'])->contains($this->subscriber); - expect($body['subject'])->equals($this->newsletter['subject']); - expect($body['body_html'])->equals($this->newsletter['body']['html']); - expect($body['body_text'])->equals($this->newsletter['body']['text']); - } - - function itCanCreateRequest() { - $request = $this->mailer->request($this->newsletter, $this->subscriber); - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - expect($request['timeout'])->equals(10); - expect($request['httpversion'])->equals('1.0'); - expect($request['method'])->equals('POST'); - expect($request['body'])->equals(urldecode(http_build_query($body))); - } - - function itCannotSendWithoutProperAPIKey() { - $this->mailer->apiKey = 'someapi'; - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCanSend() { - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->true(); - } -} +settings = array( + 'method' => 'ElasticEmail', + 'api_key' => '997f1f7f-41de-4d7f-a8cb-86c8481370fa' + ); + $this->fromEmail = 'staff@mailpoet.com'; + $this->fromName = 'Sender'; + $this->mailer = new ElasticEmail( + $this->settings['api_key'], + $this->fromEmail, + $this->fromName + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing ElasticEmail', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itCanGenerateBody() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + expect($body['api_key'])->equals($this->settings['api_key']); + expect($body['from'])->equals($this->fromEmail); + expect($body['from_name'])->equals($this->fromName); + expect($body['to'])->contains($this->subscriber); + expect($body['subject'])->equals($this->newsletter['subject']); + expect($body['body_html'])->equals($this->newsletter['body']['html']); + expect($body['body_text'])->equals($this->newsletter['body']['text']); + } + + function itCanCreateRequest() { + $request = $this->mailer->request($this->newsletter, $this->subscriber); + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + expect($request['timeout'])->equals(10); + expect($request['httpversion'])->equals('1.0'); + expect($request['method'])->equals('POST'); + expect($request['body'])->equals(urldecode(http_build_query($body))); + } + + function itCannotSendWithoutProperAPIKey() { + $this->mailer->apiKey = 'someapi'; + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCanSend() { + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->true(); + } +} diff --git a/tests/unit/Mailer/API/MailGunCest.php b/tests/unit/Mailer/Methods/MailGunCest.php similarity index 95% rename from tests/unit/Mailer/API/MailGunCest.php rename to tests/unit/Mailer/Methods/MailGunCest.php index 6e3a5a8e68..b946949c60 100644 --- a/tests/unit/Mailer/API/MailGunCest.php +++ b/tests/unit/Mailer/Methods/MailGunCest.php @@ -1,82 +1,81 @@ -settings = array( - 'method' => 'MailGun', - 'type' => 'API', - 'api_key' => 'key-6cf5g5qjzenk-7nodj44gdt8phe6vam2', - 'domain' => 'mrcasual.com' - ); - $this->from = 'Sender '; - $this->mailer = new MailGun( - $this->settings['domain'], - $this->settings['api_key'], - $this->from - ); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing MailGun', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itCanGenerateBody() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - expect($body['from'])->equals($this->from); - expect($body['to'])->equals($this->subscriber); - expect($body['subject'])->equals($this->newsletter['subject']); - expect($body['html'])->equals($this->newsletter['body']['html']); - expect($body['text'])->equals($this->newsletter['body']['text']); - } - - function itCanDoBasicAuth() { - expect($this->mailer->auth()) - ->equals('Basic ' . base64_encode('api:' . $this->settings['api_key'])); - } - - function itCanCreateRequest() { - $request = $this->mailer->request($this->newsletter, $this->subscriber); - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - expect($request['timeout'])->equals(10); - expect($request['httpversion'])->equals('1.0'); - expect($request['method'])->equals('POST'); - expect($request['headers']['Content-Type']) - ->equals('application/x-www-form-urlencoded'); - expect($request['headers']['Authorization']) - ->equals('Basic ' . base64_encode('api:' . $this->settings['api_key'])); - expect($request['body'])->equals(urldecode(http_build_query($body))); - } - - function itCannotSendWithoutProperAPIKey() { - $this->mailer->apiKey = 'someapi'; - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCannotSendWithoutProperDomain() { - $this->mailer->url = - str_replace($this->settings['domain'], 'somedomain', $this->mailer->url); - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCanSend() { - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->true(); - } +settings = array( + 'method' => 'MailGun', + 'api_key' => 'key-6cf5g5qjzenk-7nodj44gdt8phe6vam2', + 'domain' => 'mrcasual.com' + ); + $this->from = 'Sender '; + $this->mailer = new MailGun( + $this->settings['domain'], + $this->settings['api_key'], + $this->from + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing MailGun', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itCanGenerateBody() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + expect($body['from'])->equals($this->from); + expect($body['to'])->equals($this->subscriber); + expect($body['subject'])->equals($this->newsletter['subject']); + expect($body['html'])->equals($this->newsletter['body']['html']); + expect($body['text'])->equals($this->newsletter['body']['text']); + } + + function itCanDoBasicAuth() { + expect($this->mailer->auth()) + ->equals('Basic ' . base64_encode('api:' . $this->settings['api_key'])); + } + + function itCanCreateRequest() { + $request = $this->mailer->request($this->newsletter, $this->subscriber); + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + expect($request['timeout'])->equals(10); + expect($request['httpversion'])->equals('1.0'); + expect($request['method'])->equals('POST'); + expect($request['headers']['Content-Type']) + ->equals('application/x-www-form-urlencoded'); + expect($request['headers']['Authorization']) + ->equals('Basic ' . base64_encode('api:' . $this->settings['api_key'])); + expect($request['body'])->equals(urldecode(http_build_query($body))); + } + + function itCannotSendWithoutProperAPIKey() { + $this->mailer->apiKey = 'someapi'; + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCannotSendWithoutProperDomain() { + $this->mailer->url = + str_replace($this->settings['domain'], 'somedomain', $this->mailer->url); + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCanSend() { + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->true(); + } } \ No newline at end of file diff --git a/tests/unit/Mailer/MailPoetCest.php b/tests/unit/Mailer/Methods/MailPoetCest.php similarity index 95% rename from tests/unit/Mailer/MailPoetCest.php rename to tests/unit/Mailer/Methods/MailPoetCest.php index 3176bb8e71..f54f9996fb 100644 --- a/tests/unit/Mailer/MailPoetCest.php +++ b/tests/unit/Mailer/Methods/MailPoetCest.php @@ -1,95 +1,95 @@ -settings = array( - 'method' => 'MailPoet', - 'api_key' => 'dhNSqj1XHkVltIliyQDvMiKzQShOA5rs0m_DdRUVZHU' - ); - $this->fromEmail = 'staff@mailpoet.com'; - $this->fromName = 'Sender'; - $this->mailer = new MailPoet( - $this->settings['api_key'], - $this->fromEmail, - $this->fromName - ); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing MailPoet', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itCanGenerateBody() { - $subscriber = $this->mailer->processSubscriber($this->subscriber); - $body = $this->mailer->getBody($this->newsletter, $subscriber); - expect($body['to']['address'])->equals($subscriber['email']); - expect($body['to']['name'])->equals($subscriber['name']); - expect($body['from']['address'])->equals($this->fromEmail); - expect($body['subject'])->equals($this->newsletter['subject']); - expect($body['html'])->equals($this->newsletter['body']['html']); - expect($body['text'])->equals($this->newsletter['body']['text']); - } - - function itCanCreateRequest() { - $subscriber = $this->mailer->processSubscriber( - 'Recipient ' - ); - $body = array($this->mailer->getBody($this->newsletter, $subscriber)); - $request = $this->mailer->request($this->newsletter, $subscriber); - expect($request['timeout'])->equals(10); - expect($request['httpversion'])->equals('1.0'); - expect($request['method'])->equals('POST'); - expect($request['headers']['Content-Type'])->equals('application/json'); - expect($request['headers']['Authorization'])->equals($this->mailer->auth()); - expect($request['body'])->equals($body); - } - - function itCanProcessSubscriber() { - expect($this->mailer->processSubscriber('test@test.com')) - ->equals( - array( - 'email' => 'test@test.com', - 'name' => '' - )); - expect($this->mailer->processSubscriber('First ')) - ->equals( - array( - 'email' => 'test@test.com', - 'name' => 'First' - )); - expect($this->mailer->processSubscriber('First Last ')) - ->equals( - array( - 'email' => 'test@test.com', - 'name' => 'First Last' - )); - } - - function itCanDoBasicAuth() { - expect($this->mailer->auth()) - ->equals('Basic ' . base64_encode('api:' . $this->settings['api_key'])); - } - - function itCannotSendWithoutProperAPIKey() { - $this->mailer->apiKey = 'someapi'; - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCanSend() { - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->true(); - } -} +settings = array( + 'method' => 'MailPoet', + 'api_key' => 'dhNSqj1XHkVltIliyQDvMiKzQShOA5rs0m_DdRUVZHU' + ); + $this->fromEmail = 'staff@mailpoet.com'; + $this->fromName = 'Sender'; + $this->mailer = new MailPoet( + $this->settings['api_key'], + $this->fromEmail, + $this->fromName + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing MailPoet', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itCanGenerateBody() { + $subscriber = $this->mailer->processSubscriber($this->subscriber); + $body = $this->mailer->getBody($this->newsletter, $subscriber); + expect($body['to']['address'])->equals($subscriber['email']); + expect($body['to']['name'])->equals($subscriber['name']); + expect($body['from']['address'])->equals($this->fromEmail); + expect($body['subject'])->equals($this->newsletter['subject']); + expect($body['html'])->equals($this->newsletter['body']['html']); + expect($body['text'])->equals($this->newsletter['body']['text']); + } + + function itCanCreateRequest() { + $subscriber = $this->mailer->processSubscriber( + 'Recipient ' + ); + $body = array($this->mailer->getBody($this->newsletter, $subscriber)); + $request = $this->mailer->request($this->newsletter, $subscriber); + expect($request['timeout'])->equals(10); + expect($request['httpversion'])->equals('1.0'); + expect($request['method'])->equals('POST'); + expect($request['headers']['Content-Type'])->equals('application/json'); + expect($request['headers']['Authorization'])->equals($this->mailer->auth()); + expect($request['body'])->equals($body); + } + + function itCanProcessSubscriber() { + expect($this->mailer->processSubscriber('test@test.com')) + ->equals( + array( + 'email' => 'test@test.com', + 'name' => '' + )); + expect($this->mailer->processSubscriber('First ')) + ->equals( + array( + 'email' => 'test@test.com', + 'name' => 'First' + )); + expect($this->mailer->processSubscriber('First Last ')) + ->equals( + array( + 'email' => 'test@test.com', + 'name' => 'First Last' + )); + } + + function itCanDoBasicAuth() { + expect($this->mailer->auth()) + ->equals('Basic ' . base64_encode('api:' . $this->settings['api_key'])); + } + + function itCannotSendWithoutProperAPIKey() { + $this->mailer->apiKey = 'someapi'; + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCanSend() { + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->true(); + } +} diff --git a/tests/unit/Mailer/API/MandrillCest.php b/tests/unit/Mailer/Methods/MandrillCest.php similarity index 95% rename from tests/unit/Mailer/API/MandrillCest.php rename to tests/unit/Mailer/Methods/MandrillCest.php index 38775ca2d5..86b0774a8c 100644 --- a/tests/unit/Mailer/API/MandrillCest.php +++ b/tests/unit/Mailer/Methods/MandrillCest.php @@ -1,90 +1,89 @@ -settings = array( - 'method' => 'Mandrill', - 'type' => 'API', - 'api_key' => '692ys1B7REEoZN7R-dYwNA' - ); - $this->fromEmail = 'staff@mailpoet.com'; - $this->fromName = 'Sender'; - $this->mailer = new Mandrill( - $this->settings['api_key'], - $this->fromEmail, - $this->fromName - ); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing Mandrill', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itCanGenerateBody() { - $subscriber = $this->mailer->processSubscriber($this->subscriber); - $body = $this->mailer->getBody($this->newsletter, $subscriber); - expect($body['key'])->equals($this->settings['api_key']); - expect($body['message']['from_email'])->equals($this->fromEmail); - expect($body['message']['from_name'])->equals($this->fromName); - expect($body['message']['to'])->equals(array($subscriber)); - expect($body['message']['subject'])->equals($this->newsletter['subject']); - expect($body['message']['html'])->equals($this->newsletter['body']['html']); - expect($body['message']['text'])->equals($this->newsletter['body']['text']); - expect($body['async'])->false(); - } - - function itCanCreateRequest() { - $subscriber = $this->mailer->processSubscriber($this->subscriber); - $body = $this->mailer->getBody($this->newsletter, $subscriber); - $request = $this->mailer->request($this->newsletter, $subscriber); - expect($request['timeout'])->equals(10); - expect($request['httpversion'])->equals('1.0'); - expect($request['method'])->equals('POST'); - expect($request['headers']['Content-Type'])->equals('application/json'); - expect($request['body'])->equals(json_encode($body)); - } - - function itCanProcessSubscriber() { - expect($this->mailer->processSubscriber('test@test.com')) - ->equals( - array( - 'email' => 'test@test.com', - 'name' => '' - )); - expect($this->mailer->processSubscriber('First ')) - ->equals( - array( - 'email' => 'test@test.com', - 'name' => 'First' - )); - expect($this->mailer->processSubscriber('First Last ')) - ->equals( - array( - 'email' => 'test@test.com', - 'name' => 'First Last' - )); - } - - function itCannotSendWithoutProperAPIKey() { - $this->mailer->apiKey = 'someapi'; - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCanSend() { - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->true(); - } +settings = array( + 'method' => 'Mandrill', + 'api_key' => '692ys1B7REEoZN7R-dYwNA' + ); + $this->fromEmail = 'staff@mailpoet.com'; + $this->fromName = 'Sender'; + $this->mailer = new Mandrill( + $this->settings['api_key'], + $this->fromEmail, + $this->fromName + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing Mandrill', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itCanGenerateBody() { + $subscriber = $this->mailer->processSubscriber($this->subscriber); + $body = $this->mailer->getBody($this->newsletter, $subscriber); + expect($body['key'])->equals($this->settings['api_key']); + expect($body['message']['from_email'])->equals($this->fromEmail); + expect($body['message']['from_name'])->equals($this->fromName); + expect($body['message']['to'])->equals(array($subscriber)); + expect($body['message']['subject'])->equals($this->newsletter['subject']); + expect($body['message']['html'])->equals($this->newsletter['body']['html']); + expect($body['message']['text'])->equals($this->newsletter['body']['text']); + expect($body['async'])->false(); + } + + function itCanCreateRequest() { + $subscriber = $this->mailer->processSubscriber($this->subscriber); + $body = $this->mailer->getBody($this->newsletter, $subscriber); + $request = $this->mailer->request($this->newsletter, $subscriber); + expect($request['timeout'])->equals(10); + expect($request['httpversion'])->equals('1.0'); + expect($request['method'])->equals('POST'); + expect($request['headers']['Content-Type'])->equals('application/json'); + expect($request['body'])->equals(json_encode($body)); + } + + function itCanProcessSubscriber() { + expect($this->mailer->processSubscriber('test@test.com')) + ->equals( + array( + 'email' => 'test@test.com', + 'name' => '' + )); + expect($this->mailer->processSubscriber('First ')) + ->equals( + array( + 'email' => 'test@test.com', + 'name' => 'First' + )); + expect($this->mailer->processSubscriber('First Last ')) + ->equals( + array( + 'email' => 'test@test.com', + 'name' => 'First Last' + )); + } + + function itCannotSendWithoutProperAPIKey() { + $this->mailer->apiKey = 'someapi'; + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCanSend() { + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->true(); + } } \ No newline at end of file diff --git a/tests/unit/Mailer/SMTPCest.php b/tests/unit/Mailer/Methods/SMTPCest.php similarity index 95% rename from tests/unit/Mailer/SMTPCest.php rename to tests/unit/Mailer/Methods/SMTPCest.php index c83dd00f5c..a0ed11a25c 100644 --- a/tests/unit/Mailer/SMTPCest.php +++ b/tests/unit/Mailer/Methods/SMTPCest.php @@ -1,92 +1,92 @@ -settings = array( - 'method' => 'SMTP', - 'host' => 'email-smtp.us-west-2.amazonaws.com', - 'port' => 587, - 'login' => 'AKIAIGPBLH6JWG5VCBQQ', - 'password' => 'AudVHXHaYkvr54veCzqiqOxDiMMyfQW3/V6F1tYzGXY3', - 'authentication' => '1', - 'encryption' => 'tls' - ); - $this->fromEmail = 'staff@mailpoet.com'; - $this->fromName = 'Sender'; - $this->mailer = new SMTP( - $this->settings['host'], - $this->settings['port'], - $this->settings['authentication'], - $this->settings['login'], - $this->settings['password'], - $this->settings['encryption'], - $this->fromEmail, - $this->fromName - ); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing SMTP', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itCanBuildMailer() { - $mailer = $this->mailer->buildMailer(); - expect($mailer->getTransport()->getHost()) - ->equals($this->settings['host']); - expect($mailer->getTransport()->getPort()) - ->equals($this->settings['port']); - expect($mailer->getTransport()->getUsername()) - ->equals($this->settings['login']); - expect($mailer->getTransport()->getPassword()) - ->equals($this->settings['password']); - expect($mailer->getTransport()->getEncryption()) - ->equals($this->settings['encryption']); - } - - function itCanCreateMessage() { - $message = $this->mailer->createMessage($this->newsletter, $this->subscriber); - expect($message->getTo()) - ->equals(array('mailpoet-phoenix-test@mailinator.com' => 'Recipient')); - expect($message->getFrom()) - ->equals(array($this->fromEmail => $this->fromName)); - expect($message->getSubject()) - ->equals($this->newsletter['subject']); - expect($message->getBody()) - ->equals($this->newsletter['body']['html']); - expect($message->getChildren()[0]->getContentType()) - ->equals('text/plain'); - } - - function itCanProcessSubscriber() { - expect($this->mailer->processSubscriber('test@test.com')) - ->equals(array('test@test.com' => '')); - expect($this->mailer->processSubscriber('First ')) - ->equals(array('test@test.com' => 'First')); - expect($this->mailer->processSubscriber('First Last ')) - ->equals(array('test@test.com' => 'First Last')); - } - - function itCantSentWithoutProperAuthentication() { - $this->mailer->login = 'someone'; - $this->mailer->mailer = $this->mailer->buildMailer(); - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCanSend() { - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->true(); - } +settings = array( + 'method' => 'SMTP', + 'host' => 'email-smtp.us-west-2.amazonaws.com', + 'port' => 587, + 'login' => 'AKIAIGPBLH6JWG5VCBQQ', + 'password' => 'AudVHXHaYkvr54veCzqiqOxDiMMyfQW3/V6F1tYzGXY3', + 'authentication' => '1', + 'encryption' => 'tls' + ); + $this->fromEmail = 'staff@mailpoet.com'; + $this->fromName = 'Sender'; + $this->mailer = new SMTP( + $this->settings['host'], + $this->settings['port'], + $this->settings['authentication'], + $this->settings['login'], + $this->settings['password'], + $this->settings['encryption'], + $this->fromEmail, + $this->fromName + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing SMTP', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itCanBuildMailer() { + $mailer = $this->mailer->buildMailer(); + expect($mailer->getTransport()->getHost()) + ->equals($this->settings['host']); + expect($mailer->getTransport()->getPort()) + ->equals($this->settings['port']); + expect($mailer->getTransport()->getUsername()) + ->equals($this->settings['login']); + expect($mailer->getTransport()->getPassword()) + ->equals($this->settings['password']); + expect($mailer->getTransport()->getEncryption()) + ->equals($this->settings['encryption']); + } + + function itCanCreateMessage() { + $message = $this->mailer->createMessage($this->newsletter, $this->subscriber); + expect($message->getTo()) + ->equals(array('mailpoet-phoenix-test@mailinator.com' => 'Recipient')); + expect($message->getFrom()) + ->equals(array($this->fromEmail => $this->fromName)); + expect($message->getSubject()) + ->equals($this->newsletter['subject']); + expect($message->getBody()) + ->equals($this->newsletter['body']['html']); + expect($message->getChildren()[0]->getContentType()) + ->equals('text/plain'); + } + + function itCanProcessSubscriber() { + expect($this->mailer->processSubscriber('test@test.com')) + ->equals(array('test@test.com' => '')); + expect($this->mailer->processSubscriber('First ')) + ->equals(array('test@test.com' => 'First')); + expect($this->mailer->processSubscriber('First Last ')) + ->equals(array('test@test.com' => 'First Last')); + } + + function itCantSentWithoutProperAuthentication() { + $this->mailer->login = 'someone'; + $this->mailer->mailer = $this->mailer->buildMailer(); + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCanSend() { + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->true(); + } } \ No newline at end of file diff --git a/tests/unit/Mailer/API/SendGridCest.php b/tests/unit/Mailer/Methods/SendGridCest.php similarity index 95% rename from tests/unit/Mailer/API/SendGridCest.php rename to tests/unit/Mailer/Methods/SendGridCest.php index 77bb636ff0..d7e6db3429 100644 --- a/tests/unit/Mailer/API/SendGridCest.php +++ b/tests/unit/Mailer/Methods/SendGridCest.php @@ -1,71 +1,70 @@ -settings = array( - 'method' => 'SendGrid', - 'type' => 'API', - 'api_key' => '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' - ); - $this->fromEmail = 'staff@mailpoet.com'; - $this->fromName = 'Sender'; - $this->mailer = new SendGrid( - $this->settings['api_key'], - $this->fromEmail, - $this->fromName - ); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing SendGrid', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itCanGenerateBody() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - expect($body['to'])->contains($this->subscriber); - expect($body['from'])->equals($this->fromEmail); - expect($body['fromname'])->equals($this->fromName); - expect($body['subject'])->equals($this->newsletter['subject']); - expect($body['html'])->equals($this->newsletter['body']['html']); - expect($body['text'])->equals($this->newsletter['body']['text']); - } - - function itCanCreateRequest() { - $body = $this->mailer->getBody($this->newsletter, $this->subscriber); - $request = $this->mailer->request($this->newsletter, $this->subscriber); - expect($request['timeout'])->equals(10); - expect($request['httpversion'])->equals('1.1'); - expect($request['method'])->equals('POST'); - expect($request['headers']['Authorization']) - ->equals('Bearer ' . $this->settings['api_key']); - expect($request['body'])->equals(urldecode(http_build_query($body))); - } - - function itCanDoBasicAuth() { - expect($this->mailer->auth()) - ->equals('Bearer ' . $this->settings['api_key']); - } - - function itCannotSendWithoutProperAPIKey() { - $this->mailer->apiKey = 'someapi'; - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->false(); - } - - function itCanSend() { - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - expect($result)->true(); - } -} +settings = array( + 'method' => 'SendGrid', + 'api_key' => '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' + ); + $this->fromEmail = 'staff@mailpoet.com'; + $this->fromName = 'Sender'; + $this->mailer = new SendGrid( + $this->settings['api_key'], + $this->fromEmail, + $this->fromName + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing SendGrid', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itCanGenerateBody() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + expect($body['to'])->contains($this->subscriber); + expect($body['from'])->equals($this->fromEmail); + expect($body['fromname'])->equals($this->fromName); + expect($body['subject'])->equals($this->newsletter['subject']); + expect($body['html'])->equals($this->newsletter['body']['html']); + expect($body['text'])->equals($this->newsletter['body']['text']); + } + + function itCanCreateRequest() { + $body = $this->mailer->getBody($this->newsletter, $this->subscriber); + $request = $this->mailer->request($this->newsletter, $this->subscriber); + expect($request['timeout'])->equals(10); + expect($request['httpversion'])->equals('1.1'); + expect($request['method'])->equals('POST'); + expect($request['headers']['Authorization']) + ->equals('Bearer ' . $this->settings['api_key']); + expect($request['body'])->equals(urldecode(http_build_query($body))); + } + + function itCanDoBasicAuth() { + expect($this->mailer->auth()) + ->equals('Bearer ' . $this->settings['api_key']); + } + + function itCannotSendWithoutProperAPIKey() { + $this->mailer->apiKey = 'someapi'; + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->false(); + } + + function itCanSend() { + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + expect($result)->true(); + } +} diff --git a/tests/unit/Mailer/WPMailCest.php b/tests/unit/Mailer/Methods/WPMailCest.php similarity index 94% rename from tests/unit/Mailer/WPMailCest.php rename to tests/unit/Mailer/Methods/WPMailCest.php index c8cfdbf686..e76f2f4940 100644 --- a/tests/unit/Mailer/WPMailCest.php +++ b/tests/unit/Mailer/Methods/WPMailCest.php @@ -1,70 +1,70 @@ -settings = array( - 'method' => 'WPMail' - ); - $this->fromEmail = 'staff@mailpoet.com'; - $this->fromName = 'Sender'; - $this->mailer = new WPMail( - $this->fromEmail, - $this->fromName - ); - $this->subscriber = 'Recipient '; - $this->newsletter = array( - 'subject' => 'testing SMTP', - 'body' => array( - 'html' => 'HTML body', - 'text' => 'TEXT body' - ) - ); - } - - function itCanAddFilters() { - $this->mailer->addFilters(); - expect(has_filter('wp_mail_from_name', array( - $this->mailer, - 'setFromName' - )))->notEmpty(); - expect(has_filter('wp_mail_from', array( - $this->mailer, - 'setFromEmail' - )))->notEmpty(); - expect(has_filter('wp_mail_content_type', array( - $this->mailer, - 'setContentType' - )))->notEmpty(); - } - - function itCanRemoveFilters() { - $this->mailer->addFilters(); - $this->mailer->removeFilters(); - expect(has_filter('wp_mail_from_name'))->false(); - expect(has_filter('wp_mail_from'))->false(); - expect(has_filter('wp_mail_content_type'))->false(); - } - - function itCanSetFromName() { - expect($this->mailer->setFromName())->equals($this->fromName); - } - - function itCanSetFromEmail() { - expect($this->mailer->setFromName())->equals($this->fromName); - } - - function itCanSetContentType() { - expect($this->mailer->setContentType())->equals('text/html'); - } - - function itCanSend() { - $_SERVER['SERVER_NAME'] = 'localhost'; - $result = $this->mailer->send( - $this->newsletter, - $this->subscriber - ); - //expect($result)->true(); - } +settings = array( + 'method' => 'WPMail' + ); + $this->fromEmail = 'staff@mailpoet.com'; + $this->fromName = 'Sender'; + $this->mailer = new WPMail( + $this->fromEmail, + $this->fromName + ); + $this->subscriber = 'Recipient '; + $this->newsletter = array( + 'subject' => 'testing SMTP', + 'body' => array( + 'html' => 'HTML body', + 'text' => 'TEXT body' + ) + ); + } + + function itCanAddFilters() { + $this->mailer->addFilters(); + expect(has_filter('wp_mail_from_name', array( + $this->mailer, + 'setFromName' + )))->notEmpty(); + expect(has_filter('wp_mail_from', array( + $this->mailer, + 'setFromEmail' + )))->notEmpty(); + expect(has_filter('wp_mail_content_type', array( + $this->mailer, + 'setContentType' + )))->notEmpty(); + } + + function itCanRemoveFilters() { + $this->mailer->addFilters(); + $this->mailer->removeFilters(); + expect(has_filter('wp_mail_from_name'))->false(); + expect(has_filter('wp_mail_from'))->false(); + expect(has_filter('wp_mail_content_type'))->false(); + } + + function itCanSetFromName() { + expect($this->mailer->setFromName())->equals($this->fromName); + } + + function itCanSetFromEmail() { + expect($this->mailer->setFromName())->equals($this->fromName); + } + + function itCanSetContentType() { + expect($this->mailer->setContentType())->equals('text/html'); + } + + function itCanSend() { + $_SERVER['SERVER_NAME'] = 'localhost'; + $result = $this->mailer->send( + $this->newsletter, + $this->subscriber + ); + //expect($result)->true(); + } } \ No newline at end of file