From 25fc2ab9bc508c1b30d21487c0fa920034b9a7fa Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 12:51:27 +0300 Subject: [PATCH 01/15] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=20?= =?UTF-8?q?=D1=81=20=D1=88=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/lib/CCache.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/lib/CCache.class.php b/inc/lib/CCache.class.php index aabac9d..5434827 100644 --- a/inc/lib/CCache.class.php +++ b/inc/lib/CCache.class.php @@ -173,7 +173,7 @@ class CCache * @return int Размер кэша в байтах или false */ public static function getCacheSize():int - { + { // Получить размер кэша $return_size = 0; foreach (scandir(self::$cache_dir) as $file) { if ($file == '.' or $file == '..') continue; From e8496feed899659bce2de79e93e8518d1c348bd0 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 13:58:46 +0300 Subject: [PATCH 02/15] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=88=D0=B0=D0=B1=D0=BE=D0=BD=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=B2=20=D0=BF=D0=B8=D1=81=D1=8C=D0=BC=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/mail_templates/default.html | 148 +++++++++++++++++++++++++++++ inc/func.php | 29 ++++++ inc/lib/CMail.class.php | 84 +++++++++++++++- test.php | 4 +- 4 files changed, 262 insertions(+), 3 deletions(-) create mode 100644 assets/mail_templates/default.html diff --git a/assets/mail_templates/default.html b/assets/mail_templates/default.html new file mode 100644 index 0000000..24e993a --- /dev/null +++ b/assets/mail_templates/default.html @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + +
+ + + + + + + +
+

{HEADER}

+
+

{TITLE}

+

{MESSAGE}

+ + + + +
+

+ {LINKNAME} +

+
+

{FOOTER}

+
+
+ + + + +
+
+ + \ No newline at end of file diff --git a/inc/func.php b/inc/func.php index f445e7a..fd93233 100644 --- a/inc/func.php +++ b/inc/func.php @@ -273,6 +273,35 @@ function getOS() { return; } + + /** + * Отправка уведомления на почту администратору с использованием шаблонов + */ +function adminSendMailWithTemplate($template, $subject, $message, $file = false){ + $mail = new CMail; + $mail->from('iot@'.$_SERVER['SERVER_NAME'], 'Система оповещений IoT Core'); + $mail->to(ADMIN_EMAIL, 'Администратор панели'); + $mail->subject = $subject; + $mail->assignTemplateVars( + array( + 'HEADER' => 'IoT Core', + 'MESSAGE' => 'test0', + 'TITLE' => 'test title', + 'LINKNAME' => 'Go to site', + 'FOOTER' => 'Thanks!' + ) + ); + + + + // прикрепляем лог, если он есть + if(isset($file) and !empty($file) and file_exists($file)){ + $mail->addFile($file); + } + $mail->sendUsingTemplate($template); + + return; + } /** * Отправка уведомления пользователю * diff --git a/inc/lib/CMail.class.php b/inc/lib/CMail.class.php index db4d249..66c9175 100644 --- a/inc/lib/CMail.class.php +++ b/inc/lib/CMail.class.php @@ -31,6 +31,11 @@ class CMail * Текст */ public $body = ''; + + /** + * Массив с данными для подстановки в шаблон + */ + public $arrTemplate = []; /** * Массив заголовков файлов @@ -112,6 +117,10 @@ class CMail $this->toEmail = $email; $this->toName = $name; } + + public function assignTemplateVars($arrVars) { + $this->arrTemplate = $arrVars; + } /** * Добавление файла к письму @@ -239,7 +248,80 @@ class CMail // Дамп письма в файл if ($this->dump == true) { if (empty($this->dumpPath)) { - $this->dumpPath = dirname(__FILE__) . '/sendmail'; + $this->dumpPath = dirname(__FILE__) . '/uploads'; + } + + $dump = array_merge($headers, array('To: ' . $to, 'Subject: ' . $subject, ''), $message); + $file = $this->safeFile($this->dumpPath . '/' . date('Y-m-d_H-i-s') . '.eml'); + file_put_contents($file, implode("\r\n", $dump)); + } + $res[] = mb_send_mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers)); + } + + return $res; + } + + public function sendUsingTemplate($template = 'default') { + if (empty($this->toEmail)) { + return false; + } + + // От кого + $from = (empty($this->fromName)) ? $this->fromEmail : '=?UTF-8?B?' . base64_encode($this->fromName) . '?= <' . $this->fromEmail . '>'; + + // Кому + $array_to = array(); + foreach (explode(',', $this->toEmail) as $row) { + $row = trim($row); + if (!empty($row)) { + $array_to[] = (empty($this->toName)) ? $row : '=?UTF-8?B?' . base64_encode($this->toName) . '?= <' . $row . '>'; + } + } + + // Тема письма + $subject = (empty($this->subject)) ? 'No subject' : $this->subject; + + $body = file_get_contenst(__DIR__.'/../../assets/mail_template/'.$template.'.html'); + foreach($this->arrTemplate as $templateKey => $templateValue){ + $body = str_replace('{'.$templateKey.'}', $templateValue), $body); + } + + + $boundary = md5(uniqid(time())); + + // Заголовок письма + $headers = array( + 'Content-Type: multipart/mixed; boundary="' . $boundary . '"', + 'Content-Transfer-Encoding: 7bit', + 'MIME-Version: 1.0', + 'From: ' . $from, + 'Date: ' . date('r') + ); + + // Тело письма + $message = array( + '--' . $boundary, + 'Content-Type: text/html; charset=UTF-8', + 'Content-Transfer-Encoding: base64', + '', + chunk_split(base64_encode($body)) + ); + + if (!empty($this->_files)) { + foreach ($this->_files as $row) { + $message = array_merge($message, array('', '--' . $boundary), $row); + } + } + + $message[] = ''; + $message[] = '--' . $boundary . '--'; + $res = array(); + + foreach ($array_to as $to) { + // Дамп письма в файл + if ($this->dump == true) { + if (empty($this->dumpPath)) { + $this->dumpPath = dirname(__FILE__) . '/uploads'; } $dump = array_merge($headers, array('To: ' . $to, 'Subject: ' . $subject, ''), $message); diff --git a/test.php b/test.php index 9c3661c..d12d66f 100644 --- a/test.php +++ b/test.php @@ -6,6 +6,6 @@ require_once __DIR__.'/inc/bootstrap.php'; if(!CUser::is_admin()) { die('403 - Access denied'); } -userSendMail(1, 'Test userMail', 'Hello!!!',false); -//adminSendMail('Тестовое уведомление', 'Запушен тестовый скрипт для проверки функционала почтовых уведомлений.
Если Вы видите данное сообщение - значит система работает.'); +//userSendMail(1, 'Test userMail', 'Hello!!!',false); +adminSendMailWithTemplate('default', 'Тестовое уведомление', 'Запушен тестовый скрипт для проверки функционала почтовых уведомлений.
Если Вы видите данное сообщение - значит система работает.'); echo 'ok'; \ No newline at end of file From ffaf1839bad1dbfb3c056945e3aad2d3ac9d056e Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 14:01:09 +0300 Subject: [PATCH 03/15] fix --- inc/lib/CMail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/lib/CMail.class.php b/inc/lib/CMail.class.php index 66c9175..d6d8ee1 100644 --- a/inc/lib/CMail.class.php +++ b/inc/lib/CMail.class.php @@ -283,7 +283,7 @@ class CMail $body = file_get_contenst(__DIR__.'/../../assets/mail_template/'.$template.'.html'); foreach($this->arrTemplate as $templateKey => $templateValue){ - $body = str_replace('{'.$templateKey.'}', $templateValue), $body); + $body = str_replace('{'.$templateKey.'}', $templateValue, $body); } From 354a539b919439b2674a7d5dd886881cfad6557a Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 14:09:27 +0300 Subject: [PATCH 04/15] fix --- inc/lib/CMail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/lib/CMail.class.php b/inc/lib/CMail.class.php index d6d8ee1..9ee2f64 100644 --- a/inc/lib/CMail.class.php +++ b/inc/lib/CMail.class.php @@ -281,7 +281,7 @@ class CMail // Тема письма $subject = (empty($this->subject)) ? 'No subject' : $this->subject; - $body = file_get_contenst(__DIR__.'/../../assets/mail_template/'.$template.'.html'); + $body = file_get_contents(__DIR__.'/../../assets/mail_template/'.$template.'.html'); foreach($this->arrTemplate as $templateKey => $templateValue){ $body = str_replace('{'.$templateKey.'}', $templateValue, $body); } From df9258417b0468ef6c1cecede4c8168362f0f5d2 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 14:10:28 +0300 Subject: [PATCH 05/15] small fix dir --- inc/lib/CMail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/lib/CMail.class.php b/inc/lib/CMail.class.php index 9ee2f64..63b38bd 100644 --- a/inc/lib/CMail.class.php +++ b/inc/lib/CMail.class.php @@ -281,7 +281,7 @@ class CMail // Тема письма $subject = (empty($this->subject)) ? 'No subject' : $this->subject; - $body = file_get_contents(__DIR__.'/../../assets/mail_template/'.$template.'.html'); + $body = file_get_contents(__DIR__.'/../../assets/mail_templates/'.$template.'.html'); foreach($this->arrTemplate as $templateKey => $templateValue){ $body = str_replace('{'.$templateKey.'}', $templateValue, $body); } From 06d985a4ddec80d109356570700b2d4b8afd47cc Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 14:15:10 +0300 Subject: [PATCH 06/15] fix --- assets/mail_templates/default.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/assets/mail_templates/default.html b/assets/mail_templates/default.html index 24e993a..4dcbe4c 100644 --- a/assets/mail_templates/default.html +++ b/assets/mail_templates/default.html @@ -79,10 +79,10 @@ width: 100% !important; border-collapse: collapse; } .container .masthead { - padding: 80px 0; + padding: 18px 0; background: #71bc37; color: white; } - .container .masthead h1 { + .container .masthead h1 { margin: 0 auto !important; max-width: 90%; text-transform: uppercase; } @@ -120,7 +120,7 @@

- {LINKNAME} + {LINKNAME}

From 6085368aa77d9dc4ae1f66a5be7f3a3ba161b85f Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 14:15:59 +0300 Subject: [PATCH 07/15] fix --- inc/func.php | 1 + 1 file changed, 1 insertion(+) diff --git a/inc/func.php b/inc/func.php index fd93233..589eee1 100644 --- a/inc/func.php +++ b/inc/func.php @@ -287,6 +287,7 @@ function adminSendMailWithTemplate($template, $subject, $message, $file = false) 'HEADER' => 'IoT Core', 'MESSAGE' => 'test0', 'TITLE' => 'test title', + 'LINK' => 'https://it-stories.ru/', 'LINKNAME' => 'Go to site', 'FOOTER' => 'Thanks!' ) From 6320bc4735bb243ecc32df8288757ef21327f756 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 14:17:17 +0300 Subject: [PATCH 08/15] fix h1 --- assets/mail_templates/default.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/assets/mail_templates/default.html b/assets/mail_templates/default.html index 4dcbe4c..c6f302b 100644 --- a/assets/mail_templates/default.html +++ b/assets/mail_templates/default.html @@ -84,8 +84,7 @@ color: white; } .container .masthead h1 { margin: 0 auto !important; - max-width: 90%; - text-transform: uppercase; } + max-width: 90%; } .container .content { background: white; padding: 30px 35px; } From ab0b08ad7ad8c5f54e1eb4525403976f880f84d4 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 14:18:39 +0300 Subject: [PATCH 09/15] add servername to template --- inc/func.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/inc/func.php b/inc/func.php index 589eee1..7a9b06d 100644 --- a/inc/func.php +++ b/inc/func.php @@ -289,7 +289,8 @@ function adminSendMailWithTemplate($template, $subject, $message, $file = false) 'TITLE' => 'test title', 'LINK' => 'https://it-stories.ru/', 'LINKNAME' => 'Go to site', - 'FOOTER' => 'Thanks!' + 'FOOTER' => 'Thanks!', + 'SERVERNAME' => 'it-stories.ru' ) ); From f477e6ba5aed3d7d25951cfd36ae35b9eadf06f5 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 17:19:01 +0300 Subject: [PATCH 10/15] add test2.php --- test2.php | 248 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 test2.php diff --git a/test2.php b/test2.php new file mode 100644 index 0000000..7f49bd1 --- /dev/null +++ b/test2.php @@ -0,0 +1,248 @@ +fromEmail = $email; + $this->fromName = $name; + } + + /** + * Кому + */ + public function to($email, $name = null) + { + $this->toEmail = $email; + $this->toName = $name; + } + + /** + * Установка переменных шаблона + */ + public function assignTemplateVars($arrVars) { + $this->arrTemplate = $arrVars; + } + + + /** + * Добавление файла к письму + */ + public function addFile($filename) + { + if (is_file($filename)) { + $name = basename($filename); + $fp = fopen($filename, 'rb'); + $file = fread($fp, filesize($filename)); + fclose($fp); + $this->_files[] = array( + 'Content-Type: application/octet-stream; name="' . $name . '"', + 'Content-Transfer-Encoding: base64', + 'Content-Disposition: attachment; filename="' . $name . '"', + '', + chunk_split(base64_encode($file)), + ); + } + } + + /** + * Проверка существования файла + * Если директория не существует - пытается её создать. + * Если файл существует - к концу файла приписывает префикс. + */ + private function safeFile($filename) + { + $dir = dirname($filename); + if (!is_dir($dir)) { + mkdir($dir, 0777, true); + } + + $info = pathinfo($filename); + $name = $dir . '/' . $info['filename']; + $ext = (empty($info['extension'])) ? '' : '.' . $info['extension']; + $prefix = ''; + + if (is_file($name . $ext)) { + $i = 1; + $prefix = '_' . $i; + + while (is_file($name . $prefix . $ext)) { + $prefix = '_' . ++$i; + } + } + + return $name . $prefix . $ext; + } + + /** + * Отправка + */ + public function send() { + if (empty($this->toEmail)) { + return false; + } + + // От кого + $from = (empty($this->fromName)) ? $this->fromEmail : '=?UTF-8?B?' . base64_encode($this->fromName) . '?= <' . $this->fromEmail . '>'; + + // Кому + $array_to = array(); + foreach (explode(',', $this->toEmail) as $row) { + $row = trim($row); + if (!empty($row)) { + $array_to[] = (empty($this->toName)) ? $row : '=?UTF-8?B?' . base64_encode($this->toName) . '?= <' . $row . '>'; + } + } + + // Тема письма + $subject = (empty($this->subject)) ? 'No subject' : $this->subject; + + + $body = file_get_contents($this->templateDir.'/'.$this->template.'.html'); + + foreach($this->arrTemplate as $templateKey => $templateValue){ + $body = str_replace('{'.$templateKey.'}', $templateValue, $body); + } + + + $boundary = md5(uniqid(time())); + + // Заголовок письма + $headers = array( + 'Content-Type: multipart/mixed; boundary="' . $boundary . '"', + 'Content-Transfer-Encoding: 7bit', + 'MIME-Version: 1.0', + 'From: ' . $from, + 'Date: ' . date('r') + ); + + // Тело письма + $message = array( + '--' . $boundary, + 'Content-Type: text/html; charset=UTF-8', + 'Content-Transfer-Encoding: base64', + '', + chunk_split(base64_encode($body)) + ); + + if (!empty($this->_files)) { + foreach ($this->_files as $row) { + $message = array_merge($message, array('', '--' . $boundary), $row); + } + } + + $message[] = ''; + $message[] = '--' . $boundary . '--'; + $res = array(); + + foreach ($array_to as $to) { + // Дамп письма в файл + if ($this->dump == true) { + if (empty($this->dumpPath)) { + $this->dumpPath = dirname(__FILE__) . '/uploads'; + } + + $dump = array_merge($headers, array('To: ' . $to, 'Subject: ' . $subject, ''), $message); + $file = $this->safeFile($this->dumpPath . '/' . date('Y-m-d_H-i-s') . '.eml'); + file_put_contents($file, implode("\r\n", $dump)); + } + $res[] = mb_send_mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers)); + } + + return $res; + } +} + + + + + + + $mail = new CMail2; + $mail->dump = true; + $mail->dumpPath = $_SERVER['DOCUMENT_ROOT'].'/uploads'; + $mail->from('iot@'.$_SERVER['SERVER_NAME'], 'Система оповещений IoT Core'); + $mail->to(ADMIN_EMAIL, 'Администратор панели'); + $mail->subject = 'Проверка почтовой подсистемы'; + $mail->assignTemplateVars( + array( + 'HEADER' => 'IoT Core Board', + 'MESSAGE' => 'Произошла проверка почтовой рассылки с помощью нового класса', + 'TITLE' => 'Уведомление системы', + 'LINK' => 'https://it-stories.ru/', + 'LINKNAME' => 'Перейти в панель', + 'FOOTER' => 'Сообщение сгенерировано автоматически', + 'SERVERNAME' => 'it-stories.ru' + ) + ); + + $mail->template = 'default'; + $mail->templateDir = $_SERVER['DOCUMENT_ROOT'].'/assets/mail_templates'; + + + // прикрепляем лог, если он есть + if(isset($file) and !empty($file) and file_exists($file)){ + $mail->addFile($file); + } + $mail->send(); \ No newline at end of file From 3ec47d0272c289b3fc4e8b383d47ec179047fc89 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 17:22:05 +0300 Subject: [PATCH 11/15] add class cmail2 --- inc/lib/CMail.class.php | 208 +++++++++++++++++++++++++++++++++++++++ test2.php | 210 ---------------------------------------- 2 files changed, 208 insertions(+), 210 deletions(-) diff --git a/inc/lib/CMail.class.php b/inc/lib/CMail.class.php index 63b38bd..28724e1 100644 --- a/inc/lib/CMail.class.php +++ b/inc/lib/CMail.class.php @@ -287,6 +287,214 @@ class CMail } + $boundary = md5(uniqid(time())); + + // Заголовок письма + $headers = array( + 'Content-Type: multipart/mixed; boundary="' . $boundary . '"', + 'Content-Transfer-Encoding: 7bit', + 'MIME-Version: 1.0', + 'From: ' . $from, + 'Date: ' . date('r') + ); + + // Тело письма + $message = array( + '--' . $boundary, + 'Content-Type: text/html; charset=UTF-8', + 'Content-Transfer-Encoding: base64', + '', + chunk_split(base64_encode($body)) + ); + + if (!empty($this->_files)) { + foreach ($this->_files as $row) { + $message = array_merge($message, array('', '--' . $boundary), $row); + } + } + + $message[] = ''; + $message[] = '--' . $boundary . '--'; + $res = array(); + + foreach ($array_to as $to) { + // Дамп письма в файл + if ($this->dump == true) { + if (empty($this->dumpPath)) { + $this->dumpPath = dirname(__FILE__) . '/uploads'; + } + + $dump = array_merge($headers, array('To: ' . $to, 'Subject: ' . $subject, ''), $message); + $file = $this->safeFile($this->dumpPath . '/' . date('Y-m-d_H-i-s') . '.eml'); + file_put_contents($file, implode("\r\n", $dump)); + } + $res[] = mb_send_mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers)); + } + + return $res; + } +} + + + +/** + * Класс для отправки E-Mail с использованием почтовых шаблонов + */ +class CMail2 { + /** + * Шаблон письма + */ + public $template = 'default'; + + /** + * Дирректория с шаблонами писем + */ + public $templateDir = '/assets/mail_templates/'; + + /** + * От кого + */ + public $fromEmail = ''; + public $fromName = ''; + + /** + * Кому + */ + public $toEmail = ''; + public $toName = ''; + + /** + * Тема + */ + public $subject = ''; + + /** + * Массив с данными для подстановки в шаблон + */ + public $arrTemplate = []; + + /** + * Массив заголовков файлов + */ + private $_files = array(); + + /** + * Создавать письмо в файл при отправке + */ + public $dump = false; + + /** + * Директория сохранения писем + */ + public $dumpPath = ''; + + + /** + * От кого + */ + public function from($email, $name = null) + { + $this->fromEmail = $email; + $this->fromName = $name; + } + + /** + * Кому + */ + public function to($email, $name = null) + { + $this->toEmail = $email; + $this->toName = $name; + } + + /** + * Установка переменных шаблона + */ + public function assignTemplateVars($arrVars) { + $this->arrTemplate = $arrVars; + } + + + /** + * Добавление файла к письму + */ + public function addFile($filename) + { + if (is_file($filename)) { + $name = basename($filename); + $fp = fopen($filename, 'rb'); + $file = fread($fp, filesize($filename)); + fclose($fp); + $this->_files[] = array( + 'Content-Type: application/octet-stream; name="' . $name . '"', + 'Content-Transfer-Encoding: base64', + 'Content-Disposition: attachment; filename="' . $name . '"', + '', + chunk_split(base64_encode($file)), + ); + } + } + + /** + * Проверка существования файла + * Если директория не существует - пытается её создать. + * Если файл существует - к концу файла приписывает префикс. + */ + private function safeFile($filename) + { + $dir = dirname($filename); + if (!is_dir($dir)) { + mkdir($dir, 0777, true); + } + + $info = pathinfo($filename); + $name = $dir . '/' . $info['filename']; + $ext = (empty($info['extension'])) ? '' : '.' . $info['extension']; + $prefix = ''; + + if (is_file($name . $ext)) { + $i = 1; + $prefix = '_' . $i; + + while (is_file($name . $prefix . $ext)) { + $prefix = '_' . ++$i; + } + } + + return $name . $prefix . $ext; + } + + /** + * Отправка + */ + public function send() { + if (empty($this->toEmail)) { + return false; + } + + // От кого + $from = (empty($this->fromName)) ? $this->fromEmail : '=?UTF-8?B?' . base64_encode($this->fromName) . '?= <' . $this->fromEmail . '>'; + + // Кому + $array_to = array(); + foreach (explode(',', $this->toEmail) as $row) { + $row = trim($row); + if (!empty($row)) { + $array_to[] = (empty($this->toName)) ? $row : '=?UTF-8?B?' . base64_encode($this->toName) . '?= <' . $row . '>'; + } + } + + // Тема письма + $subject = (empty($this->subject)) ? 'No subject' : $this->subject; + + + $body = file_get_contents($this->templateDir.'/'.$this->template.'.html'); + + foreach($this->arrTemplate as $templateKey => $templateValue){ + $body = str_replace('{'.$templateKey.'}', $templateValue, $body); + } + + $boundary = md5(uniqid(time())); // Заголовок письма diff --git a/test2.php b/test2.php index 7f49bd1..89c6b30 100644 --- a/test2.php +++ b/test2.php @@ -8,216 +8,6 @@ if(!CUser::is_admin()) { } -/** - * Класс для отправки E-Mail с использованием почтовых шаблонов - */ -class CMail2 { - /** - * Шаблон письма - */ - public $template = 'default'; - - /** - * Дирректория с шаблонами писем - */ - public $templateDir = '/mail_templates/'; - - /** - * От кого - */ - public $fromEmail = ''; - public $fromName = ''; - - /** - * Кому - */ - public $toEmail = ''; - public $toName = ''; - - /** - * Тема - */ - public $subject = ''; - - /** - * Массив с данными для подстановки в шаблон - */ - public $arrTemplate = []; - - /** - * Массив заголовков файлов - */ - private $_files = array(); - - /** - * Управление дампированием - */ - public $dump = false; - - /** - * Директория куда сохранять письма - */ - public $dumpPath = ''; - - - /** - * От кого - */ - public function from($email, $name = null) - { - $this->fromEmail = $email; - $this->fromName = $name; - } - - /** - * Кому - */ - public function to($email, $name = null) - { - $this->toEmail = $email; - $this->toName = $name; - } - - /** - * Установка переменных шаблона - */ - public function assignTemplateVars($arrVars) { - $this->arrTemplate = $arrVars; - } - - - /** - * Добавление файла к письму - */ - public function addFile($filename) - { - if (is_file($filename)) { - $name = basename($filename); - $fp = fopen($filename, 'rb'); - $file = fread($fp, filesize($filename)); - fclose($fp); - $this->_files[] = array( - 'Content-Type: application/octet-stream; name="' . $name . '"', - 'Content-Transfer-Encoding: base64', - 'Content-Disposition: attachment; filename="' . $name . '"', - '', - chunk_split(base64_encode($file)), - ); - } - } - - /** - * Проверка существования файла - * Если директория не существует - пытается её создать. - * Если файл существует - к концу файла приписывает префикс. - */ - private function safeFile($filename) - { - $dir = dirname($filename); - if (!is_dir($dir)) { - mkdir($dir, 0777, true); - } - - $info = pathinfo($filename); - $name = $dir . '/' . $info['filename']; - $ext = (empty($info['extension'])) ? '' : '.' . $info['extension']; - $prefix = ''; - - if (is_file($name . $ext)) { - $i = 1; - $prefix = '_' . $i; - - while (is_file($name . $prefix . $ext)) { - $prefix = '_' . ++$i; - } - } - - return $name . $prefix . $ext; - } - - /** - * Отправка - */ - public function send() { - if (empty($this->toEmail)) { - return false; - } - - // От кого - $from = (empty($this->fromName)) ? $this->fromEmail : '=?UTF-8?B?' . base64_encode($this->fromName) . '?= <' . $this->fromEmail . '>'; - - // Кому - $array_to = array(); - foreach (explode(',', $this->toEmail) as $row) { - $row = trim($row); - if (!empty($row)) { - $array_to[] = (empty($this->toName)) ? $row : '=?UTF-8?B?' . base64_encode($this->toName) . '?= <' . $row . '>'; - } - } - - // Тема письма - $subject = (empty($this->subject)) ? 'No subject' : $this->subject; - - - $body = file_get_contents($this->templateDir.'/'.$this->template.'.html'); - - foreach($this->arrTemplate as $templateKey => $templateValue){ - $body = str_replace('{'.$templateKey.'}', $templateValue, $body); - } - - - $boundary = md5(uniqid(time())); - - // Заголовок письма - $headers = array( - 'Content-Type: multipart/mixed; boundary="' . $boundary . '"', - 'Content-Transfer-Encoding: 7bit', - 'MIME-Version: 1.0', - 'From: ' . $from, - 'Date: ' . date('r') - ); - - // Тело письма - $message = array( - '--' . $boundary, - 'Content-Type: text/html; charset=UTF-8', - 'Content-Transfer-Encoding: base64', - '', - chunk_split(base64_encode($body)) - ); - - if (!empty($this->_files)) { - foreach ($this->_files as $row) { - $message = array_merge($message, array('', '--' . $boundary), $row); - } - } - - $message[] = ''; - $message[] = '--' . $boundary . '--'; - $res = array(); - - foreach ($array_to as $to) { - // Дамп письма в файл - if ($this->dump == true) { - if (empty($this->dumpPath)) { - $this->dumpPath = dirname(__FILE__) . '/uploads'; - } - - $dump = array_merge($headers, array('To: ' . $to, 'Subject: ' . $subject, ''), $message); - $file = $this->safeFile($this->dumpPath . '/' . date('Y-m-d_H-i-s') . '.eml'); - file_put_contents($file, implode("\r\n", $dump)); - } - $res[] = mb_send_mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers)); - } - - return $res; - } -} - - - - - $mail = new CMail2; $mail->dump = true; From deaa0d3daf110c19c4e14ba8951d44c94878f0df Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 17:22:44 +0300 Subject: [PATCH 12/15] fix dir --- test2.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test2.php b/test2.php index 89c6b30..c7c789a 100644 --- a/test2.php +++ b/test2.php @@ -11,7 +11,7 @@ if(!CUser::is_admin()) { $mail = new CMail2; $mail->dump = true; - $mail->dumpPath = $_SERVER['DOCUMENT_ROOT'].'/uploads'; + $mail->dumpPath = $_SERVER['DOCUMENT_ROOT'].'/uploads/emails'; $mail->from('iot@'.$_SERVER['SERVER_NAME'], 'Система оповещений IoT Core'); $mail->to(ADMIN_EMAIL, 'Администратор панели'); $mail->subject = 'Проверка почтовой подсистемы'; From fd0c492e52f5f325ef5ce80bd785299bd7316e88 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 7 Dec 2021 17:24:54 +0300 Subject: [PATCH 13/15] fix --- test2.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test2.php b/test2.php index c7c789a..fb2b60b 100644 --- a/test2.php +++ b/test2.php @@ -7,6 +7,9 @@ if(!CUser::is_admin()) { die('403 - Access denied'); } +$output=null; +$retval=null; +exec('uptime', $output, $retval); $mail = new CMail2; @@ -18,8 +21,8 @@ if(!CUser::is_admin()) { $mail->assignTemplateVars( array( 'HEADER' => 'IoT Core Board', - 'MESSAGE' => 'Произошла проверка почтовой рассылки с помощью нового класса', - 'TITLE' => 'Уведомление системы', + 'MESSAGE' => '
'.print_r($output, true).'
', + 'TITLE' => 'Код: '.$retval, 'LINK' => 'https://it-stories.ru/', 'LINKNAME' => 'Перейти в панель', 'FOOTER' => 'Сообщение сгенерировано автоматически', From 2989c00f52305f23362a3b289075061d4c8e1c6b Mon Sep 17 00:00:00 2001 From: Roman Sergeevitch Grinko Date: Tue, 7 Dec 2021 20:32:13 +0300 Subject: [PATCH 14/15] Delete debugger.xml --- debugger.xml | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 debugger.xml diff --git a/debugger.xml b/debugger.xml deleted file mode 100644 index 544ab15..0000000 --- a/debugger.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file From 7ba93851ae15ca6b828d5f8bfc6474c5dd53647c Mon Sep 17 00:00:00 2001 From: Roman Sergeevitch Grinko Date: Tue, 7 Dec 2021 20:32:33 +0300 Subject: [PATCH 15/15] Delete github.xml --- github.xml | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 github.xml diff --git a/github.xml b/github.xml deleted file mode 100644 index 0eca9de..0000000 --- a/github.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file