-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathMailTemplate.php
More file actions
673 lines (582 loc) · 22.4 KB
/
Copy pathMailTemplate.php
File metadata and controls
673 lines (582 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
<?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\Text;
use Joomla\CMS\Layout\FileLayout;
use Joomla\CMS\Mail\Exception\MailDisabledException;
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
{
/**
* 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 = [];
/**
* Constructor for the mail templating class
*
* @param string $templateId Id of the mail template.
* @param string $language Language of the template to use.
* @param ?Mail $mailer Mail object to send the mail with.
*
* @since 4.0.0
*/
public function __construct($templateId, $language, ?MailerInterface $mailer = 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();
}
}
/**
* 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 = static::getTemplate($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', '');
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(Text::_($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(Text::_($mail->body), $plainData);
$htmlBody = $useLayout ? Text::_($mail->htmlbody) : $this->replaceTags(Text::_($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(Text::_($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(Text::_($htmlBody), $this->data);
}
$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
*
* @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
*/
public static function getTemplate($key, $language)
{
$db = Factory::getDbo();
$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;
}
/**
* 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
*/
public static function createTemplate($key, $subject, $body, $tags, $htmlbody = '')
{
$db = Factory::getDbo();
$template = new \stdClass();
$template->template_id = $key;
$template->language = '';
$template->subject = $subject;
$template->body = $body;
$template->htmlbody = $htmlbody;
$template->extension = explode('.', $key, 2)[0] ?? '';
$template->attachments = '';
$params = new \stdClass();
$params->tags = (array) $tags;
$template->params = json_encode($params);
return $db->insertObject('#__mail_templates', $template);
}
/**
* 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
*/
public static function updateTemplate($key, $subject, $body, $tags, $htmlbody = '')
{
$db = Factory::getDbo();
$template = new \stdClass();
$template->template_id = $key;
$template->language = '';
$template->subject = $subject;
$template->body = $body;
$template->htmlbody = $htmlbody;
$params = new \stdClass();
$params->tags = (array) $tags;
$template->params = json_encode($params);
return $db->updateObject('#__mail_templates', $template, ['template_id', 'language']);
}
/**
* 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
*/
public static function deleteTemplate($key)
{
$db = Factory::getDbo();
$query = $db->createQuery();
$query->delete($db->quoteName('#__mail_templates'))
->where($db->quoteName('template_id') . ' = :key')
->bind(':key', $key);
$db->setQuery($query);
return $db->execute();
}
/**
* 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 : '');
}
}