Merge pull request #21323 from civicrm/5.41
[civicrm-core.git] / CRM / Core / BAO / MessageTemplate.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 use Civi\Api4\MessageTemplate;
19 use Civi\WorkflowMessage\WorkflowMessage;
20
21 require_once 'Mail/mime.php';
22
23 /**
24 * Class CRM_Core_BAO_MessageTemplate.
25 */
26 class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
27
28 /**
29 * Fetch object based on array of properties.
30 *
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.
35 *
36 * @return CRM_Core_DAO_MessageTemplate
37 */
38 public static function retrieve(&$params, &$defaults) {
39 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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 /**
49 * Update the is_active flag in the db.
50 *
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.
55 *
56 * @return bool
57 * true if we found and updated the object, else false
58 */
59 public static function setIsActive($id, $is_active) {
60 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
61 }
62
63 /**
64 * Add the Message Templates.
65 *
66 * @param array $params
67 * Reference array contains the values submitted by the form.
68 *
69 *
70 * @return object
71 * @throws \CiviCRM_API3_Exception
72 * @throws \Civi\API\Exception\UnauthorizedException
73 */
74 public static function add(&$params) {
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']]);
83 if (!empty($details['workflow_id']) || !empty($details['workflow_name'])) {
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 {
93 if (!empty($params['workflow_id']) || !empty($params['workflow_name'])) {
94 if (!CRM_Core_Permission::check('edit system workflow message templates')) {
95 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
96 }
97 }
98 elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
99 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
100 }
101 }
102 }
103 }
104 $hook = empty($params['id']) ? 'create' : 'edit';
105 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
106
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
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
137 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
138 $messageTemplates->copyValues($params);
139 $messageTemplates->save();
140
141 if (!empty($fileParams)) {
142 $params['file_id'] = $fileParams;
143 CRM_Core_BAO_File::filePostProcess(
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 );
154 }
155
156 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
157 return $messageTemplates;
158 }
159
160 /**
161 * Delete the Message Templates.
162 *
163 * @param int $messageTemplatesID
164 *
165 * @throws \CRM_Core_Exception
166 */
167 public static function del($messageTemplatesID) {
168 // make sure messageTemplatesID is an integer
169 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
170 throw new CRM_Core_Exception(ts('Invalid Message template'));
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";
177
178 $params = [1 => [$messageTemplatesID, 'Integer']];
179 CRM_Core_DAO::executeQuery($query, $params);
180
181 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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 /**
188 * Get the Message Templates.
189 *
190 *
191 * @param bool $all
192 *
193 * @param bool $isSMS
194 *
195 * @return array
196 */
197 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
198 $msgTpls = [];
199
200 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
201 $messageTemplates->is_active = 1;
202 $messageTemplates->is_sms = $isSMS;
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
215 /**
216 * @param int $contactId
217 * @param $email
218 * @param int $messageTemplateID
219 * @param $from
220 *
221 * @return bool|NULL
222 * @throws \CRM_Core_Exception
223 */
224 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
225 CRM_Core_Error::deprecatedWarning('CRM_Core_BAO_MessageTemplate::sendReminder is deprecated and will be removed in a future version of CiviCRM');
226
227 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
228 $messageTemplates->id = $messageTemplateID;
229
230 $domain = CRM_Core_BAO_Domain::getDomain();
231 $result = NULL;
232 $hookTokens = [];
233
234 if ($messageTemplates->find(TRUE)) {
235 $body_text = $messageTemplates->msg_text;
236 $body_html = $messageTemplates->msg_html;
237 $body_subject = $messageTemplates->msg_subject;
238 if (!$body_text) {
239 $body_text = CRM_Utils_String::htmlToText($body_html);
240 }
241
242 $params = [['contact_id', '=', $contactId, 0, 0]];
243 [$contact] = CRM_Contact_BAO_Query::apiQuery($params);
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),
256 CRM_Utils_Token::getTokens($body_html),
257 CRM_Utils_Token::getTokens($body_subject));
258
259 // get replacement text for these tokens
260 $returnProperties = ["preferred_mail_format" => 1];
261 if (isset($tokens['contact'])) {
262 foreach ($tokens['contact'] as $key => $value) {
263 $returnProperties[$value] = 1;
264 }
265 }
266 [$details] = CRM_Utils_Token::getTokenDetails([$contactId],
267 $returnProperties,
268 NULL, NULL, FALSE,
269 $tokens,
270 'CRM_Core_BAO_MessageTemplate');
271 $contact = reset($details);
272
273 // call token hook
274 $hookTokens = [];
275 CRM_Utils_Hook::tokens($hookTokens);
276 $categories = array_keys($hookTokens);
277
278 // do replacements in text and html body
279 $type = ['html', 'text'];
280 foreach ($type as $key => $value) {
281 $bodyType = "body_{$value}";
282 if ($$bodyType) {
283 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
284 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens, TRUE);
285 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
286 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, TRUE);
287 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
288 }
289 }
290 $html = $body_html;
291 $text = $body_text;
292
293 $smarty = CRM_Core_Smarty::singleton();
294 foreach ([
295 'text',
296 'html',
297 ] as $elem) {
298 $$elem = $smarty->fetch("string:{$$elem}");
299 }
300
301 // do replacements in message subject
302 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
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);
306
307 $messageSubject = $smarty->fetch("string:{$messageSubject}");
308
309 // set up the parameters for CRM_Utils_Mail::send
310 $mailParams = [
311 'groupName' => 'Scheduled Reminder Sender',
312 'from' => $from,
313 'toName' => $contact['display_name'],
314 'toEmail' => $email,
315 'subject' => $messageSubject,
316 ];
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'
325 )
326 ) {
327 $mailParams['html'] = $html;
328 }
329
330 $result = CRM_Utils_Mail::send($mailParams);
331 }
332
333 return $result;
334 }
335
336 /**
337 * Revert a message template to its default subject+text+HTML state.
338 *
339 * @param int $id id of the template
340 *
341 * @throws \CRM_Core_Exception
342 */
343 public static function revert($id) {
344 $diverted = new CRM_Core_BAO_MessageTemplate();
345 $diverted->id = (int) $id;
346 $diverted->find(1);
347
348 if ($diverted->N != 1) {
349 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
350 }
351
352 $orig = new CRM_Core_BAO_MessageTemplate();
353 $orig->workflow_id = $diverted->workflow_id;
354 $orig->is_reserved = 1;
355 $orig->find(1);
356
357 if ($orig->N != 1) {
358 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
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
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
399 /**
400 * Send an email from the specified template based on an array of params.
401 *
402 * @param array $params
403 * A string-keyed array of function params, see function body for details.
404 *
405 * @return array
406 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
407 * @throws \CRM_Core_Exception
408 * @throws \API_Exception
409 */
410 public static function sendTemplate($params) {
411 $modelDefaults = [
412 // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template
413 'model' => NULL,
414 // Symbolic name of the workflow step. Matches the option-value-name of the template.
415 'valueName' => NULL,
416 // additional template params (other than the ones already set in the template singleton)
417 'tplParams' => [],
418 // additional token params (passed to the TokenProcessor)
419 // INTERNAL: 'tokenContext' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
420 'tokenContext' => [],
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 = [
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,
453 // filename of optional PDF version to add as attachment (do not include path)
454 'PDFFilename' => NULL,
455 ];
456
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
464 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
465
466 CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
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'];
470 }
471 $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '', $params['messageTemplate'], $params['subject'] ?? NULL);
472
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);
483
484 // send the template, honouring the target user’s preferences (if any)
485 $sent = FALSE;
486
487 // create the params array
488 $params['subject'] = $mailContent['subject'];
489 $params['text'] = $mailContent['text'];
490 $params['html'] = $mailContent['html'];
491
492 if ($params['toEmail']) {
493 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
494 [$contact] = CRM_Contact_BAO_Query::apiQuery($contactParams);
495
496 $prefs = array_pop($contact);
497
498 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
499 $params['text'] = NULL;
500 }
501
502 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
503 $params['html'] = NULL;
504 }
505
506 $config = CRM_Core_Config::singleton();
507 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
508 // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId.
509 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
510 if (empty($params['attachments'])) {
511 $params['attachments'] = [];
512 }
513 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
514 }
515 $pdf_filename = '';
516 if ($config->doNotAttachPDFReceipt &&
517 $params['PDFFilename'] &&
518 $params['html']
519 ) {
520 if (empty($params['attachments'])) {
521 $params['attachments'] = [];
522 }
523 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
524 if (isset($params['tplParams']['email_comment'])) {
525 $params['html'] = $params['tplParams']['email_comment'];
526 $params['text'] = strip_tags($params['tplParams']['email_comment']);
527 }
528 }
529
530 $sent = CRM_Utils_Mail::send($params);
531
532 if ($pdf_filename) {
533 unlink($pdf_filename);
534 }
535 }
536
537 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
538 }
539
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
553 /**
554 * Load the specified template.
555 *
556 * @param string $workflowName
557 * @param bool $isTest
558 * @param int|null $messageTemplateID
559 * @param string $groupName
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']...
565 *
566 * @return array
567 * @throws \API_Exception
568 * @throws \CRM_Core_Exception
569 */
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];
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 }
586 $messageTemplate = array_merge($base, $apiCall->execute()->first() ?: [], $messageTemplateOverride ?: []);
587 if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) {
588 if ($messageTemplateID) {
589 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
590 }
591 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
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'],
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
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
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
633 return $mailContent;
634 }
635
636 }