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 = array(1 => array($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();
212 $hookTokens = array();
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 = array(array('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 = array("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(array($contactId),
250 'CRM_Core_BAO_MessageTemplate');
251 $contact = reset($details);
254 $hookTokens = array();
255 CRM_Utils_Hook
::tokens($hookTokens);
256 $categories = array_keys($hookTokens);
258 // do replacements in text and html body
259 $type = array('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);
313 $messageTemplates->free();
319 * Revert a message template to its default subject+text+HTML state.
321 * @param int $id id of the template
323 public static function revert($id) {
324 $diverted = new CRM_Core_BAO_MessageTemplate();
325 $diverted->id
= (int) $id;
328 if ($diverted->N
!= 1) {
329 CRM_Core_Error
::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
332 $orig = new CRM_Core_BAO_MessageTemplate();
333 $orig->workflow_id
= $diverted->workflow_id
;
334 $orig->is_reserved
= 1;
338 CRM_Core_Error
::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
341 $diverted->msg_subject
= $orig->msg_subject
;
342 $diverted->msg_text
= $orig->msg_text
;
343 $diverted->msg_html
= $orig->msg_html
;
344 $diverted->pdf_format_id
= is_null($orig->pdf_format_id
) ?
'null' : $orig->pdf_format_id
;
349 * Send an email from the specified template based on an array of params.
351 * @param array $params
352 * A string-keyed array of function params, see function body for details.
355 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
357 public static function sendTemplate($params) {
359 // option group name of the template
361 // option value name of the template
363 // ID of the template
364 'messageTemplateID' => NULL,
365 // contact id if contact tokens are to be replaced
367 // additional template params (other than the ones already set in the template singleton)
368 'tplParams' => array(),
371 // the recipient’s name
373 // the recipient’s email - mail is sent only if set
379 // the Reply-To: header
382 'attachments' => NULL,
383 // whether this is a test email (and hence should include the test banner)
385 // filename of optional PDF version to add as attachment (do not include path)
386 'PDFFilename' => NULL,
388 $params = array_merge($defaults, $params);
390 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
392 // Core#644 - handle contact ID passed as "From".
393 if (isset($params['from'])) {
394 $params['from'] = CRM_Utils_Mail
::formatFromAddress($params['from']);
397 if ((!$params['groupName'] ||
398 !$params['valueName']
400 !$params['messageTemplateID']
402 CRM_Core_Error
::fatal(ts("Message template's option group and/or option value or ID missing."));
405 if ($params['messageTemplateID']) {
406 // fetch the three elements from the db based on id
407 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
408 FROM civicrm_msg_template mt
409 WHERE mt.id = %1 AND mt.is_default = 1';
410 $sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
413 // fetch the three elements from the db based on option_group and option_value names
414 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
415 FROM civicrm_msg_template mt
416 JOIN civicrm_option_value ov ON workflow_id = ov.id
417 JOIN civicrm_option_group og ON ov.option_group_id = og.id
418 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
419 $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
421 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
425 if ($params['messageTemplateID']) {
426 CRM_Core_Error
::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
429 CRM_Core_Error
::fatal(ts('No such message template: option group %1, option value %2.', array(
430 1 => $params['groupName'],
431 2 => $params['valueName'],
436 $mailContent = array(
437 'subject' => $dao->subject
,
438 'text' => $dao->text
,
439 'html' => $dao->html
,
440 'format' => $dao->format
,
441 'groupName' => $params['groupName'],
442 'valueName' => $params['valueName'],
443 'messageTemplateID' => $params['messageTemplateID'],
447 CRM_Utils_Hook
::alterMailContent($mailContent);
449 // add the test banner (if requested)
450 if ($params['isTest']) {
451 $query = "SELECT msg_subject subject, msg_text text, msg_html html
452 FROM civicrm_msg_template mt
453 JOIN civicrm_option_value ov ON workflow_id = ov.id
454 JOIN civicrm_option_group og ON ov.option_group_id = og.id
455 WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
456 $testDao = CRM_Core_DAO
::executeQuery($query);
459 $mailContent['subject'] = $testDao->subject
. $mailContent['subject'];
460 $mailContent['text'] = $testDao->text
. $mailContent['text'];
461 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']);
465 // replace tokens in the three elements (in subject as if it was the text body)
466 $domain = CRM_Core_BAO_Domain
::getDomain();
467 $hookTokens = array();
468 $mailing = new CRM_Mailing_BAO_Mailing();
469 $mailing->subject
= $mailContent['subject'];
470 $mailing->body_text
= $mailContent['text'];
471 $mailing->body_html
= $mailContent['html'];
472 $tokens = $mailing->getTokens();
473 CRM_Utils_Hook
::tokens($hookTokens);
474 $categories = array_keys($hookTokens);
476 $contactID = CRM_Utils_Array
::value('contactId', $params);
479 $contactParams = array('contact_id' => $contactID);
480 $returnProperties = array();
482 if (isset($tokens['subject']['contact'])) {
483 foreach ($tokens['subject']['contact'] as $name) {
484 $returnProperties[$name] = 1;
488 if (isset($tokens['text']['contact'])) {
489 foreach ($tokens['text']['contact'] as $name) {
490 $returnProperties[$name] = 1;
494 if (isset($tokens['html']['contact'])) {
495 foreach ($tokens['html']['contact'] as $name) {
496 $returnProperties[$name] = 1;
500 // @todo CRM-17253 don't resolve contact details if there are no tokens
501 // effectively comment out this next (performance-expensive) line
502 // but unfortunately testing is a bit think on the ground to that needs to
504 list($contact) = CRM_Utils_Token
::getTokenDetails($contactParams,
507 CRM_Utils_Token
::flattenTokens($tokens),
508 // we should consider adding groupName and valueName here
509 'CRM_Core_BAO_MessageTemplate'
511 $contact = $contact[$contactID];
514 $mailContent['subject'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['subject'], TRUE);
515 $mailContent['text'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE);
516 $mailContent['html'] = CRM_Utils_Token
::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE);
519 $mailContent['subject'] = CRM_Utils_Token
::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['subject'], FALSE, TRUE);
520 $mailContent['text'] = CRM_Utils_Token
::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE);
521 $mailContent['html'] = CRM_Utils_Token
::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE);
523 $contactArray = array($contactID => $contact);
524 CRM_Utils_Hook
::tokenValues($contactArray,
527 CRM_Utils_Token
::flattenTokens($tokens),
528 // we should consider adding groupName and valueName here
529 'CRM_Core_BAO_MessageTemplate'
531 $contact = $contactArray[$contactID];
533 $mailContent['subject'] = CRM_Utils_Token
::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE);
534 $mailContent['text'] = CRM_Utils_Token
::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE);
535 $mailContent['html'] = CRM_Utils_Token
::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE);
538 // strip whitespace from ends and turn into a single line
539 $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}";
541 // parse the three elements with Smarty
542 $smarty = CRM_Core_Smarty
::singleton();
543 foreach ($params['tplParams'] as $name => $value) {
544 $smarty->assign($name, $value);
551 $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
554 // send the template, honouring the target user’s preferences (if any)
557 // create the params array
558 $params['subject'] = $mailContent['subject'];
559 $params['text'] = $mailContent['text'];
560 $params['html'] = $mailContent['html'];
562 if ($params['toEmail']) {
563 $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1));
564 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($contactParams);
566 $prefs = array_pop($contact);
568 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
569 $params['text'] = NULL;
572 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
573 $params['html'] = NULL;
576 $config = CRM_Core_Config
::singleton();
577 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
578 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
579 if (empty($params['attachments'])) {
580 $params['attachments'] = array();
582 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
585 if ($config->doNotAttachPDFReceipt
&&
586 $params['PDFFilename'] &&
589 if (empty($params['attachments'])) {
590 $params['attachments'] = array();
592 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
593 if (isset($params['tplParams']['email_comment'])) {
594 $params['html'] = $params['tplParams']['email_comment'];
595 $params['text'] = strip_tags($params['tplParams']['email_comment']);
599 $sent = CRM_Utils_Mail
::send($params);
602 unlink($pdf_filename);
606 return array($sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']);