diff --git a/assets/mail_templates/default.html b/assets/mail_templates/default.html new file mode 100644 index 0000000..c6f302b --- /dev/null +++ b/assets/mail_templates/default.html @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + +
+ + + + + + + +
+

{HEADER}

+
+

{TITLE}

+

{MESSAGE}

+ + + + +
+

+ {LINKNAME} +

+
+

{FOOTER}

+
+
+ + + + +
+
+ + \ No newline at end of file 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 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 diff --git a/inc/func.php b/inc/func.php index f445e7a..7a9b06d 100644 --- a/inc/func.php +++ b/inc/func.php @@ -273,6 +273,37 @@ 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', + 'LINK' => 'https://it-stories.ru/', + 'LINKNAME' => 'Go to site', + 'FOOTER' => 'Thanks!', + 'SERVERNAME' => 'it-stories.ru' + ) + ); + + + + // прикрепляем лог, если он есть + if(isset($file) and !empty($file) and file_exists($file)){ + $mail->addFile($file); + } + $mail->sendUsingTemplate($template); + + return; + } /** * Отправка уведомления пользователю * 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; diff --git a/inc/lib/CMail.class.php b/inc/lib/CMail.class.php index db4d249..28724e1 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,288 @@ 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_contents(__DIR__.'/../../assets/mail_templates/'.$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; + } +} + + + +/** + * Класс для отправки 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())); + + // Заголовок письма + $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 diff --git a/test2.php b/test2.php new file mode 100644 index 0000000..fb2b60b --- /dev/null +++ b/test2.php @@ -0,0 +1,41 @@ +dump = true; + $mail->dumpPath = $_SERVER['DOCUMENT_ROOT'].'/uploads/emails'; + $mail->from('iot@'.$_SERVER['SERVER_NAME'], 'Система оповещений IoT Core'); + $mail->to(ADMIN_EMAIL, 'Администратор панели'); + $mail->subject = 'Проверка почтовой подсистемы'; + $mail->assignTemplateVars( + array( + 'HEADER' => 'IoT Core Board', + 'MESSAGE' => '
'.print_r($output, true).'
', + 'TITLE' => 'Код: '.$retval, + '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