295 linhas
12 KiB
PHP
295 linhas
12 KiB
PHP
<?php
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Sends the emails of WordPress (wp_mail) through the E-mail Center transactional API.
|
|
* If the API fails and the fallback is on, WordPress sends the email the normal way.
|
|
*/
|
|
class INTERWEB_MZ_EMAIL_CENTER_Mailer
|
|
{
|
|
const MAX_RECIPIENTS = 50;
|
|
const MAX_ATTACH_BYTES = 5242880; // 5 MB in total, as the API accepts.
|
|
|
|
/** True when the last send was only simulated (sandbox key or E-mail Center in test mode). */
|
|
public static $last_simulated = false;
|
|
|
|
public static function init()
|
|
{
|
|
add_filter('pre_wp_mail', array(__CLASS__, 'pre_wp_mail'), 10, 2);
|
|
}
|
|
|
|
public static function enabled()
|
|
{
|
|
return (int) INTERWEB_MZ_EMAIL_CENTER_Settings::get('mail_enabled') === 1 && INTERWEB_MZ_EMAIL_CENTER_Settings::api_key() !== '';
|
|
}
|
|
|
|
/**
|
|
* @param null|bool $short
|
|
* @param array $atts to, subject, message, headers, attachments (already through the "wp_mail" filter)
|
|
* @return null|bool null lets WordPress send the normal way.
|
|
*/
|
|
public static function pre_wp_mail($short, $atts)
|
|
{
|
|
if ($short !== null || !self::enabled()) {
|
|
return $short;
|
|
}
|
|
$result = self::send($atts);
|
|
if ($result === true) {
|
|
return true;
|
|
}
|
|
$fallback = (int) INTERWEB_MZ_EMAIL_CENTER_Settings::get('mail_fallback') === 1;
|
|
$to_list = self::addresses(isset($atts['to']) ? $atts['to'] : '');
|
|
INTERWEB_MZ_EMAIL_CENTER_Log::add('mail', false, $result->get_error_message(), array(
|
|
'to' => implode(', ', array_map(array('INTERWEB_MZ_EMAIL_CENTER_Log', 'mask_email'), array_slice($to_list, 0, 3))),
|
|
'fallback' => $fallback ? 1 : 0,
|
|
));
|
|
if ($fallback) {
|
|
return null; // WordPress goes on and sends it the normal way.
|
|
}
|
|
do_action('wp_mail_failed', new WP_Error('wp_mail_failed', $result->get_error_message(), $atts));
|
|
return false;
|
|
}
|
|
|
|
/** @return true|WP_Error */
|
|
public static function send($atts, $log = true)
|
|
{
|
|
$payload = self::build_payload($atts);
|
|
if (is_wp_error($payload)) {
|
|
return $payload;
|
|
}
|
|
$chunks = array_chunk($payload['to'], self::MAX_RECIPIENTS);
|
|
$first = true;
|
|
$simulated = false;
|
|
foreach ($chunks as $chunk) {
|
|
$p = $payload;
|
|
$p['to'] = array_values($chunk);
|
|
if (!$first) {
|
|
unset($p['cc'], $p['bcc']);
|
|
}
|
|
$first = false;
|
|
$res = INTERWEB_MZ_EMAIL_CENTER_Api::send_email($p, true);
|
|
if (is_wp_error($res)) {
|
|
return $res;
|
|
}
|
|
$data = isset($res['data']) && is_array($res['data']) ? $res['data'] : array();
|
|
if (!empty($data['simulated'])) {
|
|
$simulated = true;
|
|
}
|
|
if (isset($data['status']) && $data['status'] === 'failed') {
|
|
return new WP_Error('interweb_mz_email_center_mail_failed', !empty($data['error']) ? (string) $data['error'] : __('The email was not sent.', 'interweb-mz-email-center'));
|
|
}
|
|
}
|
|
self::$last_simulated = $simulated;
|
|
if ($log) {
|
|
INTERWEB_MZ_EMAIL_CENTER_Log::add('mail', true, $simulated ? __('Email accepted by the API (simulated: sandbox key or test mode).', 'interweb-mz-email-center') : __('Email sent through the API.', 'interweb-mz-email-center'), array(
|
|
'to' => implode(', ', array_map(array('INTERWEB_MZ_EMAIL_CENTER_Log', 'mask_email'), array_slice($payload['to'], 0, 3))),
|
|
'subject' => function_exists('mb_substr') ? mb_substr($payload['subject'], 0, 80) : substr($payload['subject'], 0, 80),
|
|
));
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/** Turns the wp_mail arguments into the body of POST /v1/email/messages. */
|
|
public static function build_payload($atts)
|
|
{
|
|
$to = self::addresses(isset($atts['to']) ? $atts['to'] : '');
|
|
$subject = isset($atts['subject']) ? (string) $atts['subject'] : '';
|
|
$message = isset($atts['message']) ? (string) $atts['message'] : '';
|
|
$headers = isset($atts['headers']) ? $atts['headers'] : array();
|
|
$attachments = isset($atts['attachments']) ? $atts['attachments'] : array();
|
|
|
|
$cc = array();
|
|
$bcc = array();
|
|
$reply_to = array();
|
|
$from_header = '';
|
|
$from_header_name = '';
|
|
$content_type = '';
|
|
$extra = array();
|
|
|
|
if (!is_array($headers)) {
|
|
$headers = explode("\n", str_replace("\r\n", "\n", (string) $headers));
|
|
}
|
|
foreach ($headers as $name => $line) {
|
|
// Headers may come as "Name: value" lines or as name => value.
|
|
if (!is_int($name)) {
|
|
$line = $name . ': ' . $line;
|
|
}
|
|
if (strpos($line, ':') === false) {
|
|
continue;
|
|
}
|
|
list($hname, $hval) = explode(':', $line, 2);
|
|
$hname = strtolower(trim($hname));
|
|
$hval = trim($hval);
|
|
switch ($hname) {
|
|
case 'from':
|
|
$parsed = self::parse_address($hval);
|
|
$from_header = $parsed[0];
|
|
$from_header_name = $parsed[1];
|
|
break;
|
|
case 'cc':
|
|
$cc = array_merge($cc, self::addresses($hval));
|
|
break;
|
|
case 'bcc':
|
|
$bcc = array_merge($bcc, self::addresses($hval));
|
|
break;
|
|
case 'reply-to':
|
|
$reply_to = array_merge($reply_to, self::addresses($hval));
|
|
break;
|
|
case 'content-type':
|
|
$ct = explode(';', $hval);
|
|
$content_type = strtolower(trim($ct[0]));
|
|
break;
|
|
default:
|
|
// Only the headers the API accepts: your own X- headers and a few standard ones.
|
|
if (strpos($hname, 'x-') === 0 || in_array($hname, array('list-unsubscribe', 'list-unsubscribe-post', 'list-id', 'in-reply-to', 'references'), true)) {
|
|
$extra[trim(explode(':', $line, 2)[0])] = $hval;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!$to) {
|
|
return new WP_Error('interweb_mz_email_center_mail_no_to', __('The email has no valid recipient.', 'interweb-mz-email-center'));
|
|
}
|
|
if ($content_type === '') {
|
|
$content_type = apply_filters('wp_mail_content_type', 'text/plain');
|
|
}
|
|
|
|
// Sender: the verified address from the settings. The original sender goes to Reply-To.
|
|
$from = sanitize_email((string) INTERWEB_MZ_EMAIL_CENTER_Settings::get('mail_from_email'));
|
|
$from_name = (string) INTERWEB_MZ_EMAIL_CENTER_Settings::get('mail_from_name');
|
|
$force = (int) INTERWEB_MZ_EMAIL_CENTER_Settings::get('mail_force_from') === 1;
|
|
if (!$force && $from_header && is_email($from_header)) {
|
|
$from = $from_header;
|
|
if ($from_header_name !== '') {
|
|
$from_name = $from_header_name;
|
|
}
|
|
}
|
|
if (!$from) {
|
|
return new WP_Error('interweb_mz_email_center_mail_no_from', __('Choose the sender address (at a verified domain) in the plugin settings.', 'interweb-mz-email-center'));
|
|
}
|
|
if ($from_name === '') {
|
|
$from_name = $from_header_name !== '' ? $from_header_name : wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
|
|
}
|
|
if ($from_header && strcasecmp($from_header, $from) !== 0 && !$reply_to && is_email($from_header)) {
|
|
$reply_to = array($from_header);
|
|
}
|
|
|
|
$payload = array(
|
|
'from' => $from,
|
|
'from_name' => $from_name,
|
|
'to' => array_values(array_unique($to)),
|
|
'subject' => $subject,
|
|
);
|
|
if ($content_type === 'text/html') {
|
|
$payload['html'] = $message;
|
|
$payload['text'] = self::html_to_text($message);
|
|
} else {
|
|
$payload['text'] = $message;
|
|
}
|
|
if ($cc) {
|
|
$payload['cc'] = array_values(array_unique($cc));
|
|
}
|
|
if ($bcc) {
|
|
$payload['bcc'] = array_values(array_unique($bcc));
|
|
}
|
|
if ($reply_to) {
|
|
$payload['reply_to'] = array_slice(array_values(array_unique($reply_to)), 0, 5);
|
|
}
|
|
if ($extra) {
|
|
$payload['headers'] = array_slice($extra, 0, 20, true);
|
|
}
|
|
|
|
$files = self::attachments($attachments);
|
|
if (is_wp_error($files)) {
|
|
return $files;
|
|
}
|
|
if ($files) {
|
|
$payload['attachments'] = $files;
|
|
}
|
|
return $payload;
|
|
}
|
|
|
|
private static function attachments($attachments)
|
|
{
|
|
if (empty($attachments)) {
|
|
return array();
|
|
}
|
|
if (!is_array($attachments)) {
|
|
$attachments = explode("\n", str_replace("\r\n", "\n", (string) $attachments));
|
|
}
|
|
$out = array();
|
|
$total = 0;
|
|
foreach ($attachments as $name => $path) {
|
|
$path = trim((string) $path);
|
|
if ($path === '' || !is_file($path) || !is_readable($path)) {
|
|
continue;
|
|
}
|
|
$size = filesize($path);
|
|
$total += $size;
|
|
if ($total > self::MAX_ATTACH_BYTES) {
|
|
return new WP_Error('interweb_mz_email_center_mail_attachments', __('The attachments go over 5 MB, the most the API accepts.', 'interweb-mz-email-center'));
|
|
}
|
|
$filename = is_string($name) ? $name : basename($path);
|
|
$type = wp_check_filetype($filename);
|
|
$out[] = array(
|
|
'filename' => $filename,
|
|
'content' => base64_encode(file_get_contents($path)),
|
|
'content_type' => !empty($type['type']) ? $type['type'] : 'application/octet-stream',
|
|
);
|
|
}
|
|
return $out;
|
|
}
|
|
|
|
/** Accepts "a@x.com, B <b@y.com>" or an array; returns valid addresses only. */
|
|
public static function addresses($value)
|
|
{
|
|
if (is_array($value)) {
|
|
$parts = $value;
|
|
} else {
|
|
$parts = preg_split('/,(?=(?:[^"]*"[^"]*")*[^"]*$)/', (string) $value);
|
|
}
|
|
$out = array();
|
|
foreach ($parts as $p) {
|
|
$parsed = self::parse_address((string) $p);
|
|
if ($parsed[0] !== '' && is_email($parsed[0])) {
|
|
$out[] = $parsed[0];
|
|
}
|
|
}
|
|
return $out;
|
|
}
|
|
|
|
/** @return array(email, name) */
|
|
public static function parse_address($value)
|
|
{
|
|
$value = trim($value);
|
|
if (preg_match('/^(.*)<([^>]+)>\s*$/', $value, $m)) {
|
|
return array(trim($m[2]), trim(trim($m[1]), '"\' '));
|
|
}
|
|
return array($value, '');
|
|
}
|
|
|
|
public static function html_to_text($html)
|
|
{
|
|
$text = preg_replace('#<(br|/p|/div|/h[1-6]|/li|/tr)[^>]*>#i', "\n", $html);
|
|
$text = wp_strip_all_tags($text);
|
|
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
|
|
return trim(preg_replace("/\n{3,}/", "\n\n", $text));
|
|
}
|
|
|
|
/** Test from the settings page: goes straight to the API, without the fallback, to show the real answer. */
|
|
public static function test($to)
|
|
{
|
|
$lang = INTERWEB_MZ_EMAIL_CENTER_I18n::lang();
|
|
$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
|
|
$atts = array(
|
|
'to' => $to,
|
|
'subject' => sprintf(INTERWEB_MZ_EMAIL_CENTER_I18n::in($lang, 'Test email from %s'), $site),
|
|
'message' => sprintf(INTERWEB_MZ_EMAIL_CENTER_I18n::in($lang, "Hello,\n\nThis is a test sent by the Interweb Mozambique E-mail Center plugin, on %s, through E-mail Center.\nIf it reached you, the site emails can go out this way.\n"), home_url('/')),
|
|
'headers' => array('Content-Type: text/plain; charset=UTF-8'),
|
|
'attachments' => array(),
|
|
);
|
|
return self::send($atts);
|
|
}
|
|
}
|