ArcaniSGK507

Untitled

Mar 27th, 2025
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.14 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. /**
  6.  * Last Hammer Framework 2.0
  7.  * PHP Version 8.3 (Required).
  8.  *
  9.  * @see https://github.com/arcanisgk/LH-Framework
  10.  *
  11.  * @author    Walter Nuñez (arcanisgk/founder) <[email protected]>
  12.  * @copyright 2017 - 2024
  13.  * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  14.  * @note      This program is distributed in the hope that it will be useful
  15.  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  16.  * or FITNESS FOR A PARTICULAR PURPOSE.
  17.  */
  18.  
  19. namespace Asset\Framework\Core;
  20.  
  21. use Asset\Framework\Template\MailComposer;
  22. use Asset\Framework\Trait\SingletonTrait;
  23. use PHPMailer\PHPMailer\Exception;
  24. use PHPMailer\PHPMailer\PHPMailer;
  25. use Random\RandomException;
  26.  
  27. /**
  28.  * Class that handles: Email Sender
  29.  *
  30.  * @package Asset\Framework\Core;
  31.  */
  32. class Mailer
  33. {
  34.  
  35.     use SingletonTrait;
  36.  
  37.     /**
  38.      * @var PHPMailer
  39.      */
  40.     private PHPMailer $mailer;
  41.  
  42.     /**
  43.      * @var string
  44.      */
  45.     private string $defaultFromAddress;
  46.  
  47.     /**
  48.      * @var string
  49.      */
  50.     private string $defaultFromName = 'LH Framework';
  51.  
  52.     /**
  53.      * @var string
  54.      */
  55.     private string $privateKeyPath;
  56.  
  57.     /**
  58.      * Mailer constructor.
  59.      */
  60.     public function __construct()
  61.     {
  62.         $this->defaultFromAddress = CONFIG->mail->mail1->getMailUser();
  63.         $this->mailer             = new PHPMailer(true);
  64.         $this->privateKeyPath     = Files::getInstance()->getAbsolutePath(
  65.             implode(DS, [PD, 'Asset', 'resource', 'keyring', 'private.pem'])
  66.         );
  67.         $this->configure();
  68.     }
  69.  
  70.  
  71.     /**
  72.      * @return void
  73.      * @throws Exception|RandomException
  74.      */
  75.     private function configure(): void
  76.     {
  77.         $this->mailer->isSMTP();
  78.         $this->mailer->SMTPDebug             = CONFIG->mail->mail1->getMailDebug();
  79.         $this->mailer->Host                  = CONFIG->mail->mail1->getMailHost();
  80.         $this->mailer->MessageID             = sprintf(
  81.             '<%s@%s>',
  82.             bin2hex(random_bytes(16)),
  83.             CONFIG->app->host->getDomain()
  84.         );
  85.         $this->mailer->SMTPAuth              = CONFIG->mail->mail1->getMailAuthentication();
  86.         $this->mailer->Username              = $this->defaultFromAddress;
  87.         $this->mailer->Password              = CONFIG->mail->mail1->getMailPassword();
  88.         $this->mailer->SMTPSecure            = PHPMailer::ENCRYPTION_STARTTLS;
  89.         $this->mailer->SMTPOptions           = [
  90.             'ssl' => [
  91.                 'crypto_method'     => STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT,
  92.                 'verify_peer'       => CONFIG->mail->mail1->getMailVerify(),
  93.                 'verify_peer_name'  => CONFIG->mail->mail1->getMailVerifyPeerName(),
  94.                 'allow_self_signed' => CONFIG->mail->mail1->getMailSelfSigned(),
  95.             ],
  96.         ];
  97.         $this->mailer->Port                  = CONFIG->mail->mail1->getMailPort();
  98.         $this->mailer->DKIM_domain           = CONFIG->app->host->getDomain();
  99.         $this->mailer->DKIM_private          = $this->privateKeyPath;
  100.         $this->mailer->DKIM_selector         = CONFIG->mail->mail1->getMailDkimSign();
  101.         $this->mailer->DKIM_passphrase       = CONFIG->mail->mail1->getMailDkimPassphrase();
  102.         $this->mailer->DKIM_identity         = $this->defaultFromAddress;
  103.         $this->mailer->DKIM_copyHeaderFields = CONFIG->mail->mail1->getMailDkimCopyHeaderFields();
  104.         $this->mailer->DKIM_extraHeaders     = ['List-Unsubscribe', 'List-Help'];
  105.         $this->mailer->CharSet               = 'UTF-8';
  106.         $this->mailer->Encoding              = PHPMailer::ENCODING_8BIT;
  107.         $this->mailer->XMailer               = 'LH Framework Mailer ('.
  108.             CONFIG->app->host->getProtocol().'://'.
  109.             CONFIG->app->host->getDomain().')';
  110.         $this->mailer->addCustomHeader('X-Mailer-Version', 'LH-2.0');
  111.         $this->mailer->addCustomHeader('List-Unsubscribe', 'List-Unsubscribe=One-Click');
  112.         $this->mailer->addCustomHeader('Precedence', 'bulk');
  113.         $this->mailer->addCustomHeader('X-Auto-Response-Suppress', 'OOF, AutoReply');
  114.         foreach (SecurityPolicies::getHumanitarianHeaders('mail') as $key => $value) {
  115.             $this->mailer->addCustomHeader($key, $value);
  116.         }
  117.     }
  118.  
  119.  
  120.     /**
  121.      * @param string $to
  122.      * @param string $subject
  123.      * @param array $emailData
  124.      * @param bool $isHtml
  125.      * @param array $attachments
  126.      * @param string $fromName
  127.      * @param string|null $plainTextBody
  128.      * @return bool
  129.      * @throws \Exception
  130.      */
  131.     public function send(
  132.         string $to,
  133.         string $subject,
  134.         array $emailData,
  135.         bool $isHtml = true,
  136.         array $attachments = [],
  137.         string $fromName = 'LH Framework',
  138.         string $plainTextBody = null
  139.     ): bool {
  140.         try {
  141.             $htmlBody = MailComposer::getInstance()->buildEmail($emailData);
  142.             $this->mailer->clearAddresses();
  143.             $this->mailer->clearAttachments();
  144.             $this->mailer->setFrom($this->defaultFromAddress, $fromName ?? $this->defaultFromName);
  145.             $this->mailer->addAddress($to);
  146.             $this->mailer->Subject = $subject;
  147.             $this->mailer->isHTML($isHtml);
  148.             $this->mailer->Body    = $htmlBody;
  149.             $this->mailer->AltBody = $plainTextBody ?? $this->convertToPlainText($htmlBody);
  150.             foreach ($attachments as $attachment) {
  151.                 if (is_array($attachment) && isset($attachment['path'], $attachment['name'])) {
  152.                     $this->mailer->addAttachment(
  153.                         $attachment['path'],
  154.                         $attachment['name'],
  155.                         PHPMailer::ENCODING_BASE64,
  156.                         $this->getMimeType($attachment['path'])
  157.                     );
  158.                 } elseif (is_string($attachment)) {
  159.                     $this->mailer->addAttachment($attachment);
  160.                 }
  161.             }
  162.  
  163.             return $this->mailer->send();
  164.         } catch (Exception $e) {
  165.             // Aquí podrías implementar tu sistema de logging
  166.             return false;
  167.         }
  168.     }
  169.  
  170.     /**
  171.      * @param string $html
  172.      * @return string
  173.      */
  174.     private function convertToPlainText(string $html): string
  175.     {
  176.         // Convert HTML to plain text
  177.         $html = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $html);
  178.         $html = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $html);
  179.  
  180.         $text = strip_tags($html);
  181.         $text = html_entity_decode($text);
  182.         $text = preg_replace('/\s+/', ' ', $text);
  183.         $text = preg_replace('/[\r\n]{2,}/', "\n\n", $text);
  184.  
  185.         return trim($text);
  186.     }
  187.  
  188.     /**
  189.      * @param string $filepath
  190.      * @return string
  191.      */
  192.     private function getMimeType(string $filepath): string
  193.     {
  194.         return mime_content_type($filepath) ?: 'application/octet-stream';
  195.     }
  196.  
  197.     /**
  198.      * @return PHPMailer
  199.      * @throws Exception
  200.      * @throws RandomException
  201.      */
  202.     public function __debugInfo()
  203.     {
  204.         $this->configure();
  205.  
  206.         return $this->mailer;
  207.     }
  208. }
Add Comment
Please, Sign In to add comment