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