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 +--------------------------------------------------------------------+
12 use Civi\Token\TokenProcessor
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 use Civi\Api4\MessageTemplate
;
22 require_once 'Mail/mime.php';
25 * Class CRM_Core_BAO_MessageTemplate.
27 class CRM_Core_BAO_MessageTemplate
extends CRM_Core_DAO_MessageTemplate
{
30 * Fetch object based on array of properties.
32 * @param array $params
33 * (reference ) an assoc array of name/value pairs.
34 * @param array $defaults
35 * (reference ) an assoc array to hold the flattened values.
37 * @return CRM_Core_DAO_MessageTemplate
39 public static function retrieve(&$params, &$defaults) {
40 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
41 $messageTemplates->copyValues($params);
42 if ($messageTemplates->find(TRUE)) {
43 CRM_Core_DAO
::storeValues($messageTemplates, $defaults);
44 return $messageTemplates;
50 * Update the is_active flag in the db.
53 * Id of the database record.
54 * @param bool $is_active
55 * Value we want to set the is_active field.
58 * true if we found and updated the object, else false
60 public static function setIsActive($id, $is_active) {
61 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
65 * Add the Message Templates.
67 * @param array $params
68 * Reference array contains the values submitted by the form.
72 * @throws \CiviCRM_API3_Exception
73 * @throws \Civi\API\Exception\UnauthorizedException
75 public static function add(&$params) {
76 // System Workflow Templates have a specific wodkflow_id in them but normal user end message templates don't
77 // If we have an id check to see if we are update, and need to check if original is a system workflow or not.
78 $systemWorkflowPermissionDeniedMessage = 'Editing or creating system workflow messages requires edit system workflow message templates permission or the edit message templates permission';
79 $userWorkflowPermissionDeniedMessage = 'Editing or creating user driven workflow messages requires edit user-driven message templates or the edit message templates permission';
80 if (!empty($params['check_permissions'])) {
81 if (!CRM_Core_Permission
::check('edit message templates')) {
82 if (!empty($params['id'])) {
83 $details = civicrm_api3('MessageTemplate', 'getSingle', ['id' => $params['id']]);
84 if (!empty($details['workflow_id']) ||
!empty($details['workflow_name'])) {
85 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
86 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
89 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
90 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
94 if (!empty($params['workflow_id']) ||
!empty($params['workflow_name'])) {
95 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
96 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
99 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
100 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
105 $hook = empty($params['id']) ?
'create' : 'edit';
106 CRM_Utils_Hook
::pre($hook, 'MessageTemplate', CRM_Utils_Array
::value('id', $params), $params);
108 if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
109 $fileParams = $params['file_id'];
110 unset($params['file_id']);
113 // The workflow_id and workflow_name should be sync'd. But what mix of inputs do we have to work with?
114 switch ((empty($params['workflow_id']) ?
'' : 'id') . (empty($params['workflow_name']) ?
'' : 'name')) {
116 $params['workflow_name'] = array_search($params['workflow_id'], self
::getWorkflowNameIdMap());
120 $params['workflow_id'] = self
::getWorkflowNameIdMap()[$params['workflow_name']] ??
NULL;
124 $map = self
::getWorkflowNameIdMap();
125 if ($map[$params['workflow_name']] != $params['workflow_id']) {
126 throw new CRM_Core_Exception("The workflow_id and workflow_name are mismatched. Note: You only need to submit one or the other.");
135 throw new \
RuntimeException("Bad code");
138 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
139 $messageTemplates->copyValues($params);
140 $messageTemplates->save();
142 if (!empty($fileParams)) {
143 $params['file_id'] = $fileParams;
144 CRM_Core_BAO_File
::filePostProcess(
145 $params['file_id']['location'],
147 'civicrm_msg_template',
148 $messageTemplates->id
,
153 $params['file_id']['type']
157 CRM_Utils_Hook
::post($hook, 'MessageTemplate', $messageTemplates->id
, $messageTemplates);
158 return $messageTemplates;
162 * Delete the Message Templates.
164 * @param int $messageTemplatesID
166 * @throws \CRM_Core_Exception
168 public static function del($messageTemplatesID) {
169 // make sure messageTemplatesID is an integer
170 if (!CRM_Utils_Rule
::positiveInteger($messageTemplatesID)) {
171 throw new CRM_Core_Exception(ts('Invalid Message template'));
174 // Set mailing msg template col to NULL
175 $query = "UPDATE civicrm_mailing
176 SET msg_template_id = NULL
177 WHERE msg_template_id = %1";
179 $params = [1 => [$messageTemplatesID, 'Integer']];
180 CRM_Core_DAO
::executeQuery($query, $params);
182 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
183 $messageTemplates->id
= $messageTemplatesID;
184 $messageTemplates->delete();
185 CRM_Core_Session
::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
189 * Get the Message Templates.
198 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
201 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
202 $messageTemplates->is_active
= 1;
203 $messageTemplates->is_sms
= $isSMS;
206 $messageTemplates->workflow_id
= 'NULL';
208 $messageTemplates->find();
209 while ($messageTemplates->fetch()) {
210 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
217 * @param int $contactId
219 * @param int $messageTemplateID
223 * @throws \CRM_Core_Exception
225 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
226 CRM_Core_Error
::deprecatedWarning('CRM_Core_BAO_MessageTemplate::sendReminder is deprecated and will be removed in a future version of CiviCRM');
228 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
229 $messageTemplates->id
= $messageTemplateID;
231 $domain = CRM_Core_BAO_Domain
::getDomain();
235 if ($messageTemplates->find(TRUE)) {
236 $body_text = $messageTemplates->msg_text
;
237 $body_html = $messageTemplates->msg_html
;
238 $body_subject = $messageTemplates->msg_subject
;
240 $body_text = CRM_Utils_String
::htmlToText($body_html);
243 $params = [['contact_id', '=', $contactId, 0, 0]];
244 [$contact] = CRM_Contact_BAO_Query
::apiQuery($params);
247 $contact = reset($contact);
249 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
255 // get tokens to be replaced
256 $tokens = array_merge(CRM_Utils_Token
::getTokens($body_text),
257 CRM_Utils_Token
::getTokens($body_html),
258 CRM_Utils_Token
::getTokens($body_subject));
260 // get replacement text for these tokens
261 $returnProperties = ["preferred_mail_format" => 1];
262 if (isset($tokens['contact'])) {
263 foreach ($tokens['contact'] as $key => $value) {
264 $returnProperties[$value] = 1;
267 [$details] = CRM_Utils_Token
::getTokenDetails([$contactId],
271 'CRM_Core_BAO_MessageTemplate');
272 $contact = reset($details);
276 CRM_Utils_Hook
::tokens($hookTokens);
277 $categories = array_keys($hookTokens);
279 // do replacements in text and html body
280 $type = ['html', 'text'];
281 foreach ($type as $key => $value) {
282 $bodyType = "body_{$value}";
284 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
285 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens, TRUE);
286 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
287 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens, TRUE);
288 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
294 $smarty = CRM_Core_Smarty
::singleton();
299 $
$elem = $smarty->fetch("string:{$$elem}");
302 // do replacements in message subject
303 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
304 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
305 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
306 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
308 $messageSubject = $smarty->fetch("string:{$messageSubject}");
310 // set up the parameters for CRM_Utils_Mail::send
312 'groupName' => 'Scheduled Reminder Sender',
314 'toName' => $contact['display_name'],
316 'subject' => $messageSubject,
318 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
319 $contact['preferred_mail_format'] == 'Both'
321 // render the & entities in text mode, so that the links work
322 $mailParams['text'] = str_replace('&', '&', $text);
324 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
325 $contact['preferred_mail_format'] == 'Both'
328 $mailParams['html'] = $html;
331 $result = CRM_Utils_Mail
::send($mailParams);
338 * Revert a message template to its default subject+text+HTML state.
340 * @param int $id id of the template
342 * @throws \CRM_Core_Exception
344 public static function revert($id) {
345 $diverted = new CRM_Core_BAO_MessageTemplate();
346 $diverted->id
= (int) $id;
349 if ($diverted->N
!= 1) {
350 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
353 $orig = new CRM_Core_BAO_MessageTemplate();
354 $orig->workflow_id
= $diverted->workflow_id
;
355 $orig->is_reserved
= 1;
359 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
362 $diverted->msg_subject
= $orig->msg_subject
;
363 $diverted->msg_text
= $orig->msg_text
;
364 $diverted->msg_html
= $orig->msg_html
;
365 $diverted->pdf_format_id
= is_null($orig->pdf_format_id
) ?
'null' : $orig->pdf_format_id
;
370 * Send an email from the specified template based on an array of params.
372 * @param array $params
373 * A string-keyed array of function params, see function body for details.
376 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
377 * @throws \CRM_Core_Exception
378 * @throws \API_Exception
380 public static function sendTemplate($params) {
382 // option value name of the template
384 // ID of the template
385 'messageTemplateID' => NULL,
386 // contact id if contact tokens are to be replaced
388 // additional template params (other than the ones already set in the template singleton)
392 // the recipient’s name
394 // the recipient’s email - mail is sent only if set
400 // the Reply-To: header
403 'attachments' => NULL,
404 // whether this is a test email (and hence should include the test banner)
406 // filename of optional PDF version to add as attachment (do not include path)
407 'PDFFilename' => NULL,
409 'disableSmarty' => FALSE,
411 $params = array_merge($defaults, $params);
413 // Core#644 - handle Email ID passed as "From".
414 if (isset($params['from'])) {
415 $params['from'] = CRM_Utils_Mail
::formatFromAddress($params['from']);
418 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
419 if (!is_int($params['messageTemplateID']) && !is_null($params['messageTemplateID'])) {
420 CRM_Core_Error
::deprecatedWarning('message template id should be an integer');
421 $params['messageTemplateID'] = (int) $params['messageTemplateID'];
423 $mailContent = self
::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ??
NULL, $params['groupName'] ??
'');
425 // Overwrite subject from form field
426 if (!empty($params['subject'])) {
427 $mailContent['subject'] = $params['subject'];
430 $mailContent = self
::renderMessageTemplate($mailContent, (bool) $params['disableSmarty'], $params['contactId'] ??
NULL, $params['tplParams']);
432 // send the template, honouring the target user’s preferences (if any)
435 // create the params array
436 $params['subject'] = $mailContent['subject'];
437 $params['text'] = $mailContent['text'];
438 $params['html'] = $mailContent['html'];
440 if ($params['toEmail']) {
441 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
442 [$contact] = CRM_Contact_BAO_Query
::apiQuery($contactParams);
444 $prefs = array_pop($contact);
446 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
447 $params['text'] = NULL;
450 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
451 $params['html'] = NULL;
454 $config = CRM_Core_Config
::singleton();
455 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
456 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
457 if (empty($params['attachments'])) {
458 $params['attachments'] = [];
460 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
463 if ($config->doNotAttachPDFReceipt
&&
464 $params['PDFFilename'] &&
467 if (empty($params['attachments'])) {
468 $params['attachments'] = [];
470 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
471 if (isset($params['tplParams']['email_comment'])) {
472 $params['html'] = $params['tplParams']['email_comment'];
473 $params['text'] = strip_tags($params['tplParams']['email_comment']);
477 $sent = CRM_Utils_Mail
::send($params);
480 unlink($pdf_filename);
484 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
488 * Create a map between workflow_name and workflow_id.
491 * Array(string $workflowName => int $workflowId)
493 protected static function getWorkflowNameIdMap() {
494 // There's probably some more clever way to do this, but this seems simple.
495 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', [
496 1 => ['msg_tpl_workflow_%', 'String'],
497 ])->fetchMap('name', 'id');
501 * Load the specified template.
503 * @param string $workflowName
504 * @param bool $isTest
505 * @param int|null $messageTemplateID
506 * @param string $groupName
509 * @throws \API_Exception
510 * @throws \CRM_Core_Exception
512 protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL): array {
513 if (!$workflowName && !$messageTemplateID) {
514 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
517 $apiCall = MessageTemplate
::get(FALSE)
518 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
519 ->addWhere('is_default', '=', 1);
521 if ($messageTemplateID) {
522 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
525 $apiCall->addWhere('workflow_name', '=', $workflowName);
527 $messageTemplate = $apiCall->execute()->first();
528 if (empty($messageTemplate['id'])) {
529 if ($messageTemplateID) {
530 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
532 throw new CRM_Core_Exception(ts('No message template with workflow name %2.', [2 => $workflowName]));
536 'subject' => $messageTemplate['msg_subject'],
537 'text' => $messageTemplate['msg_text'],
538 'html' => $messageTemplate['msg_html'],
539 'format' => $messageTemplate['pdf_format_id'],
540 // Workflow name is the field in the message templates table that denotes the
541 // workflow the template is used for. This is intended to eventually
542 // replace the non-standard option value/group implementation - see
543 // https://github.com/civicrm/civicrm-core/pull/17227 and the longer
544 // discussion on https://github.com/civicrm/civicrm-core/pull/17180
545 'workflow_name' => $workflowName,
546 // Note messageTemplateID is the id but when present we also know it was specifically requested.
547 'messageTemplateID' => $messageTemplateID,
548 // Group name & valueName are deprecated parameters. At some point it will not be passed out.
549 // https://github.com/civicrm/civicrm-core/pull/17180
550 'groupName' => $groupName,
551 'valueName' => $workflowName,
554 CRM_Utils_Hook
::alterMailContent($mailContent);
556 // add the test banner (if requested)
558 $testText = MessageTemplate
::get(FALSE)
559 ->setSelect(['msg_subject', 'msg_text', 'msg_html'])
560 ->addWhere('workflow_name', '=', 'test_preview')
561 ->addWhere('is_default', '=', TRUE)
562 ->execute()->first();
564 $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject'];
565 $mailContent['text'] = $testText['msg_text'] . $mailContent['text'];
566 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']);
573 * Render the message template, resolving tokens and smarty tokens.
575 * As with all BAO methods this should not be called directly outside
576 * of tested core code and is highly likely to change.
578 * @param array $mailContent
579 * @param bool $disableSmarty
580 * @param int|NULL $contactID
581 * @param array $smartyAssigns
585 public static function renderMessageTemplate(array $mailContent, bool $disableSmarty, $contactID, array $smartyAssigns): array {
586 CRM_Core_Smarty
::singleton()->pushScope($smartyAssigns);
587 $tokenProcessor = new TokenProcessor(\Civi
::dispatcher(), ['smarty' => !$disableSmarty]);
588 $tokenProcessor->addMessage('html', $mailContent['html'], 'text/html');
589 $tokenProcessor->addMessage('text', $mailContent['text'], 'text/plain');
590 $tokenProcessor->addMessage('subject', $mailContent['subject'], 'text/plain');
591 $tokenProcessor->addRow($contactID ?
['contactId' => $contactID] : []);
592 $tokenProcessor->evaluate();
593 foreach ($tokenProcessor->getRows() as $row) {
594 $mailContent['html'] = $row->render('html');
595 $mailContent['text'] = $row->render('text');
596 $mailContent['subject'] = $row->render('subject');
598 CRM_Core_Smarty
::singleton()->popScope();
599 $mailContent['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $mailContent['subject']));