@ -1,4 +1,5 @@
<?php
/**
* Plugin Facteur 4
* (c) 2009-2019 Collectif SPIP
@ -12,7 +13,7 @@ namespace SPIP\Facteur;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if (!defined("_ECRIRE_INC_VERSION")) {
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
@ -51,7 +52,7 @@ class FacteurMail extends PHPMailer {
* Les URLs du site
* @var array
*/
protected $urlsBase = array() ;
protected $urlsBase = [] ;
/**
* CC Auto a remettre quand on clear les recipients
@ -79,7 +80,7 @@ class FacteurMail extends PHPMailer {
* @param $message
* @param $level
*/
public static function logDebug($message, $level){
public static function logDebug($message, $level) {
$facteurClass = get_called_class();
spip_log("$facteurClass: $level: " . trim($message), $facteurClass::$logName . _LOG_DEBUG);
}
@ -102,14 +103,14 @@ class FacteurMail extends PHPMailer {
* @param array $options
* @throws Exception
*/
public function __construct($options = array()) {
public function __construct($options = []) {
// par defaut on log rien car tres verbeux
// on utilise facteur_log_debug qui filtre log SPIP en _LOG_DEBUG
$this->SMTPDebug = 0;
$this->Debugoutput = __NAMESPACE__ . '\FacteurMail::logDebug';
// Il est possible d'avoir beaucoup plus de logs avec 2, 3 ou 4, ce qui logs les échanges complets avec le serveur
// utiliser avec un define('_MAX_LOG',1000); car sinon on est limite a 100 lignes par hit et phpMailer est tres verbeux
if (defined('_FACTEUR_DEBUG_SMTP')){
if (defined('_FACTEUR_DEBUG_SMTP')) {
$this->SMTPDebug = _FACTEUR_DEBUG_SMTP;
}
$this->exceptions = false;
@ -117,13 +118,13 @@ class FacteurMail extends PHPMailer {
$this->exceptions = ($options['exceptions'] ? true : false);
}
if (!empty($options['adresse_envoi_email'])){
if (!empty($options['adresse_envoi_email'])) {
$this->From = $options['adresse_envoi_email'];
}
// Si plusieurs emails dans le from, pas de Name !
if (strpos($this->From, ",")===false) {
if (!empty($options['adresse_envoi_nom'])){
if (strpos($this->From, ',') === false) {
if (!empty($options['adresse_envoi_nom'])) {
$this->FromName = $options['adresse_envoi_nom'];
}
}
@ -131,27 +132,27 @@ class FacteurMail extends PHPMailer {
// si forcer_from, on sauvegarde le From et FromName par defaut, qui seront utilises
// si From n'est pas dans le meme domaine
// (utiliser le facteur avec un service externe qui necessite la validation des domaines d'envoi)
if (isset($options['forcer_from']) and ($options['forcer_from'] === 'oui' or $options['forcer_from'] === true)){
if (isset($options['forcer_from']) and ($options['forcer_from'] === 'oui' or $options['forcer_from'] === true)) {
$this->ForceFrom = $this->From;
$this->ForceFromName = $this->FromName;
}
$this->CharSet = "utf-8" ;
$this->CharSet = 'utf-8' ;
$this->Mailer = 'mail';
// Retour des erreurs
if (!empty($options['smtp_sender'])){
if (!empty($options['smtp_sender'])) {
$this->Sender = $options['smtp_sender'];
$this->AddCustomHeader("Errors-To: " . $this->Sender);
$this->AddCustomHeader('Errors-To: ' . $this->Sender);
}
// Destinataires en copie, seulement s'il n'y a pas de destinataire de test
if (!defined('_TEST_EMAIL_DEST')){
if (!empty($options['cc'])){
if (!defined('_TEST_EMAIL_DEST')) {
if (!empty($options['cc'])) {
$this->autoCc = $options['cc'];
$this->AddCC($this->autoCc);
}
if (!empty($options['bcc'])){
if (!empty($options['bcc'])) {
$this->autoBcc = $options['bcc'];
$this->AddBCC($this->autoBcc);
}
@ -168,7 +169,6 @@ class FacteurMail extends PHPMailer {
if (!empty($options['adresses_site'])) {
$this->urlsBase = $options['adresses_site'];
}
}
/**
@ -176,7 +176,7 @@ class FacteurMail extends PHPMailer {
* (rien a faire ici dans le cas par defaut)
* @return bool
*/
public function configure(){
public function configure() {
return true;
}
@ -185,7 +185,7 @@ class FacteurMail extends PHPMailer {
* @param $objet
* @param $charset
*/
public function setObjet($objet, $charset = null){
public function setObjet($objet, $charset = null) {
if (is_null($charset)) {
$charset = $GLOBALS['meta']['charset'];
}
@ -203,9 +203,9 @@ class FacteurMail extends PHPMailer {
$this->clearAllRecipients();
//Pour un envoi multiple de mail, $email doit être un tableau avec les adresses.
if (is_array($email)){
foreach ($email as $cle => $adresseMail){
if (!$this->AddAddress($adresseMail)){
if (is_array($email)) {
foreach ($email as $cle => $adresseMail) {
if (!$this->AddAddress($adresseMail)) {
$this->log("Erreur AddAddress $adresseMail : " . print_r($this->ErrorInfo, true), _LOG_ERREUR);
}
}
@ -227,7 +227,7 @@ class FacteurMail extends PHPMailer {
}
// S'il y a un contenu HTML
if (!empty($message_html)){
if (!empty($message_html)) {
$message_html = unicode_to_utf_8(charset2unicode($message_html, $charset));
$this->Body = $message_html;
@ -240,11 +240,11 @@ class FacteurMail extends PHPMailer {
}
// S'il y a un contenu texte brut
if (!empty($message_texte)){
if (!empty($message_texte)) {
$message_texte = unicode_to_utf_8(charset2unicode($message_texte, $charset));
// Si pas de HTML on le remplace en tant que contenu principal
if (!$this->Body){
if (!$this->Body) {
$this->IsHTML(false);
$this->Body = $message_texte;
} // Sinon on met le texte brut en contenu alternatif
@ -252,7 +252,6 @@ class FacteurMail extends PHPMailer {
$this->AltBody = $message_texte;
}
}
}
/**
@ -260,9 +259,9 @@ class FacteurMail extends PHPMailer {
*/
public function setImportant($important = true) {
if ($important) {
$this->addCustomHeader("X-Priority", "1 (High)" );
$this->addCustomHeader("X-MSMail-Priority", "High" );
$this->addCustomHeader("Importance", "High" );
$this->addCustomHeader('X-Priority', '1 (High)' );
$this->addCustomHeader('X-MSMail-Priority', 'High' );
$this->addCustomHeader('Importance', 'High' );
}
$this->important = $important;
}
@ -274,57 +273,57 @@ class FacteurMail extends PHPMailer {
* @param $include
*/
public function setSendFailFunction($function, $args, $include) {
$this->sendFailFunction = array(
$this->sendFailFunction = [
'function' => $function,
'args' => $args,
'include' => $include,
) ;
] ;
}
/**
* Generer le log informatif sur le mail qui va etre envoye
* @return string
*/
public function getMessageLog(){
public function getMessageLog() {
$this->forceFromIfNeeded();
$header = $this->CreateHeader();
$trace = trim($header) . "\n";
// completer le header avec les infos essentielles qu'on veut dans les logs
if (!empty($this->to) and strpos($trace, "To:" ) === false) {
if (!empty($this->to) and strpos($trace, 'To:' ) === false) {
$trace .= $this->addrAppend('To', $this->to);
}
if (!empty($this->cc) and strpos($trace, "Cc:" ) === false) {
if (!empty($this->cc) and strpos($trace, 'Cc:' ) === false) {
$trace .= $this->addrAppend('Cc', $this->cc);
}
if (!empty($this->bcc) and strpos($trace, "Bcc:" ) === false) {
if (!empty($this->bcc) and strpos($trace, 'Bcc:' ) === false) {
$trace .= $this->addrAppend('Bcc', $this->bcc);
}
if (strpos($trace, 'Subject:') === false) {
$trace .= "Subject: " . $this->Subject . "\n";
$trace .= 'Subject: ' . $this->Subject . "\n";
}
$message_desc = [];
if (!empty($this->Body)) {
$message_desc[] = "Body(".strlen($this->Body)."c)" ;
$message_desc[] = 'Body(' . strlen($this->Body) . 'c)' ;
}
if (!empty($this->AltBody)) {
$message_desc[] = "AltBody(".strlen($this->AltBody)."c)" ;
$message_desc[] = 'AltBody(' . strlen($this->AltBody) . 'c)' ;
}
if (!empty($this->attachment)) {
$message_desc[] = "Files(".count($this->attachment).")" ;
$message_desc[] = 'Files(' . count($this->attachment) . ')' ;
}
$trace .= "Message: " . implode(' ', $message_desc). "\n";
$trace .= 'Message: ' . implode(' ', $message_desc) . "\n";
return "Sent by " . get_class($this) . "\n" . rtrim($trace);
return 'Sent by ' . get_class($this) . "\n" . rtrim($trace);
}
/**
* @param bool $exceptions
*/
public function setExceptions($exceptions){
public function setExceptions($exceptions) {
$this->exceptions = ($exceptions ? true : false);
}
@ -334,24 +333,36 @@ class FacteurMail extends PHPMailer {
*
* @param string|null $baseUrl
*/
protected function urlsToAbsUrls($baseUrl = null){
if (preg_match_all(',(< (a|link)[[:space:]]+[^< >]*href=["\']?)([^"\' >< [:space:]]+)([^< >]*>),imsS',
$this->Body, $liens, PREG_SET_ORDER)){
foreach ($liens as $lien){
if (strncmp($lien[3], "cid:", 4)!==0){
protected function urlsToAbsUrls($baseUrl = null) {
if (
preg_match_all(
',(< (a|link)[[:space:]]+[^< >]*href=["\']?)([^"\' >< [:space:]]+)([^< >]*>),imsS',
$this->Body,
$liens,
PREG_SET_ORDER
)
) {
foreach ($liens as $lien) {
if (strncmp($lien[3], 'cid:', 4) !== 0) {
$abs = url_absolue($lien[3], $baseUrl);
if ($abs< >$lien[3] and !preg_match('/^#/', $lien[3])){
if ($abs < > $lien[3] and !preg_match('/^#/', $lien[3])) {
$this->Body = str_replace($lien[0], $lien[1] . $abs . $lien[4], $this->Body);
}
}
}
}
if (preg_match_all(',(< (img|script)[[:space:]]+[^< >]*src=["\']?)([^"\' >< [:space:]]+)([^< >]*>),imsS',
$this->Body, $liens, PREG_SET_ORDER)){
foreach ($liens as $lien){
if (strncmp($lien[3], "cid:", 4)!==0){
if (
preg_match_all(
',(< (img|script)[[:space:]]+[^< >]*src=["\']?)([^"\' >< [:space:]]+)([^< >]*>),imsS',
$this->Body,
$liens,
PREG_SET_ORDER
)
) {
foreach ($liens as $lien) {
if (strncmp($lien[3], 'cid:', 4) !== 0) {
$abs = url_absolue($lien[3], $baseUrl);
if ($abs< >$lien[3]){
if ($abs < > $lien[3]) {
$this->Body = str_replace($lien[0], $lien[1] . $abs . $lien[4], $this->Body);
}
}
@ -363,8 +374,8 @@ class FacteurMail extends PHPMailer {
* Embed les images HTML dans l'email
* @throws Exception
*/
protected function embedReferencedImages(){
$image_types = array(
protected function embedReferencedImages() {
$image_types = [
'gif' => 'image/gif',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
@ -374,37 +385,42 @@ class FacteurMail extends PHPMailer {
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
//'swf' => 'application/x-shockwave-flash' // on elever pour des raisons de securite et deprecie
);
$src_found = array();
$images_embeded = array();
if (preg_match_all(
'/["\'](([^"\']+)\.(' . implode('|', array_keys($image_types)) . '))([?][^"\']+)?([#][^"\']+)?["\']/Uims',
$this->Body, $images, PREG_SET_ORDER)){
];
$src_found = [];
$images_embeded = [];
if (
preg_match_all(
'/["\'](([^"\']+)\.(' . implode('|', array_keys($image_types)) . '))([?][^"\']+)?([#][^"\']+)?["\']/Uims',
$this->Body,
$images,
PREG_SET_ORDER
)
) {
$adresse_site = $GLOBALS['meta']['adresse_site'] . '/';
foreach ($images as $im){
foreach ($images as $im) {
$im = array_pad($im, 6, null);
$src_orig = $im[1] . $im[4] . $im[5];
if (!isset($src_found[$src_orig])){ // deja remplace ? rien a faire (ie la meme image presente plusieurs fois)
if (!isset($src_found[$src_orig])) { // deja remplace ? rien a faire (ie la meme image presente plusieurs fois)
// examiner le src et voir si embedable
$src = $im[1];
foreach ($this->urlsBase as $base) {
if ($src AND strncmp($src, $base, strlen($base))==0) {
if ($src and strncmp($src, $base, strlen($base)) == 0) {
$src = _DIR_RACINE . substr($src, strlen($base));
}
}
if ($src
AND !preg_match(",^([a-z0-9]+:)?//,i", $src)
AND (
if (
$src
and !preg_match(',^([a-z0-9]+:)?//,i', $src)
and (
file_exists($f = $src) // l'image a ete generee depuis le meme cote que l'envoi
OR (_DIR_RACINE AND file_exists($f = _DIR_RACINE . $src)) // l'image a ete generee dans le public et on est dans le prive
OR (!_DIR_RACINE AND file_exists($f = _DIR_RESTREINT . $src)) // l'image a ete generee dans le prive et on est dans le public
or (_DIR_RACINE and file_exists($f = _DIR_RACINE . $src)) // l'image a ete generee dans le public et on est dans le prive
or (!_DIR_RACINE and file_exists($f = _DIR_RESTREINT . $src)) // l'image a ete generee dans le prive et on est dans le public
)
){
if (!isset($images_embeded[$f])){
) {
if (!isset($images_embeded[$f])) {
$extension = strtolower($im[3]);
$header_extension = $image_types[$extension];
$cid = md5($f); // un id unique pour un meme fichier
@ -412,7 +428,7 @@ class FacteurMail extends PHPMailer {
$this->AddEmbeddedImage($f, $cid, basename($f), 'base64', $header_extension);
}
$this->Body = str_replace($src_orig, "cid:" . $images_embeded[$f], $this->Body);
$this->Body = str_replace($src_orig, 'cid:' . $images_embeded[$f], $this->Body);
$src_found[$src_orig] = $f;
}
}
@ -427,17 +443,17 @@ class FacteurMail extends PHPMailer {
* @param string $mode
* @return string
*/
protected function safeUtf8Decode($text, $mode = 'texte_brut'){
if (!is_utf8($text)){
protected function safeUtf8Decode($text, $mode = 'texte_brut') {
if (!is_utf8($text)) {
return ($text);
}
if (function_exists('iconv') & & $mode=='texte_brut'){
if (function_exists('iconv') & & $mode == 'texte_brut') {
$text = str_replace('’ ', "'", $text);
$text = iconv("UTF-8", "ISO-8859-1//TRANSLIT" , $text);
$text = iconv('UTF-8', 'ISO-8859-1//TRANSLIT' , $text);
return str_replace('’ ', "'", $text);
} else {
if ($mode=='texte_brut'){
if ($mode == 'texte_brut') {
$text = str_replace('’ ', "'", $text);
}
$text = unicode2charset(utf_8_to_unicode($text), 'iso-8859-1');
@ -448,7 +464,7 @@ class FacteurMail extends PHPMailer {
/**
* Convertir tout le mail utf en isotruc
*/
protected function convertMessageFromUtf8ToIso8859(){
protected function convertMessageFromUtf8ToIso8859() {
$this->CharSet = 'iso-8859-1';
$this->Body = str_ireplace('charset=utf-8', 'charset=iso-8859-1', $this->Body);
$this->Body = $this->safeUtf8Decode($this->Body, 'html');
@ -462,15 +478,16 @@ class FacteurMail extends PHPMailer {
* @throws Exception
*/
protected function forceFromIfNeeded() {
if ($this->ForceFrom
AND $this->From!==$this->ForceFrom){
if (
$this->ForceFrom
and $this->From !== $this->ForceFrom
) {
$forcedomain = explode('@', $this->ForceFrom);
$forcedomain = end($forcedomain);
$domain = explode('@', $this->From);
$domain = end($domain);
if ($domain!==$forcedomain){
if ($domain !== $forcedomain) {
// le From passe en ReplyTo
$this->AddReplyTo($this->From, $this->FromName);
// on force le From
@ -483,12 +500,12 @@ class FacteurMail extends PHPMailer {
/**
* Clear all recipients
*/
public function clearAllRecipients(){
public function clearAllRecipients() {
parent::clearAllRecipients();
if (!empty($this->autoCc)) {
$this->AddCC($this->autoCc);
}
if (!empty($this->autoBcc)){
if (!empty($this->autoBcc)) {
$this->AddBCC($this->autoBcc);
}
}
@ -502,7 +519,7 @@ class FacteurMail extends PHPMailer {
protected function sendAlertIfNeeded($res) {
if ($res === false) {
if ($this->important and !empty($this->sendFailFunction)) {
$facteur_envoyer_alerte_fail = charger_fonction('facteur_envoyer_alerte_fail','inc');
$facteur_envoyer_alerte_fail = charger_fonction('facteur_envoyer_alerte_fail', 'inc');
$facteur_envoyer_alerte_fail($this->sendFailFunction['function'], $this->sendFailFunction['args'], $this->sendFailFunction['include']);
}
}
@ -517,22 +534,22 @@ class FacteurMail extends PHPMailer {
* @return bool
* @throws phpmailerException
*/
protected function callWrapper($function, $args){
protected function callWrapper($function, $args) {
$exceptions = $this->exceptions;
$this->exceptions = true;
try {
$retour = call_user_func_array($function, $args);
$this->exceptions = $exceptions;
} catch (Exception $exc) {
$this->log((is_array($function) ? implode('::', $function) : $function) . "() : " . $exc->getMessage(), _LOG_ERREUR);
$this->log((is_array($function) ? implode('::', $function) : $function) . '() : ' . $exc->getMessage(), _LOG_ERREUR);
$this->exceptions = $exceptions;
if ($this->exceptions){
if ($this->exceptions) {
throw $exc;
}
return false;
}
if ($this->ErrorInfo){
$this->log((is_array($function) ? implode('::', $function) : $function) . "() : " . $this->ErrorInfo, _LOG_ERREUR);
if ($this->ErrorInfo) {
$this->log((is_array($function) ? implode('::', $function) : $function) . '() : ' . $this->ErrorInfo, _LOG_ERREUR);
}
return $retour;
@ -548,33 +565,33 @@ class FacteurMail extends PHPMailer {
* @return bool
* @throws Exception
*/
public function Send(){
public function Send() {
$this->forceFromIfNeeded();
if ($this->convertMessageToIso8859){
if ($this->convertMessageToIso8859) {
$this->convertMessageFromUtf8ToIso8859();
}
$args = func_get_args();
$res = $this->callWrapper(array('parent', 'Send') , $args);
$res = $this->callWrapper(['parent', 'Send'] , $args);
return $this->sendAlertIfNeeded($res);
}
public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment'){
public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') {
$args = func_get_args();
return $this->callWrapper(array('parent', 'AddAttachment') , $args);
return $this->callWrapper(['parent', 'AddAttachment'] , $args);
}
public function AddReplyTo($address, $name = ''){
public function AddReplyTo($address, $name = '') {
$args = func_get_args();
return $this->callWrapper(array('parent', 'AddReplyTo') , $args);
return $this->callWrapper(['parent', 'AddReplyTo'] , $args);
}
public function AddBCC($address, $name = ''){
public function AddBCC($address, $name = '') {
$args = func_get_args();
return $this->callWrapper(array('parent', 'AddBCC') , $args);
return $this->callWrapper(['parent', 'AddBCC'] , $args);
}
public function AddCC($address, $name = ''){
public function AddCC($address, $name = '') {
$args = func_get_args();
return $this->callWrapper(array('parent', 'AddCC') , $args);
return $this->callWrapper(['parent', 'AddCC'] , $args);
}
}