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 require_once 'Mail/mime.php';
21 * Class CRM_Core_BAO_MessageTemplate.
23 class CRM_Core_BAO_MessageTemplate
extends CRM_Core_DAO_MessageTemplate
{
26 * Fetch object based on array of properties.
28 * @param array $params
29 * (reference ) an assoc array of name/value pairs.
30 * @param array $defaults
31 * (reference ) an assoc array to hold the flattened values.
33 * @return CRM_Core_DAO_MessageTemplate
35 public static function retrieve(&$params, &$defaults) {
36 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
37 $messageTemplates->copyValues($params);
38 if ($messageTemplates->find(TRUE)) {
39 CRM_Core_DAO
::storeValues($messageTemplates, $defaults);
40 return $messageTemplates;
46 * Update the is_active flag in the db.
49 * Id of the database record.
50 * @param bool $is_active
51 * Value we want to set the is_active field.
54 * true if we found and updated the object, else false
56 public static function setIsActive($id, $is_active) {
57 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
61 * Add the Message Templates.
63 * @param array $params
64 * Reference array contains the values submitted by the form.
68 * @throws \CiviCRM_API3_Exception
69 * @throws \Civi\API\Exception\UnauthorizedException
71 public static function add(&$params) {
72 // System Workflow Templates have a specific wodkflow_id in them but normal user end message templates don't
73 // If we have an id check to see if we are update, and need to check if original is a system workflow or not.
74 $systemWorkflowPermissionDeniedMessage = 'Editing or creating system workflow messages requires edit system workflow message templates permission or the edit message templates permission';
75 $userWorkflowPermissionDeniedMessage = 'Editing or creating user driven workflow messages requires edit user-driven message templates or the edit message templates permission';
76 if (!empty($params['check_permissions'])) {
77 if (!CRM_Core_Permission
::check('edit message templates')) {
78 if (!empty($params['id'])) {
79 $details = civicrm_api3('MessageTemplate', 'getSingle', ['id' => $params['id']]);
80 if (!empty($details['workflow_id'])) {
81 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
82 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
85 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
86 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
90 if (!empty($params['workflow_id'])) {
91 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
92 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
95 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
96 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
101 $hook = empty($params['id']) ?
'create' : 'edit';
102 CRM_Utils_Hook
::pre($hook, 'MessageTemplate', CRM_Utils_Array
::value('id', $params), $params);
104 if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
105 $fileParams = $params['file_id'];
106 unset($params['file_id']);
109 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
110 $messageTemplates->copyValues($params);
111 $messageTemplates->save();
113 if (!empty($fileParams)) {
114 $params['file_id'] = $fileParams;
115 CRM_Core_BAO_File
::filePostProcess(
116 $params['file_id']['location'],
118 'civicrm_msg_template',
119 $messageTemplates->id
,
124 $params['file_id']['type']
128 CRM_Utils_Hook
::post($hook, 'MessageTemplate', $messageTemplates->id
, $messageTemplates);
129 return $messageTemplates;
133 * Delete the Message Templates.
135 * @param int $messageTemplatesID
137 * @throws \CRM_Core_Exception
139 public static function del($messageTemplatesID) {
140 // make sure messageTemplatesID is an integer
141 if (!CRM_Utils_Rule
::positiveInteger($messageTemplatesID)) {
142 throw new CRM_Core_Exception(ts('Invalid Message template'));
145 // Set mailing msg template col to NULL
146 $query = "UPDATE civicrm_mailing
147 SET msg_template_id = NULL
148 WHERE msg_template_id = %1";
150 $params = [1 => [$messageTemplatesID, 'Integer']];
151 CRM_Core_DAO
::executeQuery($query, $params);
153 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
154 $messageTemplates->id
= $messageTemplatesID;
155 $messageTemplates->delete();
156 CRM_Core_Session
::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
160 * Get the Message Templates.
169 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
172 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
173 $messageTemplates->is_active
= 1;
174 $messageTemplates->is_sms
= $isSMS;
177 $messageTemplates->workflow_id
= 'NULL';
179 $messageTemplates->find();
180 while ($messageTemplates->fetch()) {
181 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
188 * @param int $contactId
190 * @param int $messageTemplateID
194 * @throws \CRM_Core_Exception
196 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
198 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
199 $messageTemplates->id
= $messageTemplateID;
201 $domain = CRM_Core_BAO_Domain
::getDomain();
205 if ($messageTemplates->find(TRUE)) {
206 $body_text = $messageTemplates->msg_text
;
207 $body_html = $messageTemplates->msg_html
;
208 $body_subject = $messageTemplates->msg_subject
;
210 $body_text = CRM_Utils_String
::htmlToText($body_html);
213 $params = [['contact_id', '=', $contactId, 0, 0]];
214 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
217 $contact = reset($contact);
219 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
225 // get tokens to be replaced
226 $tokens = array_merge(CRM_Utils_Token
::getTokens($body_text),
227 CRM_Utils_Token
::getTokens($body_html),
228 CRM_Utils_Token
::getTokens($body_subject));
230 // get replacement text for these tokens
231 $returnProperties = ["preferred_mail_format" => 1];
232 if (isset($tokens['contact'])) {
233 foreach ($tokens['contact'] as $key => $value) {
234 $returnProperties[$value] = 1;
237 list($details) = CRM_Utils_Token
::getTokenDetails([$contactId],
241 'CRM_Core_BAO_MessageTemplate');
242 $contact = reset($details);
246 CRM_Utils_Hook
::tokens($hookTokens);
247 $categories = array_keys($hookTokens);
249 // do replacements in text and html body
250 $type = ['html', 'text'];
251 foreach ($type as $key => $value) {
252 $bodyType = "body_{$value}";
254 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
255 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens, TRUE);
256 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
257 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens, TRUE);
258 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
264 $smarty = CRM_Core_Smarty
::singleton();
269 $
$elem = $smarty->fetch("string:{$$elem}");
272 // do replacements in message subject
273 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
274 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
275 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
276 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
278 $messageSubject = $smarty->fetch("string:{$messageSubject}");
280 // set up the parameters for CRM_Utils_Mail::send
282 'groupName' => 'Scheduled Reminder Sender',
284 'toName' => $contact['display_name'],
286 'subject' => $messageSubject,
288 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
289 $contact['preferred_mail_format'] == 'Both'
291 // render the & entities in text mode, so that the links work
292 $mailParams['text'] = str_replace('&', '&', $text);
294 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
295 $contact['preferred_mail_format'] == 'Both'
298 $mailParams['html'] = $html;
301 $result = CRM_Utils_Mail
::send($mailParams);
308 * Revert a message template to its default subject+text+HTML state.
310 * @param int $id id of the template
312 * @throws \CRM_Core_Exception
314 public static function revert($id) {
315 $diverted = new CRM_Core_BAO_MessageTemplate();
316 $diverted->id
= (int) $id;
319 if ($diverted->N
!= 1) {
320 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
323 $orig = new CRM_Core_BAO_MessageTemplate();
324 $orig->workflow_id
= $diverted->workflow_id
;
325 $orig->is_reserved
= 1;
329 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
332 $diverted->msg_subject
= $orig->msg_subject
;
333 $diverted->msg_text
= $orig->msg_text
;
334 $diverted->msg_html
= $orig->msg_html
;
335 $diverted->pdf_format_id
= is_null($orig->pdf_format_id
) ?
'null' : $orig->pdf_format_id
;
340 * Send an email from the specified template based on an array of params.
342 * @param array $params
343 * A string-keyed array of function params, see function body for details.
346 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
347 * @throws \CRM_Core_Exception
349 public static function sendTemplate($params) {
351 // option group name of the template
353 // option value name of the template
355 // ID of the template
356 'messageTemplateID' => NULL,
357 // contact id if contact tokens are to be replaced
359 // additional template params (other than the ones already set in the template singleton)
363 // the recipient’s name
365 // the recipient’s email - mail is sent only if set
371 // the Reply-To: header
374 'attachments' => NULL,
375 // whether this is a test email (and hence should include the test banner)
377 // filename of optional PDF version to add as attachment (do not include path)
378 'PDFFilename' => NULL,
380 $params = array_merge($defaults, $params);
382 // Core#644 - handle Email ID passed as "From".
383 if (isset($params['from'])) {
384 $params['from'] = CRM_Utils_Mail
::formatFromAddress($params['from']);
387 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
389 if ((!$params['groupName'] ||
390 !$params['valueName']
392 !$params['messageTemplateID']
394 throw new CRM_Core_Exception(ts("Message template's option group and/or option value or ID missing."));
397 if ($params['messageTemplateID']) {
398 // fetch the three elements from the db based on id
399 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
400 FROM civicrm_msg_template mt
401 WHERE mt.id = %1 AND mt.is_default = 1';
402 $sqlParams = [1 => [$params['messageTemplateID'], 'String']];
405 // fetch the three elements from the db based on option_group and option_value names
406 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
407 FROM civicrm_msg_template mt
408 JOIN civicrm_option_value ov ON workflow_id = ov.id
409 JOIN civicrm_option_group og ON ov.option_group_id = og.id
410 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
411 $sqlParams = [1 => [$params['groupName'], 'String'], 2 => [$params['valueName'], 'String']];
413 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
417 if ($params['messageTemplateID']) {
418 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $params['messageTemplateID']]));
420 throw new CRM_Core_Exception(ts('No such message template: option group %1, option value %2.', [
421 1 => $params['groupName'],
422 2 => $params['valueName'],
427 'subject' => $dao->subject
,
428 'text' => $dao->text
,
429 'html' => $dao->html
,
430 'format' => $dao->format
,
431 'groupName' => $params['groupName'],
432 'valueName' => $params['valueName'],
433 'messageTemplateID' => $params['messageTemplateID'],
436 CRM_Utils_Hook
::alterMailContent($mailContent);
438 // add the test banner (if requested)
439 if ($params['isTest']) {
440 $query = "SELECT msg_subject subject, msg_text text, msg_html html
441 FROM civicrm_msg_template mt
442 JOIN civicrm_option_value ov ON workflow_id = ov.id
443 JOIN civicrm_option_group og ON ov.option_group_id = og.id
444 WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
445 $testDao = CRM_Core_DAO
::executeQuery($query);
448 $mailContent['subject'] = $testDao->subject
. $mailContent['subject'];
449 $mailContent['text'] = $testDao->text
. $mailContent['text'];
450 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']);
453 // replace tokens in the three elements (in subject as if it was the text body)
454 $domain = CRM_Core_BAO_Domain
::getDomain();
456 $mailing = new CRM_Mailing_BAO_Mailing();
457 $mailing->subject
= $mailContent['subject'];
458 $mailing->body_text
= $mailContent['text'];
459 $mailing->body_html
= $mailContent['html'];
460 $tokens = $mailing->getTokens();
461 CRM_Utils_Hook
::tokens($hookTokens);
462 $categories = array_keys($hookTokens);
464 $contactID = CRM_Utils_Array
::value('contactId', $params);
467 $contactParams = ['contact_id' => $contactID];
468 $returnProperties = [];
470 if (isset($tokens['subject']['contact'])) {
471 foreach ($tokens['subject']['contact'] as $name) {
472 $returnProperties[$name] = 1;
476 if (isset($tokens['text']['contact'])) {
477 foreach ($tokens['text']['contact'] as $name) {
478 $returnProperties[$name] = 1;
482 if (isset($tokens['html']['contact'])) {
483 foreach ($tokens['html']['contact'] as $name) {
484 $returnProperties[$name] = 1;
488 // @todo CRM-17253 don't resolve contact details if there are no tokens
489 // effectively comment out this next (performance-expensive) line
490 // but unfortunately testing is a bit think on the ground to that needs to
492 list($contact) = CRM_Utils_Token
::getTokenDetails($contactParams,
495 CRM_Utils_Token
::flattenTokens($tokens),
496 // we should consider adding groupName and valueName here
497 'CRM_Core_BAO_MessageTemplate'
499 $contact = $contact[$contactID];
502 $mailContent['subject'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['subject'], TRUE);
503 $mailContent['text'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE);
504 $mailContent['html'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE);
507 $mailContent['subject'] = CRM_Utils_Token
::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['subject'], FALSE, TRUE);
508 $mailContent['text'] = CRM_Utils_Token
::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE);
509 $mailContent['html'] = CRM_Utils_Token
::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE);
511 $contactArray = [$contactID => $contact];
512 CRM_Utils_Hook
::tokenValues($contactArray,
515 CRM_Utils_Token
::flattenTokens($tokens),
516 // we should consider adding groupName and valueName here
517 'CRM_Core_BAO_MessageTemplate'
519 $contact = $contactArray[$contactID];
521 $mailContent['subject'] = CRM_Utils_Token
::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE);
522 $mailContent['text'] = CRM_Utils_Token
::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE);
523 $mailContent['html'] = CRM_Utils_Token
::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE);
526 // strip whitespace from ends and turn into a single line
527 $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}";
529 // parse the three elements with Smarty
530 $smarty = CRM_Core_Smarty
::singleton();
531 foreach ($params['tplParams'] as $name => $value) {
532 $smarty->assign($name, $value);
539 $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
542 // send the template, honouring the target user’s preferences (if any)
545 // create the params array
546 $params['subject'] = $mailContent['subject'];
547 $params['text'] = $mailContent['text'];
548 $params['html'] = $mailContent['html'];
550 if ($params['toEmail']) {
551 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
552 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($contactParams);
554 $prefs = array_pop($contact);
556 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
557 $params['text'] = NULL;
560 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
561 $params['html'] = NULL;
564 $config = CRM_Core_Config
::singleton();
565 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
566 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
567 if (empty($params['attachments'])) {
568 $params['attachments'] = [];
570 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
573 if ($config->doNotAttachPDFReceipt
&&
574 $params['PDFFilename'] &&
577 if (empty($params['attachments'])) {
578 $params['attachments'] = [];
580 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
581 if (isset($params['tplParams']['email_comment'])) {
582 $params['html'] = $params['tplParams']['email_comment'];
583 $params['text'] = strip_tags($params['tplParams']['email_comment']);
587 $sent = CRM_Utils_Mail
::send($params);
590 unlink($pdf_filename);
594 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];