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