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