3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 use Civi\Api4\MessageTemplate
;
19 use Civi\WorkflowMessage\WorkflowMessage
;
21 require_once 'Mail/mime.php';
24 * Class CRM_Core_BAO_MessageTemplate.
26 class CRM_Core_BAO_MessageTemplate
extends CRM_Core_DAO_MessageTemplate
{
29 * Fetch object based on array of properties.
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.
36 * @return CRM_Core_DAO_MessageTemplate
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;
49 * Update the is_active flag in the db.
52 * Id of the database record.
53 * @param bool $is_active
54 * Value we want to set the is_active field.
57 * true if we found and updated the object, else false
59 public static function setIsActive($id, $is_active) {
60 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
64 * Add the Message Templates.
66 * @param array $params
67 * Reference array contains the values submitted by the form.
71 * @throws \CiviCRM_API3_Exception
72 * @throws \Civi\API\Exception\UnauthorizedException
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]));
88 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
89 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
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]));
98 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
99 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
104 $hook = empty($params['id']) ?
'create' : 'edit';
105 CRM_Utils_Hook
::pre($hook, 'MessageTemplate', CRM_Utils_Array
::value('id', $params), $params);
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']);
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')) {
115 $params['workflow_name'] = array_search($params['workflow_id'], self
::getWorkflowNameIdMap());
119 $params['workflow_id'] = self
::getWorkflowNameIdMap()[$params['workflow_name']] ??
NULL;
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.");
134 throw new \
RuntimeException("Bad code");
137 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
138 $messageTemplates->copyValues($params);
139 $messageTemplates->save();
141 if (!empty($fileParams)) {
142 $params['file_id'] = $fileParams;
143 CRM_Core_BAO_File
::filePostProcess(
144 $params['file_id']['location'],
146 'civicrm_msg_template',
147 $messageTemplates->id
,
152 $params['file_id']['type']
156 CRM_Utils_Hook
::post($hook, 'MessageTemplate', $messageTemplates->id
, $messageTemplates);
157 return $messageTemplates;
161 * Delete the Message Templates.
163 * @param int $messageTemplatesID
165 * @throws \CRM_Core_Exception
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'));
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";
178 $params = [1 => [$messageTemplatesID, 'Integer']];
179 CRM_Core_DAO
::executeQuery($query, $params);
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');
188 * Get the Message Templates.
197 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
200 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
201 $messageTemplates->is_active
= 1;
202 $messageTemplates->is_sms
= $isSMS;
205 $messageTemplates->workflow_id
= 'NULL';
207 $messageTemplates->find();
208 while ($messageTemplates->fetch()) {
209 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
216 * @param int $contactId
218 * @param int $messageTemplateID
222 * @throws \CRM_Core_Exception
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');
227 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
228 $messageTemplates->id
= $messageTemplateID;
230 $domain = CRM_Core_BAO_Domain
::getDomain();
234 if ($messageTemplates->find(TRUE)) {
235 $body_text = $messageTemplates->msg_text
;
236 $body_html = $messageTemplates->msg_html
;
237 $body_subject = $messageTemplates->msg_subject
;
239 $body_text = CRM_Utils_String
::htmlToText($body_html);
242 $params = [['contact_id', '=', $contactId, 0, 0]];
243 [$contact] = CRM_Contact_BAO_Query
::apiQuery($params);
246 $contact = reset($contact);
248 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
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));
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;
266 [$details] = CRM_Utils_Token
::getTokenDetails([$contactId],
270 'CRM_Core_BAO_MessageTemplate');
271 $contact = reset($details);
275 CRM_Utils_Hook
::tokens($hookTokens);
276 $categories = array_keys($hookTokens);
278 // do replacements in text and html body
279 $type = ['html', 'text'];
280 foreach ($type as $key => $value) {
281 $bodyType = "body_{$value}";
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);
293 $smarty = CRM_Core_Smarty
::singleton();
298 $
$elem = $smarty->fetch("string:{$$elem}");
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);
307 $messageSubject = $smarty->fetch("string:{$messageSubject}");
309 // set up the parameters for CRM_Utils_Mail::send
311 'groupName' => 'Scheduled Reminder Sender',
313 'toName' => $contact['display_name'],
315 'subject' => $messageSubject,
317 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
318 $contact['preferred_mail_format'] == 'Both'
320 // render the & entities in text mode, so that the links work
321 $mailParams['text'] = str_replace('&', '&', $text);
323 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
324 $contact['preferred_mail_format'] == 'Both'
327 $mailParams['html'] = $html;
330 $result = CRM_Utils_Mail
::send($mailParams);
337 * Revert a message template to its default subject+text+HTML state.
339 * @param int $id id of the template
341 * @throws \CRM_Core_Exception
343 public static function revert($id) {
344 $diverted = new CRM_Core_BAO_MessageTemplate();
345 $diverted->id
= (int) $id;
348 if ($diverted->N
!= 1) {
349 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
352 $orig = new CRM_Core_BAO_MessageTemplate();
353 $orig->workflow_id
= $diverted->workflow_id
;
354 $orig->is_reserved
= 1;
358 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
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
;
369 * Render a message template.
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.
376 * Mixed render parameters. See sendTemplate() for more details.
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()
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)));
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);
400 * Send an email from the specified template based on an array of params.
402 * @param array $params
403 * A string-keyed array of function params, see function body for details.
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
410 public static function sendTemplate($params) {
412 // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template
414 // Symbolic name of the workflow step. Matches the option-value-name of the template.
416 // additional template params (other than the ones already set in the template singleton)
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
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)
436 'disableSmarty' => FALSE,
438 $envelopeDefaults = [
441 // the recipient’s name
443 // the recipient’s email - mail is sent only if set
449 // the Reply-To: header
452 'attachments' => NULL,
453 // filename of optional PDF version to add as attachment (do not include path)
454 'PDFFilename' => NULL,
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()`.
464 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
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'];
471 $mailContent = self
::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ??
NULL, $params['groupName'] ??
'', $params['messageTemplate'], $params['subject'] ??
NULL);
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']));
481 $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL];
482 $mailContent = array_merge($nullSet, $mailContent, $rendered);
484 // send the template, honouring the target user’s preferences (if any)
487 // create the params array
488 $params['subject'] = $mailContent['subject'];
489 $params['text'] = $mailContent['text'];
490 $params['html'] = $mailContent['html'];
492 if ($params['toEmail']) {
493 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
494 [$contact] = CRM_Contact_BAO_Query
::apiQuery($contactParams);
496 $prefs = array_pop($contact);
498 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
499 $params['text'] = NULL;
502 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
503 $params['html'] = NULL;
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'] = [];
513 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
516 if ($config->doNotAttachPDFReceipt
&&
517 $params['PDFFilename'] &&
520 if (empty($params['attachments'])) {
521 $params['attachments'] = [];
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']);
530 $sent = CRM_Utils_Mail
::send($params);
533 unlink($pdf_filename);
537 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
541 * Create a map between workflow_name and workflow_id.
544 * Array(string $workflowName => int $workflowId)
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');
554 * Load the specified template.
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']...
567 * @throws \API_Exception
568 * @throws \CRM_Core_Exception
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."));
576 $apiCall = MessageTemplate
::get(FALSE)
577 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
578 ->addWhere('is_default', '=', 1);
580 if ($messageTemplateID) {
581 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
584 $apiCall->addWhere('workflow_name', '=', $workflowName);
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]));
591 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
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,
613 CRM_Utils_Hook
::alterMailContent($mailContent);
615 // add the test banner (if requested)
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();
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']);
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;