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
;
20 require_once 'Mail/mime.php';
23 * Class CRM_Core_BAO_MessageTemplate.
25 class CRM_Core_BAO_MessageTemplate
extends CRM_Core_DAO_MessageTemplate
{
28 * Fetch object based on array of properties.
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.
35 * @return CRM_Core_DAO_MessageTemplate
37 public static function retrieve(&$params, &$defaults) {
38 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
39 $messageTemplates->copyValues($params);
40 if ($messageTemplates->find(TRUE)) {
41 CRM_Core_DAO
::storeValues($messageTemplates, $defaults);
42 return $messageTemplates;
48 * Update the is_active flag in the db.
51 * Id of the database record.
52 * @param bool $is_active
53 * Value we want to set the is_active field.
56 * true if we found and updated the object, else false
58 public static function setIsActive($id, $is_active) {
59 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
63 * Add the Message Templates.
65 * @param array $params
66 * Reference array contains the values submitted by the form.
70 * @throws \CiviCRM_API3_Exception
71 * @throws \Civi\API\Exception\UnauthorizedException
73 public static function add(&$params) {
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']]);
82 if (!empty($details['workflow_id']) ||
!empty($details['workflow_name'])) {
83 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
84 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
87 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
88 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
92 if (!empty($params['workflow_id']) ||
!empty($params['workflow_name'])) {
93 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
94 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
97 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
98 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
103 $hook = empty($params['id']) ?
'create' : 'edit';
104 CRM_Utils_Hook
::pre($hook, 'MessageTemplate', CRM_Utils_Array
::value('id', $params), $params);
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']);
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')) {
114 $params['workflow_name'] = array_search($params['workflow_id'], self
::getWorkflowNameIdMap());
118 $params['workflow_id'] = self
::getWorkflowNameIdMap()[$params['workflow_name']] ??
NULL;
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.");
133 throw new \
RuntimeException("Bad code");
136 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
137 $messageTemplates->copyValues($params);
138 $messageTemplates->save();
140 if (!empty($fileParams)) {
141 $params['file_id'] = $fileParams;
142 CRM_Core_BAO_File
::filePostProcess(
143 $params['file_id']['location'],
145 'civicrm_msg_template',
146 $messageTemplates->id
,
151 $params['file_id']['type']
155 CRM_Utils_Hook
::post($hook, 'MessageTemplate', $messageTemplates->id
, $messageTemplates);
156 return $messageTemplates;
160 * Delete the Message Templates.
162 * @param int $messageTemplatesID
164 * @throws \CRM_Core_Exception
166 public static function del($messageTemplatesID) {
167 // make sure messageTemplatesID is an integer
168 if (!CRM_Utils_Rule
::positiveInteger($messageTemplatesID)) {
169 throw new CRM_Core_Exception(ts('Invalid Message template'));
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";
177 $params = [1 => [$messageTemplatesID, 'Integer']];
178 CRM_Core_DAO
::executeQuery($query, $params);
180 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
181 $messageTemplates->id
= $messageTemplatesID;
182 $messageTemplates->delete();
183 CRM_Core_Session
::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
187 * Get the Message Templates.
196 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
199 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
200 $messageTemplates->is_active
= 1;
201 $messageTemplates->is_sms
= $isSMS;
204 $messageTemplates->workflow_id
= 'NULL';
206 $messageTemplates->find();
207 while ($messageTemplates->fetch()) {
208 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
215 * @param int $contactId
217 * @param int $messageTemplateID
221 * @throws \CRM_Core_Exception
223 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
225 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
226 $messageTemplates->id
= $messageTemplateID;
228 $domain = CRM_Core_BAO_Domain
::getDomain();
232 if ($messageTemplates->find(TRUE)) {
233 $body_text = $messageTemplates->msg_text
;
234 $body_html = $messageTemplates->msg_html
;
235 $body_subject = $messageTemplates->msg_subject
;
237 $body_text = CRM_Utils_String
::htmlToText($body_html);
240 $params = [['contact_id', '=', $contactId, 0, 0]];
241 [$contact] = CRM_Contact_BAO_Query
::apiQuery($params);
244 $contact = reset($contact);
246 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
252 // get tokens to be replaced
253 $tokens = array_merge(CRM_Utils_Token
::getTokens($body_text),
254 CRM_Utils_Token
::getTokens($body_html),
255 CRM_Utils_Token
::getTokens($body_subject));
257 // get replacement text for these tokens
258 $returnProperties = ["preferred_mail_format" => 1];
259 if (isset($tokens['contact'])) {
260 foreach ($tokens['contact'] as $key => $value) {
261 $returnProperties[$value] = 1;
264 list($details) = CRM_Utils_Token
::getTokenDetails([$contactId],
268 'CRM_Core_BAO_MessageTemplate');
269 $contact = reset($details);
273 CRM_Utils_Hook
::tokens($hookTokens);
274 $categories = array_keys($hookTokens);
276 // do replacements in text and html body
277 $type = ['html', 'text'];
278 foreach ($type as $key => $value) {
279 $bodyType = "body_{$value}";
281 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
282 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens, TRUE);
283 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
284 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens, TRUE);
285 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
291 $smarty = CRM_Core_Smarty
::singleton();
296 $
$elem = $smarty->fetch("string:{$$elem}");
299 // do replacements in message subject
300 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
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);
305 $messageSubject = $smarty->fetch("string:{$messageSubject}");
307 // set up the parameters for CRM_Utils_Mail::send
309 'groupName' => 'Scheduled Reminder Sender',
311 'toName' => $contact['display_name'],
313 'subject' => $messageSubject,
315 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
316 $contact['preferred_mail_format'] == 'Both'
318 // render the & entities in text mode, so that the links work
319 $mailParams['text'] = str_replace('&', '&', $text);
321 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
322 $contact['preferred_mail_format'] == 'Both'
325 $mailParams['html'] = $html;
328 $result = CRM_Utils_Mail
::send($mailParams);
335 * Revert a message template to its default subject+text+HTML state.
337 * @param int $id id of the template
339 * @throws \CRM_Core_Exception
341 public static function revert($id) {
342 $diverted = new CRM_Core_BAO_MessageTemplate();
343 $diverted->id
= (int) $id;
346 if ($diverted->N
!= 1) {
347 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
350 $orig = new CRM_Core_BAO_MessageTemplate();
351 $orig->workflow_id
= $diverted->workflow_id
;
352 $orig->is_reserved
= 1;
356 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
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
;
367 * Send an email from the specified template based on an array of params.
369 * @param array $params
370 * A string-keyed array of function params, see function body for details.
373 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
374 * @throws \CRM_Core_Exception
375 * @throws \API_Exception
377 public static function sendTemplate($params) {
379 // option value name of the template
381 // ID of the template
382 'messageTemplateID' => NULL,
383 // contact id if contact tokens are to be replaced
385 // additional template params (other than the ones already set in the template singleton)
389 // the recipient’s name
391 // the recipient’s email - mail is sent only if set
397 // the Reply-To: header
400 'attachments' => NULL,
401 // whether this is a test email (and hence should include the test banner)
403 // filename of optional PDF version to add as attachment (do not include path)
404 'PDFFilename' => NULL,
406 'disableSmarty' => FALSE,
408 $params = array_merge($defaults, $params);
410 // Core#644 - handle Email ID passed as "From".
411 if (isset($params['from'])) {
412 $params['from'] = CRM_Utils_Mail
::formatFromAddress($params['from']);
415 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
417 if (!$params['valueName'] && !$params['messageTemplateID']) {
418 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
421 $apiCall = MessageTemplate
::get(FALSE)
422 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
423 ->addWhere('is_default', '=', 1);
425 if ($params['messageTemplateID']) {
426 $apiCall->addWhere('id', '=', (int) $params['messageTemplateID']);
429 $apiCall->addWhere('workflow_name', '=', $params['valueName']);
431 $messageTemplate = $apiCall->execute()->first();
433 if (empty($messageTemplate['id'])) {
434 if ($params['messageTemplateID']) {
435 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $params['messageTemplateID']]));
437 throw new CRM_Core_Exception(ts('No message template with workflow name %2.', [2 => $params['valueName']]));
441 'subject' => $messageTemplate['msg_subject'],
442 'text' => $messageTemplate['msg_text'],
443 'html' => $messageTemplate['msg_html'],
444 'format' => $messageTemplate['pdf_format_id'],
445 // Group name is a deprecated parameter. At some point it will not be passed out.
446 // https://github.com/civicrm/civicrm-core/pull/17180
447 'groupName' => $params['groupName'] ??
NULL,
448 'valueName' => $params['valueName'],
449 'messageTemplateID' => $params['messageTemplateID'],
452 CRM_Utils_Hook
::alterMailContent($mailContent);
454 // add the test banner (if requested)
455 if ($params['isTest']) {
456 $query = "SELECT msg_subject subject, msg_text text, msg_html html
457 FROM civicrm_msg_template mt
458 WHERE workflow_name = 'test_preview' AND mt.is_default = 1";
459 $testDao = CRM_Core_DAO
::executeQuery($query);
462 $mailContent['subject'] = $testDao->subject
. $mailContent['subject'];
463 $mailContent['text'] = $testDao->text
. $mailContent['text'];
464 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']);
467 // Overwrite subject from form field
468 if (!empty($params['subject'])) {
469 $mailContent['subject'] = $params['subject'];
472 // replace tokens in the three elements (in subject as if it was the text body)
473 $domain = CRM_Core_BAO_Domain
::getDomain();
475 $mailing = new CRM_Mailing_BAO_Mailing();
476 $mailing->subject
= $mailContent['subject'];
477 $mailing->body_text
= $mailContent['text'];
478 $mailing->body_html
= $mailContent['html'];
479 $tokens = $mailing->getTokens();
480 CRM_Utils_Hook
::tokens($hookTokens);
481 $categories = array_keys($hookTokens);
483 $contactID = $params['contactId'] ??
NULL;
486 $contactParams = ['contact_id' => $contactID];
487 $returnProperties = [];
489 if (isset($tokens['subject']['contact'])) {
490 foreach ($tokens['subject']['contact'] as $name) {
491 $returnProperties[$name] = 1;
495 if (isset($tokens['text']['contact'])) {
496 foreach ($tokens['text']['contact'] as $name) {
497 $returnProperties[$name] = 1;
501 if (isset($tokens['html']['contact'])) {
502 foreach ($tokens['html']['contact'] as $name) {
503 $returnProperties[$name] = 1;
507 // @todo CRM-17253 don't resolve contact details if there are no tokens
508 // effectively comment out this next (performance-expensive) line
509 // but unfortunately testing is a bit think on the ground to that needs to
511 list($contact) = CRM_Utils_Token
::getTokenDetails($contactParams,
514 CRM_Utils_Token
::flattenTokens($tokens),
515 // we should consider adding valueName here
516 'CRM_Core_BAO_MessageTemplate'
518 $contact = $contact[$contactID];
521 // When using Smarty we need to pass the $escapeSmarty parameter.
522 $escapeSmarty = !$params['disableSmarty'];
524 $mailContent['subject'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['subject'], $escapeSmarty);
525 $mailContent['text'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], $escapeSmarty);
526 $mailContent['html'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], $escapeSmarty);
529 $mailContent['subject'] = CRM_Utils_Token
::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['subject'], FALSE, $escapeSmarty);
530 $mailContent['text'] = CRM_Utils_Token
::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, $escapeSmarty);
531 $mailContent['html'] = CRM_Utils_Token
::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, $escapeSmarty);
533 $contactArray = [$contactID => $contact];
534 CRM_Utils_Hook
::tokenValues($contactArray,
537 CRM_Utils_Token
::flattenTokens($tokens),
538 // we should consider adding valueName here
539 'CRM_Core_BAO_MessageTemplate'
541 $contact = $contactArray[$contactID];
543 $mailContent['subject'] = CRM_Utils_Token
::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE);
544 $mailContent['text'] = CRM_Utils_Token
::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE);
545 $mailContent['html'] = CRM_Utils_Token
::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE);
548 // Normally Smarty is run, but it can be disabled using the disableSmarty
549 // parameter, which may be useful for non-core uses of MessageTemplate.send
550 // In particular it helps with the mosaicomsgtpl extension.
551 if (!$params['disableSmarty']) {
552 // strip whitespace from ends and turn into a single line
553 $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}";
555 // parse the three elements with Smarty
556 $smarty = CRM_Core_Smarty
::singleton();
557 foreach ($params['tplParams'] as $name => $value) {
558 $smarty->assign($name, $value);
565 $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
569 // Since we're not relying on Smarty for this function, we DIY.
570 // strip whitespace from ends and turn into a single line
571 $mailContent['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $mailContent['subject']));
574 // send the template, honouring the target user’s preferences (if any)
577 // create the params array
578 $params['subject'] = $mailContent['subject'];
579 $params['text'] = $mailContent['text'];
580 $params['html'] = $mailContent['html'];
582 if ($params['toEmail']) {
583 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
584 [$contact] = CRM_Contact_BAO_Query
::apiQuery($contactParams);
586 $prefs = array_pop($contact);
588 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
589 $params['text'] = NULL;
592 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
593 $params['html'] = NULL;
596 $config = CRM_Core_Config
::singleton();
597 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
598 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
599 if (empty($params['attachments'])) {
600 $params['attachments'] = [];
602 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
605 if ($config->doNotAttachPDFReceipt
&&
606 $params['PDFFilename'] &&
609 if (empty($params['attachments'])) {
610 $params['attachments'] = [];
612 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
613 if (isset($params['tplParams']['email_comment'])) {
614 $params['html'] = $params['tplParams']['email_comment'];
615 $params['text'] = strip_tags($params['tplParams']['email_comment']);
619 $sent = CRM_Utils_Mail
::send($params);
622 unlink($pdf_filename);
626 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
630 * Create a map between workflow_name and workflow_id.
633 * Array(string $workflowName => int $workflowId)
635 protected static function getWorkflowNameIdMap() {
636 // There's probably some more clever way to do this, but this seems simple.
637 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', [
638 1 => ['msg_tpl_workflow_%', 'String'],
639 ])->fetchMap('name', 'id');