Merge pull request #15042 from civicrm/5.17
[civicrm-core.git] / CRM / Core / BAO / MessageTemplate.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34require_once 'Mail/mime.php';
b5c2afd0
EM
35
36/**
8eedd10a 37 * Class CRM_Core_BAO_MessageTemplate.
b5c2afd0 38 */
c6327d7d 39class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
6a488035
TO
40
41 /**
fe482240 42 * Fetch object based on array of properties.
6a488035 43 *
6a0b768e
TO
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
46 * @param array $defaults
47 * (reference ) an assoc array to hold the flattened values.
6a488035 48 *
16b10e64 49 * @return CRM_Core_BAO_MessageTemplate
6a488035 50 */
00be9182 51 public static function retrieve(&$params, &$defaults) {
c6327d7d 52 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035
TO
53 $messageTemplates->copyValues($params);
54 if ($messageTemplates->find(TRUE)) {
55 CRM_Core_DAO::storeValues($messageTemplates, $defaults);
56 return $messageTemplates;
57 }
58 return NULL;
59 }
60
61 /**
fe482240 62 * Update the is_active flag in the db.
6a488035 63 *
6a0b768e
TO
64 * @param int $id
65 * Id of the database record.
66 * @param bool $is_active
67 * Value we want to set the is_active field.
6a488035 68 *
8a4fede3 69 * @return bool
70 * true if we found and updated the object, else false
6a488035 71 */
00be9182 72 public static function setIsActive($id, $is_active) {
c6327d7d 73 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
6a488035
TO
74 }
75
76 /**
fe482240 77 * Add the Message Templates.
6a488035 78 *
6a0b768e
TO
79 * @param array $params
80 * Reference array contains the values submitted by the form.
6a488035 81 *
6a488035
TO
82 *
83 * @return object
84 */
00be9182 85 public static function add(&$params) {
781ed314
SL
86 // System Workflow Templates have a specific wodkflow_id in them but normal user end message templates don't
87 // If we have an id check to see if we are update, and need to check if original is a system workflow or not.
88 $systemWorkflowPermissionDeniedMessage = 'Editing or creating system workflow messages requires edit system workflow message templates permission or the edit message templates permission';
89 $userWorkflowPermissionDeniedMessage = 'Editing or creating user driven workflow messages requires edit user-driven message templates or the edit message templates permission';
90 if (!empty($params['check_permissions'])) {
91 if (!CRM_Core_Permission::check('edit message templates')) {
92 if (!empty($params['id'])) {
93 $details = civicrm_api3('MessageTemplate', 'getSingle', ['id' => $params['id']]);
94 if (!empty($details['workflow_id'])) {
95 if (!CRM_Core_Permission::check('edit system workflow message templates')) {
96 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
97 }
98 }
99 elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
100 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
101 }
102 }
103 else {
104 if (!empty($params['workflow_id']) && !CRM_Core_Permission::check('edit system workflow message templates')) {
105 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
106 }
107 elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
108 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
109 }
110 }
111 }
112 }
3c8059c8
KM
113 $hook = empty($params['id']) ? 'create' : 'edit';
114 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
c39c0aa1 115
90a73810 116 if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
117 $fileParams = $params['file_id'];
118 unset($params['file_id']);
119 }
120
c6327d7d 121 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035 122 $messageTemplates->copyValues($params);
6a488035 123 $messageTemplates->save();
c39c0aa1 124
90a73810 125 if (!empty($fileParams)) {
126 $params['file_id'] = $fileParams;
04a76231 127 CRM_Core_BAO_File::filePostProcess(
90a73810 128 $params['file_id']['location'],
129 NULL,
130 'civicrm_msg_template',
131 $messageTemplates->id,
132 NULL,
133 TRUE,
134 $params['file_id'],
135 'file_id',
136 $params['file_id']['type']
137 );
90a73810 138 }
139
c9606a53 140 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
6a488035
TO
141 return $messageTemplates;
142 }
143
144 /**
fe482240 145 * Delete the Message Templates.
6a488035 146 *
100fef9d 147 * @param int $messageTemplatesID
6a488035 148 */
00be9182 149 public static function del($messageTemplatesID) {
6a488035
TO
150 // make sure messageTemplatesID is an integer
151 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
152 CRM_Core_Error::fatal(ts('Invalid Message template'));
153 }
154
155 // Set mailing msg template col to NULL
156 $query = "UPDATE civicrm_mailing
157 SET msg_template_id = NULL
158 WHERE msg_template_id = %1";
5f351616 159
be2fb01f 160 $params = [1 => [$messageTemplatesID, 'Integer']];
6a488035
TO
161 CRM_Core_DAO::executeQuery($query, $params);
162
c6327d7d 163 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035
TO
164 $messageTemplates->id = $messageTemplatesID;
165 $messageTemplates->delete();
166 CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
167 }
168
169 /**
fe482240 170 * Get the Message Templates.
6a488035 171 *
6a488035 172 *
dd244018
EM
173 * @param bool $all
174 *
ad37ac8e 175 * @param bool $isSMS
176 *
6a488035
TO
177 * @return object
178 */
00be9182 179 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
be2fb01f 180 $msgTpls = [];
6a488035 181
c6327d7d 182 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035 183 $messageTemplates->is_active = 1;
1e035d58 184 $messageTemplates->is_sms = $isSMS;
6a488035
TO
185
186 if (!$all) {
187 $messageTemplates->workflow_id = 'NULL';
188 }
189 $messageTemplates->find();
190 while ($messageTemplates->fetch()) {
191 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
192 }
193 asort($msgTpls);
194 return $msgTpls;
195 }
196
b5c2afd0 197 /**
100fef9d 198 * @param int $contactId
b5c2afd0 199 * @param $email
100fef9d 200 * @param int $messageTemplateID
b5c2afd0
EM
201 * @param $from
202 *
e60f24eb 203 * @return bool|NULL
b5c2afd0 204 */
00be9182 205 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
6a488035 206
c6327d7d 207 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035
TO
208 $messageTemplates->id = $messageTemplateID;
209
353ffa53
TO
210 $domain = CRM_Core_BAO_Domain::getDomain();
211 $result = NULL;
be2fb01f 212 $hookTokens = [];
6a488035
TO
213
214 if ($messageTemplates->find(TRUE)) {
353ffa53
TO
215 $body_text = $messageTemplates->msg_text;
216 $body_html = $messageTemplates->msg_html;
6a488035
TO
217 $body_subject = $messageTemplates->msg_subject;
218 if (!$body_text) {
219 $body_text = CRM_Utils_String::htmlToText($body_html);
220 }
221
be2fb01f 222 $params = [['contact_id', '=', $contactId, 0, 0]];
6a488035
TO
223 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
224
225 //CRM-4524
226 $contact = reset($contact);
227
228 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
229 return NULL;
230 }
231
232 //CRM-5734
233
234 // get tokens to be replaced
235 $tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
353ffa53
TO
236 CRM_Utils_Token::getTokens($body_html),
237 CRM_Utils_Token::getTokens($body_subject));
6a488035
TO
238
239 // get replacement text for these tokens
be2fb01f 240 $returnProperties = ["preferred_mail_format" => 1];
c39c0aa1 241 if (isset($tokens['contact'])) {
6a488035 242 foreach ($tokens['contact'] as $key => $value) {
c39c0aa1 243 $returnProperties[$value] = 1;
6a488035
TO
244 }
245 }
be2fb01f 246 list($details) = CRM_Utils_Token::getTokenDetails([$contactId],
353ffa53
TO
247 $returnProperties,
248 NULL, NULL, FALSE,
249 $tokens,
250 'CRM_Core_BAO_MessageTemplate');
481a74f4 251 $contact = reset($details);
6a488035
TO
252
253 // call token hook
be2fb01f 254 $hookTokens = [];
6a488035
TO
255 CRM_Utils_Hook::tokens($hookTokens);
256 $categories = array_keys($hookTokens);
257
c39c0aa1 258 // do replacements in text and html body
be2fb01f 259 $type = ['html', 'text'];
6a488035
TO
260 foreach ($type as $key => $value) {
261 $bodyType = "body_{$value}";
262 if ($$bodyType) {
263 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
4eeb9a5b 264 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens, TRUE);
ab8a593e 265 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
4eeb9a5b 266 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, TRUE);
d3e86119 267 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
6a488035
TO
268 }
269 }
270 $html = $body_html;
271 $text = $body_text;
272
4ee279f4 273 $smarty = CRM_Core_Smarty::singleton();
be2fb01f 274 foreach ([
518fa0ee
SL
275 'text',
276 'html',
277 ] as $elem) {
4ee279f4 278 $$elem = $smarty->fetch("string:{$$elem}");
279 }
280
6a488035 281 // do replacements in message subject
ab8a593e 282 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
4eeb9a5b
TO
283 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
284 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
285 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
6a488035 286
4ee279f4 287 $messageSubject = $smarty->fetch("string:{$messageSubject}");
288
6a488035 289 // set up the parameters for CRM_Utils_Mail::send
be2fb01f 290 $mailParams = [
6a488035
TO
291 'groupName' => 'Scheduled Reminder Sender',
292 'from' => $from,
293 'toName' => $contact['display_name'],
294 'toEmail' => $email,
295 'subject' => $messageSubject,
be2fb01f 296 ];
6a488035
TO
297 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
298 $contact['preferred_mail_format'] == 'Both'
299 ) {
300 // render the &amp; entities in text mode, so that the links work
301 $mailParams['text'] = str_replace('&amp;', '&', $text);
302 }
303 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
304 $contact['preferred_mail_format'] == 'Both'
353ffa53
TO
305 )
306 ) {
6a488035
TO
307 $mailParams['html'] = $html;
308 }
309
310 $result = CRM_Utils_Mail::send($mailParams);
311 }
312
6a488035
TO
313 return $result;
314 }
315
316 /**
8eedd10a 317 * Revert a message template to its default subject+text+HTML state.
6a488035 318 *
608e6658 319 * @param int $id id of the template
6a488035 320 */
00be9182 321 public static function revert($id) {
608e6658 322 $diverted = new CRM_Core_BAO_MessageTemplate();
6a488035
TO
323 $diverted->id = (int) $id;
324 $diverted->find(1);
325
326 if ($diverted->N != 1) {
be2fb01f 327 CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', [1 => $id]));
6a488035
TO
328 }
329
608e6658 330 $orig = new CRM_Core_BAO_MessageTemplate();
6a488035
TO
331 $orig->workflow_id = $diverted->workflow_id;
332 $orig->is_reserved = 1;
333 $orig->find(1);
334
335 if ($orig->N != 1) {
be2fb01f 336 CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
6a488035
TO
337 }
338
339 $diverted->msg_subject = $orig->msg_subject;
340 $diverted->msg_text = $orig->msg_text;
341 $diverted->msg_html = $orig->msg_html;
342 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
343 $diverted->save();
344 }
345
346 /**
fe482240 347 * Send an email from the specified template based on an array of params.
6a488035 348 *
6a0b768e
TO
349 * @param array $params
350 * A string-keyed array of function params, see function body for details.
6a488035 351 *
a6c01b45 352 * @return array
16b10e64 353 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
6a488035 354 */
00be9182 355 public static function sendTemplate($params) {
be2fb01f 356 $defaults = [
6a488035
TO
357 // option group name of the template
358 'groupName' => NULL,
359 // option value name of the template
360 'valueName' => NULL,
361 // ID of the template
362 'messageTemplateID' => NULL,
363 // contact id if contact tokens are to be replaced
364 'contactId' => NULL,
365 // additional template params (other than the ones already set in the template singleton)
be2fb01f 366 'tplParams' => [],
6a488035
TO
367 // the From: header
368 'from' => NULL,
369 // the recipient’s name
370 'toName' => NULL,
371 // the recipient’s email - mail is sent only if set
372 'toEmail' => NULL,
373 // the Cc: header
374 'cc' => NULL,
375 // the Bcc: header
376 'bcc' => NULL,
377 // the Reply-To: header
378 'replyTo' => NULL,
379 // email attachments
380 'attachments' => NULL,
381 // whether this is a test email (and hence should include the test banner)
382 'isTest' => FALSE,
383 // filename of optional PDF version to add as attachment (do not include path)
384 'PDFFilename' => NULL,
be2fb01f 385 ];
6a488035
TO
386 $params = array_merge($defaults, $params);
387
4335f229
JG
388 // Core#644 - handle contact ID passed as "From".
389 if (isset($params['from'])) {
390 $params['from'] = CRM_Utils_Mail::formatFromAddress($params['from']);
391 }
392
ededcdab
BS
393 CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
394
6a488035
TO
395 if ((!$params['groupName'] ||
396 !$params['valueName']
397 ) &&
398 !$params['messageTemplateID']
399 ) {
400 CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing."));
401 }
402
403 if ($params['messageTemplateID']) {
404 // fetch the three elements from the db based on id
405 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
406 FROM civicrm_msg_template mt
407 WHERE mt.id = %1 AND mt.is_default = 1';
be2fb01f 408 $sqlParams = [1 => [$params['messageTemplateID'], 'String']];
6a488035
TO
409 }
410 else {
411 // fetch the three elements from the db based on option_group and option_value names
412 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
413 FROM civicrm_msg_template mt
414 JOIN civicrm_option_value ov ON workflow_id = ov.id
415 JOIN civicrm_option_group og ON ov.option_group_id = og.id
416 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
be2fb01f 417 $sqlParams = [1 => [$params['groupName'], 'String'], 2 => [$params['valueName'], 'String']];
6a488035
TO
418 }
419 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
420 $dao->fetch();
421
422 if (!$dao->N) {
423 if ($params['messageTemplateID']) {
be2fb01f 424 CRM_Core_Error::fatal(ts('No such message template: id=%1.', [1 => $params['messageTemplateID']]));
6a488035
TO
425 }
426 else {
be2fb01f 427 CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', [
518fa0ee
SL
428 1 => $params['groupName'],
429 2 => $params['valueName'],
430 ]));
6a488035
TO
431 }
432 }
433
be2fb01f 434 $mailContent = [
14bf6806
AF
435 'subject' => $dao->subject,
436 'text' => $dao->text,
437 'html' => $dao->html,
438 'format' => $dao->format,
87098536
BS
439 'groupName' => $params['groupName'],
440 'valueName' => $params['valueName'],
441 'messageTemplateID' => $params['messageTemplateID'],
be2fb01f 442 ];
6a488035 443
14bf6806
AF
444 CRM_Utils_Hook::alterMailContent($mailContent);
445
6a488035
TO
446 // add the test banner (if requested)
447 if ($params['isTest']) {
448 $query = "SELECT msg_subject subject, msg_text text, msg_html html
449 FROM civicrm_msg_template mt
450 JOIN civicrm_option_value ov ON workflow_id = ov.id
451 JOIN civicrm_option_group og ON ov.option_group_id = og.id
452 WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
453 $testDao = CRM_Core_DAO::executeQuery($query);
454 $testDao->fetch();
455
14bf6806
AF
456 $mailContent['subject'] = $testDao->subject . $mailContent['subject'];
457 $mailContent['text'] = $testDao->text . $mailContent['text'];
458 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']);
6a488035
TO
459 }
460
461 // replace tokens in the three elements (in subject as if it was the text body)
353ffa53 462 $domain = CRM_Core_BAO_Domain::getDomain();
be2fb01f 463 $hookTokens = [];
608e6658 464 $mailing = new CRM_Mailing_BAO_Mailing();
94993cf9 465 $mailing->subject = $mailContent['subject'];
14bf6806
AF
466 $mailing->body_text = $mailContent['text'];
467 $mailing->body_html = $mailContent['html'];
353ffa53 468 $tokens = $mailing->getTokens();
6a488035
TO
469 CRM_Utils_Hook::tokens($hookTokens);
470 $categories = array_keys($hookTokens);
471
472 $contactID = CRM_Utils_Array::value('contactId', $params);
473
474 if ($contactID) {
be2fb01f
CW
475 $contactParams = ['contact_id' => $contactID];
476 $returnProperties = [];
6a488035 477
a7c64830 478 if (isset($tokens['subject']['contact'])) {
479 foreach ($tokens['subject']['contact'] as $name) {
480 $returnProperties[$name] = 1;
481 }
482 }
483
6a488035
TO
484 if (isset($tokens['text']['contact'])) {
485 foreach ($tokens['text']['contact'] as $name) {
486 $returnProperties[$name] = 1;
487 }
488 }
489
490 if (isset($tokens['html']['contact'])) {
491 foreach ($tokens['html']['contact'] as $name) {
492 $returnProperties[$name] = 1;
493 }
494 }
b8a4ead8 495
496 // @todo CRM-17253 don't resolve contact details if there are no tokens
497 // effectively comment out this next (performance-expensive) line
498 // but unfortunately testing is a bit think on the ground to that needs to
499 // be added.
6a488035
TO
500 list($contact) = CRM_Utils_Token::getTokenDetails($contactParams,
501 $returnProperties,
502 FALSE, FALSE, NULL,
503 CRM_Utils_Token::flattenTokens($tokens),
504 // we should consider adding groupName and valueName here
505 'CRM_Core_BAO_MessageTemplate'
506 );
507 $contact = $contact[$contactID];
508 }
509
ccb438e6 510 $mailContent['subject'] = CRM_Utils_Token::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['subject'], TRUE);
14bf6806
AF
511 $mailContent['text'] = CRM_Utils_Token::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE);
512 $mailContent['html'] = CRM_Utils_Token::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE);
6a488035
TO
513
514 if ($contactID) {
ccb438e6 515 $mailContent['subject'] = CRM_Utils_Token::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['subject'], FALSE, TRUE);
14bf6806
AF
516 $mailContent['text'] = CRM_Utils_Token::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE);
517 $mailContent['html'] = CRM_Utils_Token::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE);
6a488035 518
be2fb01f 519 $contactArray = [$contactID => $contact];
6a488035 520 CRM_Utils_Hook::tokenValues($contactArray,
be2fb01f 521 [$contactID],
6a488035
TO
522 NULL,
523 CRM_Utils_Token::flattenTokens($tokens),
524 // we should consider adding groupName and valueName here
525 'CRM_Core_BAO_MessageTemplate'
526 );
527 $contact = $contactArray[$contactID];
528
94993cf9 529 $mailContent['subject'] = CRM_Utils_Token::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE);
14bf6806
AF
530 $mailContent['text'] = CRM_Utils_Token::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE);
531 $mailContent['html'] = CRM_Utils_Token::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE);
6a488035
TO
532 }
533
4ee279f4 534 // strip whitespace from ends and turn into a single line
94993cf9 535 $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}";
4ee279f4 536
537 // parse the three elements with Smarty
4ee279f4 538 $smarty = CRM_Core_Smarty::singleton();
539 foreach ($params['tplParams'] as $name => $value) {
540 $smarty->assign($name, $value);
541 }
be2fb01f 542 foreach ([
eff0a941
AF
543 'subject',
544 'text',
545 'html',
be2fb01f 546 ] as $elem) {
eff0a941 547 $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
4ee279f4 548 }
549
6a488035
TO
550 // send the template, honouring the target user’s preferences (if any)
551 $sent = FALSE;
552
553 // create the params array
94993cf9 554 $params['subject'] = $mailContent['subject'];
14bf6806
AF
555 $params['text'] = $mailContent['text'];
556 $params['html'] = $mailContent['html'];
6a488035
TO
557
558 if ($params['toEmail']) {
be2fb01f 559 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
6a488035
TO
560 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams);
561
562 $prefs = array_pop($contact);
563
564 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
565 $params['text'] = NULL;
566 }
567
568 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
569 $params['html'] = NULL;
570 }
571
572 $config = CRM_Core_Config::singleton();
9161952c 573 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
d141946b 574 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
9161952c 575 if (empty($params['attachments'])) {
be2fb01f 576 $params['attachments'] = [];
9161952c 577 }
14bf6806 578 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
9161952c 579 }
6a488035
TO
580 $pdf_filename = '';
581 if ($config->doNotAttachPDFReceipt &&
582 $params['PDFFilename'] &&
583 $params['html']
584 ) {
6a488035 585 if (empty($params['attachments'])) {
be2fb01f 586 $params['attachments'] = [];
6a488035 587 }
14bf6806 588 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
9849720e
RK
589 if (isset($params['tplParams']['email_comment'])) {
590 $params['html'] = $params['tplParams']['email_comment'];
d9e4ebe7 591 $params['text'] = strip_tags($params['tplParams']['email_comment']);
9849720e 592 }
6a488035
TO
593 }
594
595 $sent = CRM_Utils_Mail::send($params);
596
597 if ($pdf_filename) {
598 unlink($pdf_filename);
599 }
600 }
601
be2fb01f 602 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
6a488035 603 }
96025800 604
6a488035 605}