Browse Source
par defaut on ne supporte que les methodes standard `mail()` et `smtp`. A charge pour d'autres plugins de proposer des methodes supplementaires via ce pipeline et en fournissant : * le formulaires/inc-config-facteur-mailer-xxxx.html * la classe inc/Facteur/FacteurXxxxx.php (declaree dans le pipeline)pull/12/head
12 changed files with 12 additions and 959 deletions
@ -1,31 +0,0 @@
|
||||
#SET{fl,facteur} |
||||
<div class="choix"> |
||||
<input type="radio" name="mailer" class="radio" value="mailjet" id="mailer_mailjet"[(#ENV{mailer,'mail'}|=={mailjet}|oui)checked="checked"]/> |
||||
<label for="mailer_mailjet"><:facteur:label_utiliser_mailjet:></label> |
||||
<a href="https://www.mailjet.com/">https://www.mailjet.com/</a> |
||||
<div class="editer-groupe suite"[(#ENV{mailer,'mail'}|=={mailjet}|non)style='display:none;']> |
||||
#SET{name,mailjet_api_key}#SET{obli,''}#SET{defaut,''}#SET{erreurs,#ENV**{erreurs}|table_valeur{#GET{name}}} |
||||
<div class="editer editer_[(#GET{name})][ (#GET{obli})][ (#GET{erreurs}|oui)erreur]"> |
||||
<label for="#GET{name}">[(#GET{fl}|concat{':label_',#GET{name}}|_T)]</label>[ |
||||
<span class='erreur_message'>(#GET{erreurs})</span> |
||||
]<input type="text" name="#GET{name}" class="text" value="#ENV*{#GET{name},#GET{defaut}}" id="#GET{name}" [(#HTML5|et{#GET{obli}})required='required']/> |
||||
</div> |
||||
#SET{name,mailjet_secret_key}#SET{obli,''}#SET{defaut,''}#SET{erreurs,#ENV**{erreurs}|table_valeur{#GET{name}}} |
||||
<div class="editer editer_[(#GET{name})][ (#GET{obli})][ (#GET{erreurs}|oui)erreur]"> |
||||
<label for="#GET{name}">[(#GET{fl}|concat{':label_',#GET{name}}|_T)]</label>[ |
||||
<span class='erreur_message'>(#GET{erreurs})</span> |
||||
]<input type="text" name="#GET{name}" class="text" value="#ENV*{#GET{name},#GET{defaut}}" id="#GET{name}" [(#HTML5|et{#GET{obli}})required='required'] |
||||
[placeholder="(#ENV*{_#GET{name}}|facteur_affiche_password_masque{#AUTORISER{webmestre}}|attribut_html)"] /> |
||||
|
||||
</div> |
||||
#SET{name,mailjet_api_version}#SET{obli,''}#SET{defaut,'3'}#SET{erreurs,#ENV**{erreurs}|table_valeur{#GET{name}}} |
||||
<div class="editer editer_[(#GET{name})][ (#GET{obli})][ (#GET{erreurs}|oui)erreur]"> |
||||
<label for="#GET{name}">[(#GET{fl}|concat{':label_',#GET{name}}|_T)]</label>[ |
||||
<span class='erreur_message'>(#GET{erreurs})</span> |
||||
]<select name="#GET{name}" class="select" id="#GET{name}"> |
||||
#SET{val,3} |
||||
<option value="#GET{val}"[(#ENV{#GET{name},#GET{defaut}}|=={#GET{val}}|oui)selected="selected"]>[v(#GET{val})] (in-v#GET{val}.mailjet.com)</option> |
||||
</select> |
||||
</div> |
||||
</div> |
||||
</div> |
@ -1,306 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* Plugin Facteur 4 |
||||
* (c) 2009-2019 Collectif SPIP |
||||
* Distribue sous licence GPL |
||||
* |
||||
* @package SPIP\Facteur\FacteurSMTP |
||||
*/ |
||||
|
||||
namespace SPIP\Facteur\Api; |
||||
|
||||
|
||||
class Mailjetv3 { |
||||
var $version = 3; |
||||
var $apiVersion = 'v3/'; |
||||
|
||||
# Connect thru https protocol |
||||
var $secure = true; |
||||
|
||||
# Mode debug ? 0 none / 1 errors only / 2 all |
||||
var $debug = 0; |
||||
|
||||
# Edit with your Mailjet Infos |
||||
var $apiKey = ''; |
||||
var $secretKey = ''; |
||||
|
||||
var $_method = ''; |
||||
var $_request = ''; |
||||
var $_data = ''; |
||||
var $_response = ''; |
||||
var $_error = ''; |
||||
|
||||
// Constructor function |
||||
public function __construct($apiKey = false, $secretKey = false){ |
||||
if ($apiKey){ |
||||
$this->apiKey = $apiKey; |
||||
} |
||||
if ($secretKey){ |
||||
$this->secretKey = $secretKey; |
||||
} |
||||
$this->apiUrl = (($this->secure) ? 'https' : 'http') . '://' |
||||
. ($this->apiKey ? $this->apiKey . ':' . $this->secretKey . '@' : '') |
||||
. 'api.mailjet.com/' . $this->apiVersion . ''; |
||||
} |
||||
|
||||
/* |
||||
* Legacy methods |
||||
*/ |
||||
public function userSenderadd($params){ |
||||
$data = array('email' => $params['email']); |
||||
return $this->sender(array('data' => $data)); |
||||
} |
||||
|
||||
public function __call($method, $args){ |
||||
# params |
||||
$params = (sizeof($args)>0) ? $args[0] : array(); |
||||
|
||||
$data = ''; |
||||
$request = 'GET'; |
||||
|
||||
# request method |
||||
if (isset($params["method"])){ |
||||
$request = $params["method"]; |
||||
unset($params["method"]); |
||||
} |
||||
|
||||
# Make request |
||||
$result = $this->sendRequest($method, $params, $request); |
||||
|
||||
# Return result |
||||
$return = ($result===true) ? $this->_response : false; |
||||
|
||||
if ($this->_error){ |
||||
$url_log = "api.mailjet.com/" . $this->apiVersion . $this->_method; |
||||
spip_log("$url_log : " . $this->_error, 'mailjet' . _LOG_ERREUR); |
||||
} elseif (isset($this->_response['StatusCode'])) { |
||||
$url_log = "api.mailjet.com/" . $this->apiVersion . $this->_method; |
||||
spip_log("$url_log : status " . $this->_response['StatusCode'] . " - " . $this->_response['ErrorInfo'] . ", " . $this->_response['ErrorMessage'], 'mailjet' . _LOG_INFO_IMPORTANTE); |
||||
} |
||||
|
||||
/* |
||||
if ($this->debug==2 || ($this->debug==1 && $return==false)){ |
||||
$this->debug(); |
||||
}*/ |
||||
|
||||
return $return; |
||||
} |
||||
|
||||
|
||||
/** |
||||
* @param bool $method |
||||
* api call method |
||||
* @param array $params |
||||
* path : subpath of the method (:id/validate for calling sender/:id/validate) |
||||
* data : data to send as a POST |
||||
* filters : args to add in query string to filter results |
||||
* @param string $request |
||||
* GET/POST/PUT/... |
||||
* @return bool |
||||
*/ |
||||
public function sendRequest($method = false, $params = array(), $request = "GET"){ |
||||
# Method |
||||
$this->_method = $method; |
||||
$this->_request = $request; |
||||
$this->_data = ''; |
||||
$this->_response = ''; |
||||
$this->_error = ''; |
||||
|
||||
// submethod path ? |
||||
if (isset($params['path'])){ |
||||
$method .= "/" . ltrim($params['path'], "/"); |
||||
$this->_method = $method; |
||||
} |
||||
|
||||
$headers = ""; |
||||
$data = ""; |
||||
// data is the json body of request |
||||
if (isset($params['data'])){ |
||||
$data = $params['data']; |
||||
if (!is_string($data)){ |
||||
include_spip('inc/json'); |
||||
$data = json_encode($data); |
||||
} |
||||
$headers .= "Content-Type: application/json\r\n"; |
||||
$this->_data = $headers . "\r\n" . $data; |
||||
if ($request=='GET'){ |
||||
$this->_request = $request = 'POST'; |
||||
} |
||||
} |
||||
|
||||
|
||||
include_spip('inc/distant'); |
||||
if ($method!=='send'){ |
||||
$method = "REST/$method"; |
||||
} |
||||
|
||||
$url = $this->apiUrl . $method; |
||||
$url_log = "api.mailjet.com/" . $this->apiVersion . $method; |
||||
|
||||
// filters is the query string part of request |
||||
if (isset($params['filters'])){ |
||||
$qs = $params['filters']; |
||||
if (!is_string($qs)){ |
||||
$qs = http_build_query($qs); |
||||
} |
||||
$url .= "?$qs"; |
||||
$url_log .= "?$qs"; |
||||
} |
||||
|
||||
try { |
||||
if (function_exists('curl_init')) { |
||||
$ch = curl_init(); |
||||
$headers = explode("\n", $headers); |
||||
$headers = array_map("trim", $headers); |
||||
curl_setopt($ch, CURLOPT_URL, $url); |
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); |
||||
curl_setopt($ch, CURLOPT_HEADER, FALSE); |
||||
if ($headers){ |
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); |
||||
} |
||||
if (in_array($this->_request, array("DELETE", "PUT"))){ |
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->_request); |
||||
} |
||||
if ($data){ |
||||
curl_setopt($ch, CURLOPT_POST, TRUE); |
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); |
||||
} |
||||
spip_log("sendRequest via curl", "mailjet" . _LOG_DEBUG); |
||||
$response = curl_exec($ch); |
||||
spip_log($response, "mailjet" . _LOG_DEBUG); |
||||
$this->_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
||||
curl_close($ch); |
||||
} |
||||
else { |
||||
$options = array( |
||||
'methode' => $this->_request, |
||||
); |
||||
if ($this->_data){ |
||||
$options['datas'] = $this->_data; |
||||
} |
||||
spip_log("sendRequest via recuperer_url", "mailjet" . _LOG_DEBUG); |
||||
$res = recuperer_url($url, $options); |
||||
spip_log($res, "mailjet" . _LOG_DEBUG); |
||||
if ($res) { |
||||
$this->_response_code = $res['status']; |
||||
$response = $res['page']; |
||||
} |
||||
else { |
||||
$this->_error = "Fail sendRequest $url_log via recuperer_url"; |
||||
spip_log($this->_error, "mailjet" . _LOG_ERREUR); |
||||
return false; |
||||
} |
||||
} |
||||
} catch (Exception $e) { |
||||
$this->_error = "sendRequest $url_log : " . $e->getMessage(); |
||||
spip_log($this->_error, "mailjet" . _LOG_ERREUR); |
||||
return false; |
||||
} |
||||
|
||||
$success = ((intval($this->_response_code/100)==2) ? true : false); |
||||
if (!$success and !$this->_error){ |
||||
$this->_error = "Error Status " . $this->_response_code; |
||||
} |
||||
spip_log("$request $url_log " . ($success ? "OK" : "FAIL") . " resultat: " . $response, "mailjet" . _LOG_DEBUG); |
||||
if ($response){ |
||||
$this->_response = json_decode($response, true); |
||||
} |
||||
return $success; |
||||
} |
||||
|
||||
|
||||
public function debug(){ |
||||
echo '<style type="text/css">'; |
||||
echo ' |
||||
|
||||
#debugger {width: 100%; font-family: arial;} |
||||
#debugger table {padding: 0; margin: 0 0 20px; width: 100%; font-size: 11px; text-align: left;border-collapse: collapse;} |
||||
#debugger th, #debugger td {padding: 2px 4px;} |
||||
#debugger tr.h {background: #999; color: #fff;} |
||||
#debugger tr.Success {background:#90c306; color: #fff;} |
||||
#debugger tr.Error {background:#c30029 ; color: #fff;} |
||||
#debugger tr.Not-modified {background:orange ; color: #fff;} |
||||
#debugger th {width: 20%; vertical-align:top; padding-bottom: 8px;} |
||||
|
||||
'; |
||||
echo '</style>'; |
||||
|
||||
echo '<div id="debugger">'; |
||||
|
||||
if (isset($this->_response_code)) : |
||||
|
||||
if ($this->_response_code==200) : |
||||
|
||||
echo '<table>'; |
||||
echo '<tr class="Success"><th>Success</th><td></td></tr>'; |
||||
echo '<tr><th>Status code</th><td>' . $this->_response_code . '</td></tr>'; |
||||
|
||||
if (isset($this->_response)) : |
||||
echo '<tr><th>Response</th><td><pre>' . utf8_decode(print_r($this->_response, 1)) . '</pre></td></tr>'; |
||||
endif; |
||||
|
||||
echo '</table>'; |
||||
elseif ($this->_response_code==304) : |
||||
|
||||
echo '<table>'; |
||||
echo '<tr class="Not-modified"><th>Error</th><td></td></tr>'; |
||||
echo '<tr><th>Error no</th><td>' . $this->_response_code . '</td></tr>'; |
||||
echo '<tr><th>Message</th><td>Not Modified</td></tr>'; |
||||
echo '</table>'; |
||||
else : |
||||
|
||||
echo '<table>'; |
||||
echo '<tr class="Error"><th>Error</th><td></td></tr>'; |
||||
echo '<tr><th>Error no</th><td>' . $this->_response_code . '</td></tr>'; |
||||
if (isset($this->_response)) : |
||||
if (is_array($this->_response) OR is_object($this->_response)): |
||||
echo '<tr><th>Status</th><td><pre>' . print_r($this->_response, true) . '</pre></td></tr>'; |
||||
else: |
||||
echo '<tr><th>Status</th><td><pre>' . $this->_response . '</pre></td></tr>'; |
||||
endif; |
||||
endif; |
||||
echo '</table>'; |
||||
|
||||
endif; |
||||
|
||||
endif; |
||||
|
||||
$call_url = parse_url($this->call_url); |
||||
|
||||
echo '<table>'; |
||||
echo '<tr class="h"><th>API config</th><td></td></tr>'; |
||||
echo '<tr><th>Protocole</th><td>' . $call_url['scheme'] . '</td></tr>'; |
||||
echo '<tr><th>Host</th><td>' . $call_url['host'] . '</td></tr>'; |
||||
echo '<tr><th>Version</th><td>' . $this->version . '</td></tr>'; |
||||
echo '</table>'; |
||||
|
||||
echo '<table>'; |
||||
echo '<tr class="h"><th>Call infos</th><td></td></tr>'; |
||||
echo '<tr><th>Method</th><td>' . $this->_method . '</td></tr>'; |
||||
echo '<tr><th>Request type</th><td>' . $this->_request . '</td></tr>'; |
||||
echo '<tr><th>Get Arguments</th><td>'; |
||||
|
||||
$args = explode("&", $call_url['query']); |
||||
foreach ($args as $arg){ |
||||
$arg = explode("=", $arg); |
||||
echo '' . $arg[0] . ' = <span style="color:#ff6e56;">' . $arg[1] . '</span><br/>'; |
||||
} |
||||
|
||||
echo '</td></tr>'; |
||||
|
||||
if ($this->_request_post){ |
||||
echo '<tr><th>Post Arguments</th><td>'; |
||||
|
||||
foreach ($this->_request_post as $k => $v){ |
||||
echo $k . ' = <span style="color:#ff6e56;">' . $v . '</span><br/>'; |
||||
} |
||||
|
||||
echo '</td></tr>'; |
||||
} |
||||
|
||||
echo '<tr><th>Call url</th><td>' . $this->call_url . '</td></tr>'; |
||||
echo '</table>'; |
||||
|
||||
echo '</div>'; |
||||
} |
||||
} |
@ -1,588 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* Plugin Facteur 4 |
||||
* (c) 2009-2019 Collectif SPIP |
||||
* Distribue sous licence GPL |
||||
* |
||||
* @package SPIP\Facteur\FacteurSMTP |
||||
*/ |
||||
|
||||
namespace SPIP\Facteur; |
||||
|
||||
use PHPMailer\PHPMailer\PHPMailer; |
||||
use PHPMailer\PHPMailer\Exception; |
||||
use SPIP\Facteur\Api\Mailjetv3 as Mailjet; |
||||
|
||||
if (!defined("_ECRIRE_INC_VERSION")){ |
||||
return; |
||||
} |
||||
|
||||
|
||||
|
||||
include_spip('inc/Facteur/FacteurMail'); |
||||
|
||||
|
||||
function checkMessagesSentStatus($ids, $apiCredentials, $sendFailFunction, $count=0) { |
||||
$count++; |
||||
$recheck = []; |
||||
$failed = []; |
||||
if ($ids |
||||
and $mj = FacteurMailjet::newMailjetApi($apiCredentials['version'], $apiCredentials['key'], $apiCredentials['secretKey'])) { |
||||
foreach ($ids as $id) { |
||||
FacteurMailjet::logDebug("checkMessagesSentStatus: check message id $id", 0); |
||||
$status = $mj->message(['path' => $id]); |
||||
if (!$status){ |
||||
$recheck[] = $id; |
||||
} |
||||
else { |
||||
if (empty($status['Count']) or empty($status['Data'])) { |
||||
FacteurMailjet::logDebug("checkMessagesSentStatus: FAIL message $id " . json_encode($status), 0); |
||||
$failed[] = $id; |
||||
} |
||||
else { |
||||
foreach ($status['Data'] as $message) { |
||||
switch (strtolower($message['Status'])) { |
||||
case 'unknown': |
||||
case 'queued': |
||||
case 'deferred': |
||||
FacteurMailjet::logDebug("checkMessagesSentStatus: RECHECK message $id " . json_encode($message), 0); |
||||
$recheck[] = $id; |
||||
break; |
||||
|
||||
case 'bounce': |
||||
case 'spam': |
||||
case 'unsub': |
||||
case 'blocked': |
||||
case 'hardbounced': |
||||
case 'softbounced': |
||||
$failed[] = $id; |
||||
FacteurMailjet::logDebug("checkMessagesSentStatus: FAIL message $id " . json_encode($message), 0); |
||||
break; |
||||
|
||||
case 'sent': |
||||
case 'opened': |
||||
case 'clicked': |
||||
default: |
||||
FacteurMailjet::logDebug("checkMessagesSentStatus: OK message $id " . json_encode($message), 0); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
if (count($failed)) { |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
|
||||
if ($failed |
||||
or ($recheck and $count>=5)) { |
||||
$facteur_envoyer_alerte_fail = charger_fonction('facteur_envoyer_alerte_fail','inc'); |
||||
$facteur_envoyer_alerte_fail($sendFailFunction['function'], $sendFailFunction['args'], $sendFailFunction['include']); |
||||
} |
||||
elseif ($recheck) { |
||||
// on re-essaye dans 5mn, 5 fois maxi en tout |
||||
$delay = 5 * 60; |
||||
FacteurMailjet::planCheckMessagesSent($delay, $ids, $apiCredentials, $sendFailFunction, $count); |
||||
} |
||||
// tout est bon, rien a faire on a fini |
||||
FacteurMailjet::logDebug("checkMessagesSentStatus: Fini", 0); |
||||
} |
||||
|
||||
/** |
||||
* Utilise l'API REST en v3 |
||||
* Class FacteurMailjetv3 |
||||
*/ |
||||
class FacteurMailjet extends FacteurMail { |
||||
|
||||
protected $api_version = "v3/"; |
||||
protected $message = array( |
||||
'FromEmail' => '', |
||||
'FromName' => '', |
||||
'Subject' => '', |
||||
'Text-part' => '', |
||||
'Html-part' => '', |
||||
//'Mj-campaign' => '', |
||||
//'Mj-deduplicatecampaign' => 1, |
||||
//'Mj-CustomID' => '', |
||||
'Headers' => array(//'Reply-To' => 'copilot@mailjet.com', |
||||
), |
||||
'Attachments' => array(// {"Content-type":"text/plain","Filename":"test.txt","content":"VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"}] |
||||
), |
||||
'Inline_attachments' => array(// {"Content-type":"text/plain","Filename":"test.txt","content":"VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"}] |
||||
), |
||||
|
||||
); |
||||
protected $message_dest = array( |
||||
'To' => array(/*array( |
||||
'Email' => '', |
||||
'Name' => '', |
||||
)*/ |
||||
), |
||||
'Cc' => array(/*array( |
||||
'Email' => '', |
||||
'Name' => '', |
||||
)*/ |
||||
), |
||||
'Bcc' => array(/*array( |
||||
'Email' => '', |
||||
'Name' => '', |
||||
)*/ |
||||
), |
||||
); |
||||
|
||||
// pour le tracking des campagne |
||||
protected $trackingId; |
||||
|
||||
protected $apiVersion = 3; |
||||
protected $apiKey; |
||||
protected $apiSecretKey; |
||||
|
||||
public static function newMailjetApi($version, $key, $secretKey) { |
||||
switch ($version) { |
||||
case 3: |
||||
default: |
||||
include_spip('inc/Facteur/Api/Mailjetv3'); |
||||
$mj = new Mailjet($key, $secretKey); |
||||
} |
||||
$mj->debug = 0; |
||||
|
||||
return $mj; |
||||
} |
||||
|
||||
public static function planCheckMessagesSent($delay, $ids, $apiCredentials, $sendFailFunction, $count=0) { |
||||
$include = "inc/Facteur/FacteurMailjet"; |
||||
$time = time() + $delay; |
||||
self::logDebug("planCheckMessagesSent: ids " . implode(', ', $ids), 0); |
||||
job_queue_add('SPIP\Facteur\checkMessagesSentStatus', "Mailjet Important mail checkMessagesSentStatus", [$ids, $apiCredentials, $sendFailFunction, $count], $include, false, $time); |
||||
} |
||||
|
||||
/** |
||||
* Facteur constructor. |
||||
* @param array $options |
||||
* @throws Exception |
||||
*/ |
||||
public function __construct($options = array()){ |
||||
parent::__construct($options); |
||||
$this->mailer = 'mailjet'; |
||||
|
||||
if (!empty($options['mailjet_api_version'])){ |
||||
$this->apiVersion = $options['mailjet_api_version']; |
||||
} |
||||
if (!empty($options['mailjet_api_key'])){ |
||||
$this->apiKey = $options['mailjet_api_key']; |
||||
} |
||||
if (!empty($options['mailjet_api_version'])){ |
||||
$this->apiSecretKey = $options['mailjet_secret_key']; |
||||
} |
||||
if (!empty($options['tracking_id'])){ |
||||
$this->trackingId = $options['tracking_id']; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Auto-configuration du mailer si besoin |
||||
* (rien a faire ici dans le cas par defaut) |
||||
* @return bool |
||||
*/ |
||||
public function configure(){ |
||||
parent::configure(); |
||||
$this->addAuthorizedSender($this->From); |
||||
return true; |
||||
} |
||||
|
||||
/** |
||||
* @return Mailjet |
||||
*/ |
||||
protected function &getMailjetAPI(){ |
||||
static $mj = null; |
||||
if (is_null($mj)){ |
||||
$mj = self::newMailjetApi($this->apiVersion, $this->apiKey, $this->apiSecretKey); |
||||
} |
||||
return $mj; |
||||
} |
||||
|
||||
|
||||
/** |
||||
* Verifier si un email d'envoi est dans la liste des senders mailjet |
||||
* et sinon l'ajoute |
||||
* |
||||
* @param string $sender_email |
||||
* @param bool $force |
||||
* @return bool |
||||
*/ |
||||
protected function addAuthorizedSender($sender_email, $force = false){ |
||||
|
||||
$status = $this->readSenderStatus($sender_email); |
||||
|
||||
if ($status=="active"){ |
||||
return $status; |
||||
} // active |
||||
if ($status AND !$force){ |
||||
return $status; |
||||
} // pending |
||||
|
||||
// si le sender n'est pas dans la liste ou en attente |
||||
$mj = $this->getMailjetAPI(); |
||||
|
||||
$params = array( |
||||
'data' => array('Email' => $sender_email), |
||||
); |
||||
$res = $mj->sender($params); |
||||
|
||||
return $this->readSenderStatus($sender_email); |
||||
} |
||||
|
||||
/** |
||||
* Lire le status d'un sender chez mailjet |
||||
* @param string $sender_email |
||||
* @return bool|string |
||||
*/ |
||||
protected function readSenderStatus($sender_email){ |
||||
|
||||
$mj = $this->getMailjetAPI(); |
||||
$params = array( |
||||
'filters' => array('Email' => $sender_email), |
||||
); |
||||
$res = (array)$mj->sender($params); |
||||
if (!isset($res['Count'])){ |
||||
return null; |
||||
} |
||||
if (isset($res['Data'])){ |
||||
foreach ($res['Data'] as $sender){ |
||||
if ($sender['Email']==$sender_email){ |
||||
if (in_array($sender['Status'], array('Active', 'Inactive'))){ |
||||
return strtolower($sender['Status']); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
|
||||
|
||||
protected function cleanAdress($address, $name = ''){ |
||||
$address = trim($address); |
||||
$name = trim(preg_replace('/[\r\n]+/', ' ', $name)); //Strip breaks and trim |
||||
if (!self::ValidateAddress($address)){ |
||||
$this->SetError('invalid_address' . ': ' . $address); |
||||
return false; |
||||
} |
||||
return array('Email' => $address, 'Name' => $name); |
||||
} |
||||
|
||||
/** |
||||
* Mettre en forme une addresse email |
||||
* @param $dest |
||||
* @return string |
||||
*/ |
||||
protected function formatEmailDest($dest){ |
||||
$d = $dest['Email']; |
||||
if (!empty($dest['Name'])){ |
||||
$name = $dest['Name']; |
||||
if (preg_match(",\W,", $name)){ |
||||
$name = '"' . $name . '"'; |
||||
} |
||||
$d = $name . " <$d>"; |
||||
} |
||||
return $d; |
||||
} |
||||
|
||||
/** |
||||
* Clear all recipients |
||||
*/ |
||||
public function clearAllRecipients(){ |
||||
$this->message_dest['To'] = []; |
||||
$this->message_dest['Cc'] = []; |
||||
$this->message_dest['Bcc'] = []; |
||||
parent::clearAllRecipients(); |
||||
} |
||||
|
||||
/** |
||||
* Adds a "To" address. |
||||
* @param string $address |
||||
* @param string $name |
||||
* @return boolean true on success, false if address already used |
||||
*/ |
||||
public function AddAddress($address, $name = ''){ |
||||
if ($a = $this->cleanAdress($address, $name)){ |
||||
$this->message_dest['To'][] = $a; |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Adds a "Cc" address. |
||||
* Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. |
||||
* @param string $address |
||||
* @param string $name |
||||
* @return boolean true on success, false if address already used |
||||
*/ |
||||
public function AddCC($address, $name = ''){ |
||||
if ($a = $this->cleanAdress($address, $name)){ |
||||
$this->message_dest['Cc'][] = $a; |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Adds a "Bcc" address. |
||||
* Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. |
||||
* @param string $address |
||||
* @param string $name |
||||
* @return boolean true on success, false if address already used |
||||
*/ |
||||
public function AddBCC($address, $name = ''){ |
||||
if ($a = $this->cleanAdress($address, $name)){ |
||||
$this->message_dest['Bcc'][] = $a; |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Adds a "Reply-to" address. |
||||
* @param string $address |
||||
* @param string $name |
||||
* @return boolean |
||||
*/ |
||||
public function AddReplyTo($address, $name = ''){ |
||||
if ($a = $this->cleanAdress($address, $name)){ |
||||
$this->message['Headers']['Reply-To'] = $this->formatEmailDest($a); |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/** |
||||
* Adds a custom header. |
||||
* @access public |
||||
* @return void |
||||
*/ |
||||
public function AddCustomHeader($name, $value = null){ |
||||
if ($value===null){ |
||||
// Value passed in as name:value |
||||
list($name, $value) = explode(':', $name, 2); |
||||
} |
||||
$this->message['Headers'][$name] = trim($value); |
||||
} |
||||
|
||||
|
||||
/** |
||||
* Ne sert pas, sauf aux logs internes |
||||
* @return string|void |
||||
*/ |
||||
public function CreateHeader(){ |
||||
$header = ""; |
||||
|
||||
$header .= "Date: " . date('Y-m-d H:i:s') . "\n"; |
||||
|
||||
$from = $this->formatEmailDest(['Email' => $this->From, 'Name' => $this->FromName]); |
||||
$header .= "From: $from\n"; |
||||
|
||||
foreach (['To', 'Cc', 'Bcc'] as $dest_type){ |
||||
if (!empty($this->message_dest[$dest_type]) and count($this->message_dest[$dest_type])){ |
||||
$dests = []; |
||||
foreach ($this->message_dest[$dest_type] as $dest){ |
||||
$dests[] = $this->formatEmailDest($dest); |
||||
} |
||||
$header .= "$dest_type: " . implode(',', $dests) . "\n"; |
||||
} |
||||
} |
||||
|
||||
if (!empty($this->message['Headers'])){ |
||||
foreach ($this->message['Headers'] as $k => $h){ |
||||
$header .= "$k: $h\n"; |
||||
} |
||||
} |
||||
|
||||
return $header; |
||||
} |
||||
|
||||
|
||||
/** |
||||
* @return bool |
||||
* @throws \Exception |
||||
*/ |
||||
public function Send(){ |
||||
$this->forceFromIfNeeded(); |
||||
|
||||
$this->message['Html-part'] = $this->Body; |
||||
$this->message['Text-part'] = $this->AltBody; |
||||
$this->message['Subject'] = $this->Subject; |
||||
$this->message['FromEmail'] = $this->From; |
||||
$this->message['FromName'] = $this->FromName; |
||||
|
||||
|
||||
if (count($this->attachment)){ |
||||
$inline_attachements = []; |
||||
$attachments = []; |
||||
foreach ($this->attachment as $attachment){ |
||||
$bString = $attachment[5]; |
||||
if ($bString){ |
||||
$string = $attachment[0]; |
||||
} else { |
||||
$path = $attachment[0]; |
||||
$string = file_get_contents($path); |
||||
} |
||||
$string = base64_encode($string); |
||||
|
||||
if ($attachment[6]==='inline'){ |
||||
$inline_attachements[] = array( |
||||
"Content-type" => $attachment[4], |
||||
"Filename" => $attachment[7], // cid |
||||
"content" => $string, |
||||
); |
||||
} else { |
||||
$attachments[] = array( |
||||
"Content-type" => $attachment[4], |
||||
"Filename" => $attachment[1], |
||||
"content" => $string |
||||
); |
||||
} |
||||
// {"Content-type":"text/plain","Filename":"test.txt","content":"VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"}] |
||||
} |
||||
$this->message['Attachments'] = $attachments; |
||||
$this->message['Inline_attachments'] = $inline_attachements; |
||||
} |
||||
|
||||
foreach (['To', 'Cc', 'Bcc'] as $dest_type){ |
||||
if (!empty($this->message_dest[$dest_type]) and count($this->message_dest[$dest_type])){ |
||||
$dests = array(); |
||||
foreach ($this->message_dest[$dest_type] as $dest){ |
||||
$dests[] = $this->formatEmailDest($dest); |
||||
} |
||||
$this->message[$dest_type] = implode(',', $dests); |
||||
} |
||||
} |
||||
|
||||
// ajouter le trackingId en tag, pour retrouver le message apres webhook |
||||
if (!empty($this->trackingId) |
||||
and $id = $this->trackingId){ |
||||
// prefixer le tracking par l'url du site pour ne pas melanger les feedbacks |
||||
$this->message['Mj-campaign'] = protocole_implicite($GLOBALS['meta']['adresse_site']) . "/#" . $id; |
||||
$this->message['Mj-deduplicatecampaign'] = 1; |
||||
} |
||||
|
||||
|
||||
// pas de valeur vide dans le message |
||||
foreach (array_keys($this->message) as $k){ |
||||
if (empty($this->message[$k])){ |
||||
unset($this->message[$k]); |
||||
} |
||||
} |
||||
|
||||
/* |
||||
$trace = $this->message; |
||||
unset($trace['Html-part']); |
||||
unset($trace['Text-part']); |
||||
if (!empty($trace['Attachments'])) { |
||||
$trace['Attachments'] = "Array(".count($trace['Attachments']) .")"; |
||||
} |
||||
if (!empty($trace['Inline_attachments'])) { |
||||
$trace['Inline_attachments'] = "Array(".count($trace['Inline_attachments']) .")"; |
||||
} |
||||
$this->log($trace, _LOG_DEBUG); |
||||
*/ |
||||
|
||||
$mj = $this->getMailjetAPI(); |
||||
$res = $mj->send(array('data' => $this->message)); |
||||
if (!$res){ |
||||
$this->SetError($mj->_error); |
||||
if ($this->exceptions){ |
||||
throw new \Exception($mj->_error); |
||||
} |
||||
return $this->sendAlertIfNeeded(false); |
||||
} |
||||
|
||||
/* |
||||
{ |
||||
"ErrorInfo": "Bad Request", |
||||
"ErrorMessage": "Unknown resource: \"contacts\"", |
||||
"StatusCode": 400 |
||||
} |
||||
*/ |
||||
|
||||
// statut d'erreur au premier niveau ? |
||||
if (isset($res['StatusCode']) |
||||
AND intval($res['StatusCode']/100)>2){ |
||||
|
||||
$error = "status " . $res['StatusCode'] . " - " . $res['ErrorInfo'] . ": " . $res['ErrorMessage']; |
||||
$this->SetError($error); |
||||
if ($this->exceptions){ |
||||
throw new \Exception($error); |
||||
} |
||||
return $this->sendAlertIfNeeded(false); |
||||
} |
||||
|
||||
// { "Sent" : [{ "Email" : "cedric@yterium.com", "MessageID" : 19140330729428381 }] } |
||||
if (isset($res['Sent']) AND count($res['Sent'])){ |
||||
return $this->sendAlertIfNeeded($res); |
||||
} |
||||
// les autres type de reponse sont non documentees. On essaye au hasard? |
||||
if (isset($res['Queued']) AND count($res['Queued'])){ |
||||
return $this->sendAlertIfNeeded($res); |
||||
} |
||||
if (isset($res['Invalid']) AND count($res['Invalid'])){ |
||||
$this->SetError($error = "invalid"); |
||||
if ($this->exceptions){ |
||||
throw new \Exception($error); |
||||
} |
||||
return $this->sendAlertIfNeeded(false); |
||||
} |
||||
if (isset($res['Rejected']) AND count($res['Rejected'])){ |
||||
$this->SetError($error = "rejected"); |
||||
if ($this->exceptions){ |
||||
throw new \Exception($error); |
||||
} |
||||
return $this->sendAlertIfNeeded(false); |
||||
} |
||||
|
||||
// Erreur inconnue |
||||
$this->SetError("mailjetERROR " . var_export($res, true)); |
||||
$this->log($error = "mailjet/send resultat inatendu : " . json_encode($res), _LOG_ERREUR); |
||||
if ($this->exceptions){ |
||||
throw new \Exception($error); |
||||
} |
||||
return $this->sendAlertIfNeeded(false); |
||||
} |
||||
|
||||
|
||||
/** |
||||
* Verifier si il faut envoyer le mail d'alerte |
||||
* @param mixed $res |
||||
* @return mixed |
||||
*/ |
||||
protected function sendAlertIfNeeded($res) { |
||||
if ($res === false) { |
||||
return parent::sendAlertIfNeeded($res); |
||||
} |
||||
if ($this->important and !empty($this->sendFailFunction)){ |
||||
// sinon chercher les ids des message a verifier un peu plus tard |
||||
if (isset($res['Sent']) AND count($res['Sent'])){ |
||||
$message_ids = []; |
||||
$all_dests = array_column($this->message_dest['To'], 'Email'); |
||||
foreach ($res['Sent'] as $message){ |
||||
if (!empty($message['Email']) and !empty($message['MessageID'])){ |
||||
$dest = $message['Email']; |
||||
$id = $message['MessageID']; |
||||
if (in_array($dest, $all_dests)){ |
||||
$message_ids[] = $id; |
||||
} |
||||
} |
||||
} |
||||
if ($message_ids){ |
||||
// verifier ces ids dans 60s |
||||
$apiCredentials = ['version' => $this->apiVersion, 'key' => $this->apiKey, 'secretKey' => $this->apiSecretKey]; |
||||
FacteurMailjet::planCheckMessagesSent(60, $message_ids, $apiCredentials, $this->sendFailFunction); |
||||
} |
||||
} |
||||
} |
||||
|
||||
return $res; |
||||
} |
||||
|
||||
} |
Loading…
Reference in new issue