Files
ave-cms-alt/functions/func.mail.php

349 lines
13 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* AVE.cms
*
* @package AVE.cms
* @version 3.x
* @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
*
* @license GPL v.2
*/
// ----------------------------------------------------------------------
// БЛОК SYMFONY MAILER
// ----------------------------------------------------------------------
// Подключаем Composer Autoload для Symfony
require_once BASE_DIR . '/lib/SymfonyMailer/vendor/autoload.php';
// Импорт необходимых классов Symfony Mailer
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
// ----------------------------------------------------------------------
// БЛОК PHPMailer
// ----------------------------------------------------------------------
// Подключаем Composer Autoload для PHPMailer
require_once BASE_DIR . '/lib/PHPMailer/vendor/autoload.php';
// Импорт необходимых классов PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
// ----------------------------------------------------------------------
/**
* Отправка e-Mail
*/
if (! function_exists('send_mail'))
{
function send_mail($to='', $body='', $subject='', $from_email='', $from_name='', $type='text', $attach=array(), $saveattach=true, $signature=true)
{
unset($transport, $message, $mailer, $phpmailer);
$to = str_nospace($to);
$from_email = str_nospace($from_email);
$mail_type = get_settings('mail_type');
// Определяем тип письма
$is_html = (strtolower($type) == 'html' || strtolower($type) == 'text/html');
// Добавляем подпись
if ($signature)
{
$signature = $is_html ? '<br><br>' . nl2br(get_settings('mail_signature')) : "\r\n\r\n" . get_settings('mail_signature');
}
else $signature = '';
// Составляем тело письма
$body = stripslashes($body) . $signature;
if ($is_html)
{
$body = str_replace(array("\t","\r","\n"),'',$body);
$body = str_replace(array(' ','> <'),array(' ','><'),$body);
}
// Получатели
$to_addresses = array_map('trim', explode(',', $to));
// ----------------------------------------------------
// Сохранение вложений (до отправки)
// ----------------------------------------------------
if ($attach && $saveattach)
{
$attach_dir = BASE_DIR . '/tmp/' . ATTACH_DIR . '/';
foreach ($attach as $file_path)
{
if ($file_path && file_exists($file_path))
{
$file_name = basename($file_path);
$file_name = str_replace(' ','',mb_strtolower(trim($file_name)));
if (file_exists($attach_dir . $file_name))
{
$file_name = rand(1000, 9999) . '_' . $file_name;
}
$file_path_new = $attach_dir . $file_name;
if (!@move_uploaded_file($file_path,$file_path_new))
{
copy($file_path,$file_path_new);
}
}
}
}
// =================================================================
// 1. SYMFONY MAILER: ТОЛЬКО ДЛЯ SMTP
// =================================================================
if ($mail_type === 'smtp') {
$message = new Email();
$message->getHeaders()->addTextHeader('X-Mailer', 'AVE.cms Symfony Mailer');
$message->subject($subject);
$message->from(new Address($from_email, $from_name));
$message->to(...$to_addresses);
if ($is_html) {
$message->html($body);
$message->text(strip_tags($body));
} else {
$message->text($body);
}
if ($attach) {
foreach ($attach as $attach_file) {
$file_path = trim($attach_file);
if ($file_path && file_exists($file_path)) {
$message->attachFromPath($file_path);
}
}
}
// --- Формирование DSN для SMTP (Ваш рабочий блок) ---
$settings = get_settings();
$host = stripslashes($settings['mail_host']);
$port = (int)$settings['mail_port'];
$user = stripslashes($settings['mail_smtp_login']);
$pass = stripslashes($settings['mail_smtp_pass']);
$encrypt_setting = strtolower(stripslashes($settings['mail_smtp_encrypt']));
$scheme = 'smtp';
$encryption = '';
$extra_params = '';
if (str_contains($encrypt_setting, 'insecure')) {
$extra_params = '&verify_peer=0';
$encryption = str_replace('_insecure', '', $encrypt_setting);
} elseif ($encrypt_setting === 'tls' || $encrypt_setting === 'ssl') {
$encryption = $encrypt_setting;
}
if ($encryption) {
$transport_dsn = sprintf('%s://%s:%s@%s:%d?encryption=%s%s',
$scheme,
urlencode($user),
urlencode($pass),
$host,
$port,
$encryption,
$extra_params
);
} else {
$transport_dsn = sprintf('smtp://%s:%s@%s:%d',
urlencode($user),
urlencode($pass),
$host,
$port ?: 25
);
}
// --- Отправка через Symfony Mailer ---
try {
$transport = Transport::fromDsn($transport_dsn);
$mailer = new Mailer($transport);
$mailer->send($message);
return true;
} catch (TransportExceptionInterface $e) {
reportLog('Не удалось отправить письма. Symfony Mailer Transport Error: ' . $e->getMessage());
return false;
} catch (\Exception $e) {
reportLog('Не удалось отправить письма. Symfony Mailer Fatal Error: ' . $e->getMessage());
return false;
}
} else {
// =================================================================
// 2. PHPMailer: ДЛЯ 'mail' И 'sendmail'
// =================================================================
$phpmailer = new PHPMailer(true);
try {
$phpmailer->CharSet = 'UTF-8';
$phpmailer->XMailer = 'AVE.cms PHPMailer';
// Настройки отправителя
$phpmailer->setFrom($from_email, $from_name);
// Настройки получателя
foreach ($to_addresses as $address) {
$phpmailer->addAddress($address);
}
// Тема и тело
$phpmailer->Subject = $subject;
if ($is_html) {
$phpmailer->isHTML(true);
$phpmailer->Body = $body;
$phpmailer->AltBody = strip_tags($body);
} else {
$phpmailer->isHTML(false);
$phpmailer->Body = $body;
}
// Вложения
if ($attach) {
foreach ($attach as $file_path) {
if (file_exists($file_path)) {
$phpmailer->addAttachment($file_path);
}
}
}
// Устанавливаем метод отправки
if ($mail_type === 'sendmail') {
// 1. Активируем режим Sendmail.
$phpmailer->isSendmail();
// 2. Устанавливаем путь к исполняемому файлу (обязательное требование)
$phpmailer->Sendmail = get_settings('mail_sendmail_path');
} else {
// Если mail или default, используем рабочий нативный mail()
$phpmailer->isMail();
}
$phpmailer->send();
return true;
} catch (PHPMailerException $e) {
reportLog("Не удалось отправить письма. PHPMailer Error ({$mail_type}): {$phpmailer->ErrorInfo}");
return false;
} catch (\Exception $e) {
reportLog("Не удалось отправить письма. PHPMailer Fatal Error: {$e->getMessage()}");
return false;
}
}
}
}
if ( ! function_exists('safe_mailto'))
{
function safe_mailto($email, $title = '', $attributes = '')
{
$title = (string) $title;
if ($title == "")
{
$title = $email;
}
for ($i = 0; $i < 16; $i++)
{
$x[] = substr('<a href="mailto:', $i, 1);
}
for ($i = 0; $i < strlen($email); $i++)
{
$x[] = "|".ord(substr($email, $i, 1));
}
$x[] = '"';
if ($attributes != '')
{
if (is_array($attributes))
{
foreach ($attributes as $key => $val)
{
$x[] = ' '.$key.'="';
for ($i = 0; $i < strlen($val); $i++)
{
$x[] = "|".ord(substr($val, $i, 1));
}
$x[] = '"';
}
}
else
{
for ($i = 0; $i < strlen($attributes); $i++)
{
$x[] = substr($attributes, $i, 1);
}
}
}
$x[] = '>';
$temp = array();
for ($i = 0; $i < strlen($title); $i++)
{
$ordinal = ord($title[$i]);
if ($ordinal < 128)
{
$x[] = "|".$ordinal;
}
else
{
if (count($temp) == 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$x[] = "|".$number;
$count = 1;
$temp = array();
}
}
}
$x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>';
$x = array_reverse($x);
ob_start();
?><script type="text/javascript">
//<![CDATA[
var l=new Array();
<?php
$i = 0;
foreach ($x as $val){ ?>l[<?php echo $i++; ?>]='<?php echo $val; ?>';<?php } ?>
for (var i = l.length-1; i >= 0; i=i-1){
if
(l[i].substring(0, 1) == '|') document.write("&#"+unescape(l[i].substring(1))+";");
else
document.write(unescape(l[i]));}
//]]>
</script><?php
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
}
?>