3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
34 require_once 'Mail/mime.php';
37 * Class CRM_Core_BAO_MessageTemplate.
39 class CRM_Core_BAO_MessageTemplate
extends CRM_Core_DAO_MessageTemplate
{
42 * Fetch object based on array of properties.
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
46 * @param array $defaults
47 * (reference ) an assoc array to hold the flattened values.
49 * @return CRM_Core_BAO_MessageTemplate
51 public static function retrieve(&$params, &$defaults) {
52 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
53 $messageTemplates->copyValues($params);
54 if ($messageTemplates->find(TRUE)) {
55 CRM_Core_DAO
::storeValues($messageTemplates, $defaults);
56 return $messageTemplates;
62 * Update the is_active flag in the db.
65 * Id of the database record.
66 * @param bool $is_active
67 * Value we want to set the is_active field.
70 * true if we found and updated the object, else false
72 public static function setIsActive($id, $is_active) {
73 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
77 * Add the Message Templates.
79 * @param array $params
80 * Reference array contains the values submitted by the form.
85 public static function add(&$params) {
86 // System Workflow Templates have a specific wodkflow_id in them but normal user end message templates don't
87 // If we have an id check to see if we are update, and need to check if original is a system workflow or not.
88 $systemWorkflowPermissionDeniedMessage = 'Editing or creating system workflow messages requires edit system workflow message templates permission or the edit message templates permission';
89 $userWorkflowPermissionDeniedMessage = 'Editing or creating user driven workflow messages requires edit user-driven message templates or the edit message templates permission';
90 if (!empty($params['check_permissions'])) {
91 if (!CRM_Core_Permission
::check('edit message templates')) {
92 if (!empty($params['id'])) {
93 $details = civicrm_api3('MessageTemplate', 'getSingle', ['id' => $params['id']]);
94 if (!empty($details['workflow_id'])) {
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]));
104 if (!empty($params['workflow_id']) && !CRM_Core_Permission
::check('edit system workflow message templates')) {
105 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
107 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
108 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
113 $hook = empty($params['id']) ?
'create' : 'edit';
114 CRM_Utils_Hook
::pre($hook, 'MessageTemplate', CRM_Utils_Array
::value('id', $params), $params);
116 if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
117 $fileParams = $params['file_id'];
118 unset($params['file_id']);
121 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
122 $messageTemplates->copyValues($params);
123 $messageTemplates->save();
125 if (!empty($fileParams)) {
126 $params['file_id'] = $fileParams;
127 CRM_Core_BAO_File
::filePostProcess(
128 $params['file_id']['location'],
130 'civicrm_msg_template',
131 $messageTemplates->id
,
136 $params['file_id']['type']
140 CRM_Utils_Hook
::post($hook, 'MessageTemplate', $messageTemplates->id
, $messageTemplates);
141 return $messageTemplates;
145 * Delete the Message Templates.
147 * @param int $messageTemplatesID
149 public static function del($messageTemplatesID) {
150 // make sure messageTemplatesID is an integer
151 if (!CRM_Utils_Rule
::positiveInteger($messageTemplatesID)) {
152 CRM_Core_Error
::fatal(ts('Invalid Message template'));
155 // Set mailing msg template col to NULL
156 $query = "UPDATE civicrm_mailing
157 SET msg_template_id = NULL
158 WHERE msg_template_id = %1";
160 $params = [1 => [$messageTemplatesID, 'Integer']];
161 CRM_Core_DAO
::executeQuery($query, $params);
163 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
164 $messageTemplates->id
= $messageTemplatesID;
165 $messageTemplates->delete();
166 CRM_Core_Session
::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
170 * Get the Message Templates.
179 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
182 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
183 $messageTemplates->is_active
= 1;
184 $messageTemplates->is_sms
= $isSMS;
187 $messageTemplates->workflow_id
= 'NULL';
189 $messageTemplates->find();
190 while ($messageTemplates->fetch()) {
191 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
198 * @param int $contactId
200 * @param int $messageTemplateID
205 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
207 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
208 $messageTemplates->id
= $messageTemplateID;
210 $domain = CRM_Core_BAO_Domain
::getDomain();
214 if ($messageTemplates->find(TRUE)) {
215 $body_text = $messageTemplates->msg_text
;
216 $body_html = $messageTemplates->msg_html
;
217 $body_subject = $messageTemplates->msg_subject
;
219 $body_text = CRM_Utils_String
::htmlToText($body_html);
222 $params = [['contact_id', '=', $contactId, 0, 0]];
223 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
226 $contact = reset($contact);
228 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
234 // get tokens to be replaced
235 $tokens = array_merge(CRM_Utils_Token
::getTokens($body_text),
236 CRM_Utils_Token
::getTokens($body_html),
237 CRM_Utils_Token
::getTokens($body_subject));
239 // get replacement text for these tokens
240 $returnProperties = ["preferred_mail_format" => 1];
241 if (isset($tokens['contact'])) {
242 foreach ($tokens['contact'] as $key => $value) {
243 $returnProperties[$value] = 1;
246 list($details) = CRM_Utils_Token
::getTokenDetails([$contactId],
250 'CRM_Core_BAO_MessageTemplate');
251 $contact = reset($details);
255 CRM_Utils_Hook
::tokens($hookTokens);
256 $categories = array_keys($hookTokens);
258 // do replacements in text and html body
259 $type = ['html', 'text'];
260 foreach ($type as $key => $value) {
261 $bodyType = "body_{$value}";
263 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
264 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens, TRUE);
265 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
266 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens, TRUE);
267 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
273 $smarty = CRM_Core_Smarty
::singleton();
278 $
$elem = $smarty->fetch("string:{$$elem}");
281 // do replacements in message subject
282 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
283 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
284 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
285 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
287 $messageSubject = $smarty->fetch("string:{$messageSubject}");
289 // set up the parameters for CRM_Utils_Mail::send
291 'groupName' => 'Scheduled Reminder Sender',
293 'toName' => $contact['display_name'],
295 'subject' => $messageSubject,
297 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
298 $contact['preferred_mail_format'] == 'Both'
300 // render the & entities in text mode, so that the links work
301 $mailParams['text'] = str_replace('&', '&', $text);
303 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
304 $contact['preferred_mail_format'] == 'Both'
307 $mailParams['html'] = $html;
310 $result = CRM_Utils_Mail
::send($mailParams);
317 * Revert a message template to its default subject+text+HTML state.
319 * @param int $id id of the template
321 public static function revert($id) {
322 $diverted = new CRM_Core_BAO_MessageTemplate();
323 $diverted->id
= (int) $id;
326 if ($diverted->N
!= 1) {
327 CRM_Core_Error
::fatal(ts('Did not find a message template with id of %1.', [1 => $id]));
330 $orig = new CRM_Core_BAO_MessageTemplate();
331 $orig->workflow_id
= $diverted->workflow_id
;
332 $orig->is_reserved
= 1;
336 CRM_Core_Error
::fatal(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
339 $diverted->msg_subject
= $orig->msg_subject
;
340 $diverted->msg_text
= $orig->msg_text
;
341 $diverted->msg_html
= $orig->msg_html
;
342 $diverted->pdf_format_id
= is_null($orig->pdf_format_id
) ?
'null' : $orig->pdf_format_id
;
347 * Send an email from the specified template based on an array of params.
349 * @param array $params
350 * A string-keyed array of function params, see function body for details.
353 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
355 public static function sendTemplate($params) {
357 // option group name of the template
359 // option value name of the template
361 // ID of the template
362 'messageTemplateID' => NULL,
363 // contact id if contact tokens are to be replaced
365 // additional template params (other than the ones already set in the template singleton)
369 // the recipient’s name
371 // the recipient’s email - mail is sent only if set
377 // the Reply-To: header
380 'attachments' => NULL,
381 // whether this is a test email (and hence should include the test banner)
383 // filename of optional PDF version to add as attachment (do not include path)
384 'PDFFilename' => NULL,
386 $params = array_merge($defaults, $params);
388 // Core#644 - handle Email ID passed as "From".
389 if (isset($params['from'])) {
390 $params['from'] = CRM_Utils_Mail
::formatFromAddress($params['from']);
393 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
395 if ((!$params['groupName'] ||
396 !$params['valueName']
398 !$params['messageTemplateID']
400 CRM_Core_Error
::fatal(ts("Message template's option group and/or option value or ID missing."));
403 if ($params['messageTemplateID']) {
404 // fetch the three elements from the db based on id
405 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
406 FROM civicrm_msg_template mt
407 WHERE mt.id = %1 AND mt.is_default = 1';
408 $sqlParams = [1 => [$params['messageTemplateID'], 'String']];
411 // fetch the three elements from the db based on option_group and option_value names
412 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
413 FROM civicrm_msg_template mt
414 JOIN civicrm_option_value ov ON workflow_id = ov.id
415 JOIN civicrm_option_group og ON ov.option_group_id = og.id
416 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
417 $sqlParams = [1 => [$params['groupName'], 'String'], 2 => [$params['valueName'], 'String']];
419 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
423 if ($params['messageTemplateID']) {
424 CRM_Core_Error
::fatal(ts('No such message template: id=%1.', [1 => $params['messageTemplateID']]));
427 CRM_Core_Error
::fatal(ts('No such message template: option group %1, option value %2.', [
428 1 => $params['groupName'],
429 2 => $params['valueName'],
435 'subject' => $dao->subject
,
436 'text' => $dao->text
,
437 'html' => $dao->html
,
438 'format' => $dao->format
,
439 'groupName' => $params['groupName'],
440 'valueName' => $params['valueName'],
441 'messageTemplateID' => $params['messageTemplateID'],
444 CRM_Utils_Hook
::alterMailContent($mailContent);
446 // add the test banner (if requested)
447 if ($params['isTest']) {
448 $query = "SELECT msg_subject subject, msg_text text, msg_html html
449 FROM civicrm_msg_template mt
450 JOIN civicrm_option_value ov ON workflow_id = ov.id
451 JOIN civicrm_option_group og ON ov.option_group_id = og.id
452 WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
453 $testDao = CRM_Core_DAO
::executeQuery($query);
456 $mailContent['subject'] = $testDao->subject
. $mailContent['subject'];
457 $mailContent['text'] = $testDao->text
. $mailContent['text'];
458 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']);
461 // replace tokens in the three elements (in subject as if it was the text body)
462 $domain = CRM_Core_BAO_Domain
::getDomain();
464 $mailing = new CRM_Mailing_BAO_Mailing();
465 $mailing->subject
= $mailContent['subject'];
466 $mailing->body_text
= $mailContent['text'];
467 $mailing->body_html
= $mailContent['html'];
468 $tokens = $mailing->getTokens();
469 CRM_Utils_Hook
::tokens($hookTokens);
470 $categories = array_keys($hookTokens);
472 $contactID = CRM_Utils_Array
::value('contactId', $params);
475 $contactParams = ['contact_id' => $contactID];
476 $returnProperties = [];
478 if (isset($tokens['subject']['contact'])) {
479 foreach ($tokens['subject']['contact'] as $name) {
480 $returnProperties[$name] = 1;
484 if (isset($tokens['text']['contact'])) {
485 foreach ($tokens['text']['contact'] as $name) {
486 $returnProperties[$name] = 1;
490 if (isset($tokens['html']['contact'])) {
491 foreach ($tokens['html']['contact'] as $name) {
492 $returnProperties[$name] = 1;
496 // @todo CRM-17253 don't resolve contact details if there are no tokens
497 // effectively comment out this next (performance-expensive) line
498 // but unfortunately testing is a bit think on the ground to that needs to
500 list($contact) = CRM_Utils_Token
::getTokenDetails($contactParams,
503 CRM_Utils_Token
::flattenTokens($tokens),
504 // we should consider adding groupName and valueName here
505 'CRM_Core_BAO_MessageTemplate'
507 $contact = $contact[$contactID];
510 $mailContent['subject'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['subject'], TRUE);
511 $mailContent['text'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE);
512 $mailContent['html'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE);
515 $mailContent['subject'] = CRM_Utils_Token
::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['subject'], FALSE, TRUE);
516 $mailContent['text'] = CRM_Utils_Token
::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE);
517 $mailContent['html'] = CRM_Utils_Token
::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE);
519 $contactArray = [$contactID => $contact];
520 CRM_Utils_Hook
::tokenValues($contactArray,
523 CRM_Utils_Token
::flattenTokens($tokens),
524 // we should consider adding groupName and valueName here
525 'CRM_Core_BAO_MessageTemplate'
527 $contact = $contactArray[$contactID];
529 $mailContent['subject'] = CRM_Utils_Token
::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE);
530 $mailContent['text'] = CRM_Utils_Token
::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE);
531 $mailContent['html'] = CRM_Utils_Token
::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE);
534 // strip whitespace from ends and turn into a single line
535 $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}";
537 // parse the three elements with Smarty
538 $smarty = CRM_Core_Smarty
::singleton();
539 foreach ($params['tplParams'] as $name => $value) {
540 $smarty->assign($name, $value);
547 $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
550 // send the template, honouring the target user’s preferences (if any)
553 // create the params array
554 $params['subject'] = $mailContent['subject'];
555 $params['text'] = $mailContent['text'];
556 $params['html'] = $mailContent['html'];
558 if ($params['toEmail']) {
559 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
560 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($contactParams);
562 $prefs = array_pop($contact);
564 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
565 $params['text'] = NULL;
568 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
569 $params['html'] = NULL;
572 $config = CRM_Core_Config
::singleton();
573 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
574 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
575 if (empty($params['attachments'])) {
576 $params['attachments'] = [];
578 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
581 if ($config->doNotAttachPDFReceipt
&&
582 $params['PDFFilename'] &&
585 if (empty($params['attachments'])) {
586 $params['attachments'] = [];
588 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
589 if (isset($params['tplParams']['email_comment'])) {
590 $params['html'] = $params['tplParams']['email_comment'];
591 $params['text'] = strip_tags($params['tplParams']['email_comment']);
595 $sent = CRM_Utils_Mail
::send($params);
598 unlink($pdf_filename);
602 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];