- md5
- 85b1560841993d956db9046a4c5db9d0
- sha1
- e7cf6e187927584c2a190ae40f49401bb73035cc
- sha256
- 18c3c48c4536987f814637de373a683d0332a7c1307b6f7d88bbd6153fb94e2b
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
<?php
/**
* Joomla! Content Management System
*
* @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Mail;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Event\Mail\BeforeRenderingMailTemplateEvent;
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\LanguageFactoryInterface;
use Joomla\CMS\Layout\FileLayout;
use Joomla\CMS\Mail\Exception\MailDisabledException;
use Joomla\Component\Mails\Administrator\Helper\MailsHelper;
use Joomla\Database\DatabaseAwareTrait;
use Joomla\Database\DatabaseInterface;
use Joomla\Database\ParameterType;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\Registry\Registry;
use PHPMailer\PHPMailer\Exception as phpmailerException;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/**
* Email Templating Class
*
* @since 4.0.0
*/
class MailTemplate
{
use DatabaseAwareTrait;
/**
* Mailer object to send the actual mail.
*
* @var MailerInterface
* @since 4.0.0
*/
protected $mailer;
/**
* Identifier of the mail template.
*
* @var string
* @since 4.0.0
*/
protected $template_id;
/**
* Language of the mail template.
*
* @var string
*/
protected $language;
/**
*
* @var string[]
* @since 4.0.0
*/
protected $data = [];
/**
*
* @var string[]
* @since 5.1.0
*/
protected $plain_data = [];
/**
*
* @var string[]
* @since 5.1.3
*/
protected $unsafe_tags = [];
/**
*
* @var \stdClass[]
* @since 4.0.0
*/
protected $attachments = [];
/**
* List of recipients of the email
*
* @var \stdClass[]
* @since 4.0.0
*/
protected $recipients = [];
/**
* Reply To of the email
*
* @var \stdClass
* @since 4.0.0
*/
protected $replyto;
/**
* Layout mailtemplate options of the email
*
* @var string[]
* @since 5.2.0
*/
protected $layoutTemplateData = [];
/**
* The language factory
*
* @var LanguageFactoryInterface
* @since 6.2.0
*/
protected LanguageFactoryInterface $languageFactory;
/**
* Constructor for the mail templating class
*
* @param string $templateId Id of the mail template.
* @param string $language Language of the template to use.
* @param ?MailerInterface $mailer Mail object to send the mail with.
* @param ?LanguageFactoryInterface $languageFactory The language factory.
* @param ?DatabaseInterface $db The database.
*
* @since 4.0.0
*/
public function __construct(
$templateId,
$language,
?MailerInterface $mailer = null,
?LanguageFactoryInterface $languageFactory = null,
?DatabaseInterface $db = null
) {
$this->template_id = $templateId;
$this->language = $language;
if ($mailer) {
$this->mailer = $mailer;
} else {
@trigger_error('Mailer must be set, this will not be caught anymore in 8.0.', E_USER_DEPRECATED);
$this->mailer = Factory::getMailer();
}
$this->setDatabase($db ?? Factory::getContainer()->get(DatabaseInterface::class));
if ($db === null) {
@trigger_error('Database must be set, this will not be caught anymore in 8.0.', E_USER_DEPRECATED);
}
if ($languageFactory) {
$this->languageFactory = $languageFactory;
} else {
@trigger_error('Language factory must be set, this will not be caught anymore in 8.0.', E_USER_DEPRECATED);
$this->languageFactory = Factory::getContainer()->get(LanguageFactoryInterface::class);
}
}
/**
* Add an attachment to the mail
*
* @param string $name Filename of the attachment
* @param string $file Either a filepath or filecontent
*
* @return void
*
* @since 4.0.0
*/
public function addAttachment($name, $file)
{
$attachment = new \stdClass();
$attachment->name = $name;
$attachment->file = $file;
$this->attachments[] = $attachment;
}
/**
* Adds recipients for this mail
*
* @param string $mail Mail address of the recipient
* @param string $name Name of the recipient
* @param string $type How should the recipient receive the mail? ('to', 'cc', 'bcc')
*
* @return void
*
* @since 4.0.0
*/
public function addRecipient($mail, $name = null, $type = 'to')
{
$recipient = new \stdClass();
$recipient->mail = $mail;
$recipient->name = $name ?? $mail;
$recipient->type = $type;
$this->recipients[] = $recipient;
}
/**
* Set reply to for this mail
*
* @param string $mail Mail address to reply to
* @param string $name Name
*
* @return void
*
* @since 4.0.0
*/
public function setReplyTo($mail, $name = '')
{
$reply = new \stdClass();
$reply->mail = $mail;
$reply->name = $name;
$this->replyto = $reply;
}
/**
* Add data to the html layout template
*
* @param array $data Associative array of strings for the layout
*
* @return void
*
* @since 5.2.0
*/
public function addLayoutTemplateData($data)
{
$this->layoutTemplateData = array_merge($this->layoutTemplateData, $data);
}
/**
* Add data to replace in the template
*
* @param array $data Associative array of strings to replace
* @param bool $plain Only use the data for plain-text emails.
*
* @return void
*
* @since 4.0.0
*/
public function addTemplateData($data, $plain = false)
{
if (!$plain) {
$this->data = array_merge($this->data, $data);
} else {
$this->plain_data = array_merge($this->plain_data, $data);
}
}
/**
* Get the template data.
*
* @param bool $plain Data used for plain-text emails.
*
* @return array
*
* @since 6.1.0
*/
public function getTemplateData($plain = false): array
{
return !$plain ? $this->data : $this->plain_data;
}
/**
* Mark tags as unsafe to ensure escaping in HTML mails
*
* @param array $tags Tag names
*
* @return void
*
* @since 5.1.3
*/
public function addUnsafeTags($tags)
{
$this->unsafe_tags = array_merge($this->unsafe_tags, array_map('strtoupper', $tags));
}
/**
* Render and send the mail
*
* @return boolean True on success
*
* @since 4.0.0
* @throws \Exception
* @throws MailDisabledException
* @throws phpmailerException
*/
public function send()
{
$config = ComponentHelper::getParams('com_mails');
$mail = $this->loadTemplate($this->template_id, $this->language);
// If the Mail Template was not found in the db, we cannot send an email.
if ($mail === null) {
return false;
}
/** @var Registry $params */
$params = $mail->params;
$app = Factory::getApplication();
$replyTo = $app->get('replyto', '');
$replyToName = $app->get('replytoname', '');
$language = $app->getLanguage();
if ($this->language && $this->language !== $language->getTag()) {
$language = $this->languageFactory->createLanguage($this->language, $app->get('debug_lang'));
MailsHelper::loadTranslationFiles($mail->extension, $language);
}
if ((int) $config->get('alternative_mailconfig', 0) === 1 && (int) $params->get('alternative_mailconfig', 0) === 1) {
if ($this->mailer instanceof TransportConfigurableMailerInterface && $params->get('mailer') === 'smtp') {
$smtpauth = ($params->get('smtpauth', $app->get('smtpauth')) == 0) ? null : 1;
$smtpuser = $params->get('smtpuser', $app->get('smtpuser'));
$smtppass = $params->get('smtppass', $app->get('smtppass'));
$smtphost = $params->get('smtphost', $app->get('smtphost'));
$smtpsecure = $params->get('smtpsecure', $app->get('smtpsecure'));
$smtpport = $params->get('smtpport', $app->get('smtpport'));
$this->mailer->useSmtp($smtpauth, $smtphost, $smtpuser, $smtppass, $smtpsecure, $smtpport);
}
if ($this->mailer instanceof TransportConfigurableMailerInterface && $params->get('mailer') === 'sendmail') {
$this->mailer->useSendmail('joomla');
}
$mailfrom = $params->get('mailfrom', $app->get('mailfrom'));
$fromname = $params->get('fromname', $app->get('fromname'));
if (MailHelper::isEmailAddress($mailfrom)) {
$this->mailer->setSender(MailHelper::cleanLine($mailfrom), MailHelper::cleanLine($fromname));
}
$replyTo = $params->get('replyto', $replyTo);
$replyToName = $params->get('replytoname', $replyToName);
}
$useLayout = $config->get('disable_htmllayout', '1');
if ((int) $config->get('alternative_mailconfig', 0) === 1) {
$useLayout = $params->get('disable_htmllayout', $useLayout);
}
$app->getDispatcher()->dispatch('onMailBeforeRendering', new BeforeRenderingMailTemplateEvent(
'onMailBeforeRendering',
['templateId' => $this->template_id, 'subject' => $this]
));
$subject = $this->replaceTags($language->_($mail->subject), $this->data);
$this->mailer->setSubject($subject);
$mailStyle = $config->get('mail_style', 'plaintext');
// Use the plain-text replacement data, if specified.
$plainData = $this->plain_data ?: $this->data;
$plainBody = $this->replaceTags($language->_($mail->body), $plainData);
$htmlBody = $useLayout ? $language->_($mail->htmlbody) : $this->replaceTags($language->_($mail->htmlbody), $this->data, true);
if ($mailStyle === 'plaintext' || $mailStyle === 'both') {
// If the Plain template is empty try to convert the HTML template to a Plain text
if (!$plainBody) {
$plainBody = strip_tags(str_replace(['<br>', '<br />', '<br/>'], "\n", $this->replaceTags($htmlBody, $plainData)));
}
$this->mailer->setBody($plainBody);
// Set alt body, use $mailer->Body directly because it was filtered by $mailer->setBody()
if ($mailStyle === 'both') {
$this->mailer->AltBody = $this->mailer->Body;
}
}
if ($mailStyle === 'html' || $mailStyle === 'both') {
if ($this->mailer instanceof FormatConfigurableMailerInterface) {
$this->mailer->isHtml(true);
}
// If HTML body is empty try to convert the Plain template to html
if (!$htmlBody) {
$htmlBody = nl2br($this->replaceTags($language->_($mail->body), $plainData, true), false);
}
if ($useLayout) {
// Add additional data to the layout template
$this->addLayoutTemplateData([
'siteName' => $app->get('sitename'),
'lang' => substr($this->language, 0, 2),
'mail' => $mail,
]);
$layout = $config->get('mail_htmllayout', 'mailtemplate');
$logo = (string) $config->get('mail_logofile', '');
// Check alternative mailconfig
if ((int) $config->get('alternative_mailconfig', 0) === 1) {
$layout = $params->get('htmllayout', $layout);
$logo = $params->get('disable_logofile', 1) ? $logo : '' ;
}
// Add the logo to the mail as inline attachment
if ($logo) {
$logo = Path::check(JPATH_ROOT . '/' . HTMLHelper::_('cleanImageURL', $logo)->url);
if (is_file(urldecode($logo))) {
# Attach the logo as inline attachment
$this->mailer->addAttachment($logo, 'site-logo', 'base64', mime_content_type($logo), 'inline');
// We need only the cid for attached logo file
$this->addLayoutTemplateData(['logo' => 'site-logo']);
}
}
// Check if layout is a template override
$layoutParts = explode(':', $layout);
if (\count($layoutParts) === 2) {
$layout = $layoutParts[1];
}
// Wrap the default Joomla mail template around the HTML body
$layoutFile = new FileLayout('joomla.mail.' . $layout, null, ['client' => 'site']);
// Set the template layout path if needed
if (\count($layoutParts) === 2) {
$layoutFile->addIncludePaths([
JPATH_SITE . '/templates/' . $layoutParts[0] . '/html/layouts',
JPATH_SITE . '/templates/' . $layoutParts[0] . '/html/layouts/com_mails',
]);
}
$htmlBody = $layoutFile->render(['mail' => $htmlBody, 'extra' => $this->layoutTemplateData]);
$htmlBody = $this->replaceTags($language->_($htmlBody), $this->data, true);
}
$htmlBody = MailHelper::convertRelativeToAbsoluteUrls($htmlBody);
$this->mailer->setBody($htmlBody);
}
if ($config->get('copy_mails') && $params->get('copyto')) {
$this->mailer->addBcc($params->get('copyto'));
}
foreach ($this->recipients as $recipient) {
switch ($recipient->type) {
case 'cc':
$this->mailer->addCc($recipient->mail, $recipient->name);
break;
case 'bcc':
$this->mailer->addBcc($recipient->mail, $recipient->name);
break;
case 'to':
default:
$this->mailer->addRecipient($recipient->mail, $recipient->name);
}
}
if ($this->replyto) {
$this->mailer->addReplyTo($this->replyto->mail, $this->replyto->name);
} elseif ($replyTo) {
$this->mailer->addReplyTo($replyTo, $replyToName);
}
if (trim($config->get('attachment_folder', ''))) {
$folderPath = rtrim(Path::check(JPATH_ROOT . '/' . $config->get('attachment_folder')), \DIRECTORY_SEPARATOR);
if ($folderPath && $folderPath !== Path::clean(JPATH_ROOT) && is_dir($folderPath)) {
foreach ((array) json_decode($mail->attachments) as $attachment) {
$filePath = Path::check($folderPath . '/' . $attachment->file);
if (is_file($filePath)) {
$this->mailer->addAttachment($filePath, $this->getAttachmentName($filePath, $attachment->name));
}
}
}
}
$tmpAttachmentFiles = [];
foreach ($this->attachments as $attachment) {
if (is_file($attachment->file)) {
$this->mailer->addAttachment($attachment->file, $this->getAttachmentName($attachment->file, $attachment->name));
} elseif ($this->mailer instanceof Mail) {
$this->mailer->addStringAttachment($attachment->file, $attachment->name);
} else {
// If the mailer does not support string attachments, create a temporary file and attach it
$tmpFile = tempnam(JPATH_CACHE, 'mailattachment_');
if (file_put_contents($tmpFile, $attachment->file) !== false) {
$this->mailer->addAttachment($tmpFile, $attachment->name);
$tmpAttachmentFiles[] = $tmpFile;
}
}
}
$success = $this->mailer->send();
foreach ($tmpAttachmentFiles as $tmpFile) {
@unlink($tmpFile);
}
return $success;
}
/**
* Replace tags with their values recursively
*
* @param string $text The template to process
* @param array $tags An associative array to replace in the template
* @param bool $isHtml Is the text an HTML text and requires escaping
*
* @return string Rendered mail template
*
* @since 4.0.0
*/
protected function replaceTags($text, $tags, $isHtml = false)
{
foreach ($tags as $key => $value) {
// If the value is NULL, replace with an empty string. NULL itself throws notices
if (\is_null($value)) {
$value = '';
}
if (\is_array($value)) {
$matches = [];
$pregKey = preg_quote(strtoupper($key), '/');
if (preg_match_all('/{' . $pregKey . '}(.*?){\/' . $pregKey . '}/s', $text, $matches)) {
foreach ($matches[0] as $i => $match) {
$replacement = '';
foreach ($value as $name => $subvalue) {
if (\is_array($subvalue) && $name == $matches[1][$i]) {
$subvalue = implode("\n", $subvalue);
// Escape if necessary
if ($isHtml && \in_array(strtoupper($key), $this->unsafe_tags, true)) {
$subvalue = htmlspecialchars($subvalue, ENT_QUOTES, 'UTF-8');
}
$replacement .= implode("\n", $subvalue);
} elseif (\is_array($subvalue)) {
$replacement .= $this->replaceTags($matches[1][$i], $subvalue, $isHtml);
} elseif (\is_string($subvalue) && $name == $matches[1][$i]) {
// Escape if necessary
if ($isHtml && \in_array(strtoupper($key), $this->unsafe_tags, true)) {
$subvalue = htmlspecialchars($subvalue, ENT_QUOTES, 'UTF-8');
}
$replacement .= $subvalue;
}
}
$text = str_ireplace($match, $replacement, $text);
}
}
} else {
// Escape if necessary
if ($isHtml && \in_array(strtoupper($key), $this->unsafe_tags, true)) {
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
$text = str_ireplace('{' . strtoupper($key) . '}', $value, $text);
}
}
return $text;
}
/**
* Get a specific mail template for the given key and language.
*
* @param string $key Template identifier
* @param string $language Language code of the template
*
* @return \stdClass|null An object with the data of the mail, or null if the template not found in the db.
*
* @since 6.2.0
*/
protected function loadTemplate(string $key, string $language): ?\stdClass
{
$db = $this->getDatabase();
$query = $db->createQuery();
$query->select('*')
->from($db->quoteName('#__mail_templates'))
->where($db->quoteName('template_id') . ' = :key')
->whereIn($db->quoteName('language'), ['', $language], ParameterType::STRING)
->order($db->quoteName('language') . ' DESC')
->bind(':key', $key);
$db->setQuery($query);
$mail = $db->loadObject();
if ($mail) {
$mail->params = new Registry($mail->params);
}
return $mail;
}
/**
* Get a specific mail template
*
* @param string $key Template identifier
* @param string $language Language code of the template
*
* @return object|null An object with the data of the mail, or null if the template not found in the db.
*
* @since 4.0.0
*
* @deprecated 6.2.0 this will be removed without replacement in 8.0
* Use $app->bootComponent('com_mails')->getMVCFactory()->createModel('Template', 'Administrator')->getItem(); instead
*/
public static function getTemplate($key, $language)
{
return (new self($key, $language))->loadTemplate($key, $language);
}
/**
* Insert a new mail template into the system
*
* @param string $key Mail template key
* @param string $subject A default subject (normally a translatable string)
* @param string $body A default body (normally a translatable string)
* @param array $tags Associative array of tags to replace
* @param string $htmlbody A default htmlbody (normally a translatable string)
*
* @return boolean True on success, false on failure
*
* @since 4.0.0
*
* @deprecated 6.2.0 this will be removed without replacement in 8.0
* Use $app->bootComponent('com_mails')->getMVCFactory()->createModel('Template', 'Administrator')->save(); instead
*/
public static function createTemplate($key, $subject, $body, $tags, $htmlbody = '')
{
return Factory::getApplication()->bootComponent('com_mails')
->getMVCFactory()->createModel('Template', 'Administrator')->save([
'template_id' => $key,
'language' => '',
'subject' => $subject,
'body' => $body,
'htmlbody' => $htmlbody,
'params' => json_encode(['tags' => (array) $tags]),
'extension' => explode('.', $key, 2)[0] ?? '',
'attachments' => '',
]);
}
/**
* Update an existing mail template
*
* @param string $key Mail template key
* @param string $subject A default subject (normally a translatable string)
* @param string $body A default body (normally a translatable string)
* @param array $tags Associative array of tags to replace
* @param string $htmlbody A default htmlbody (normally a translatable string)
*
* @return boolean True on success, false on failure
*
* @since 4.0.0
*
* @deprecated 6.2.0 this will be removed without replacement in 8.0
* Use $app->bootComponent('com_mails')->getMVCFactory()->createModel('Template', 'Administrator')->save(); instead
*/
public static function updateTemplate($key, $subject, $body, $tags, $htmlbody = '')
{
return Factory::getApplication()->bootComponent('com_mails')
->getMVCFactory()->createModel('Template', 'Administrator')->save([
'template_id' => $key,
'language' => '',
'subject' => $subject,
'body' => $body,
'htmlbody' => $htmlbody,
'params' => json_encode(['tags' => (array) $tags]),
]);
}
/**
* Method to delete a mail template
*
* @param string $key The key of the mail template
*
* @return boolean True on success, false on failure
*
* @since 4.0.0
*
* @deprecated 6.2.0 this will be removed without replacement in 8.0
* Use $app->bootComponent('com_mails')->getMVCFactory()->createModel('Template', 'Administrator')->delete(); instead
*/
public static function deleteTemplate($key)
{
return Factory::getApplication()->bootComponent('com_mails')
->getMVCFactory()->createModel('Template', 'Administrator')->delete($key);
}
/**
* Check and if necessary fix the file name of an attachment so that the attached file
* has the same extension as the source file, and not a different file extension
*
* @param string $file Path to the file to be attached
* @param string $name The file name to be used for the attachment
*
* @return string The corrected file name for the attachment
*
* @since 4.0.0
*/
protected function getAttachmentName(string $file, string $name): string
{
// If no name is given, do not process it further
if (!trim($name)) {
return '';
}
// Replace any placeholders.
$name = $this->replaceTags($name, $this->data);
// Get the file extension.
$ext = File::getExt($file);
// Strip off extension from $name and append extension of $file, if any
return File::stripExt($name) . ($ext ? '.' . $ext : '');
}
}
The same content is in 4 releases, Joomla 6.2.0-rc1 to 6.2.1-rc1. See them all, or every version of this file.