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
;
19 use Civi\WorkflowMessage\WorkflowMessage
;
21 require_once 'Mail/mime.php';
24 * Class CRM_Core_BAO_MessageTemplate.
26 class CRM_Core_BAO_MessageTemplate
extends CRM_Core_DAO_MessageTemplate
{
29 * Fetch object based on array of properties.
31 * @param array $params
32 * (reference ) an assoc array of name/value pairs.
33 * @param array $defaults
34 * (reference ) an assoc array to hold the flattened values.
36 * @return CRM_Core_DAO_MessageTemplate
38 public static function retrieve(&$params, &$defaults) {
39 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
40 $messageTemplates->copyValues($params);
41 if ($messageTemplates->find(TRUE)) {
42 CRM_Core_DAO
::storeValues($messageTemplates, $defaults);
43 return $messageTemplates;
49 * Update the is_active flag in the db.
52 * Id of the database record.
53 * @param bool $is_active
54 * Value we want to set the is_active field.
57 * true if we found and updated the object, else false
59 public static function setIsActive($id, $is_active) {
60 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
64 * Add the Message Templates.
66 * @param array $params
67 * Reference array contains the values submitted by the form.
71 * @throws \CiviCRM_API3_Exception
72 * @throws \Civi\API\Exception\UnauthorizedException
74 public static function add(&$params) {
75 // System Workflow Templates have a specific wodkflow_id in them but normal user end message templates don't
76 // If we have an id check to see if we are update, and need to check if original is a system workflow or not.
77 $systemWorkflowPermissionDeniedMessage = 'Editing or creating system workflow messages requires edit system workflow message templates permission or the edit message templates permission';
78 $userWorkflowPermissionDeniedMessage = 'Editing or creating user driven workflow messages requires edit user-driven message templates or the edit message templates permission';
79 if (!empty($params['check_permissions'])) {
80 if (!CRM_Core_Permission
::check('edit message templates')) {
81 if (!empty($params['id'])) {
82 $details = civicrm_api3('MessageTemplate', 'getSingle', ['id' => $params['id']]);
83 if (!empty($details['workflow_id']) ||
!empty($details['workflow_name'])) {
84 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
85 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
88 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
89 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
93 if (!empty($params['workflow_id']) ||
!empty($params['workflow_name'])) {
94 if (!CRM_Core_Permission
::check('edit system workflow message templates')) {
95 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
98 elseif (!CRM_Core_Permission
::check('edit user-driven message templates')) {
99 throw new \Civi\API\Exception\
UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
104 $hook = empty($params['id']) ?
'create' : 'edit';
105 CRM_Utils_Hook
::pre($hook, 'MessageTemplate', CRM_Utils_Array
::value('id', $params), $params);
107 if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
108 $fileParams = $params['file_id'];
109 unset($params['file_id']);
112 // The workflow_id and workflow_name should be sync'd. But what mix of inputs do we have to work with?
113 switch ((empty($params['workflow_id']) ?
'' : 'id') . (empty($params['workflow_name']) ?
'' : 'name')) {
115 $params['workflow_name'] = array_search($params['workflow_id'], self
::getWorkflowNameIdMap());
119 $params['workflow_id'] = self
::getWorkflowNameIdMap()[$params['workflow_name']] ??
NULL;
123 $map = self
::getWorkflowNameIdMap();
124 if ($map[$params['workflow_name']] != $params['workflow_id']) {
125 throw new CRM_Core_Exception("The workflow_id and workflow_name are mismatched. Note: You only need to submit one or the other.");
134 throw new \
RuntimeException("Bad code");
137 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
138 $messageTemplates->copyValues($params);
139 $messageTemplates->save();
141 if (!empty($fileParams)) {
142 $params['file_id'] = $fileParams;
143 CRM_Core_BAO_File
::filePostProcess(
144 $params['file_id']['location'],
146 'civicrm_msg_template',
147 $messageTemplates->id
,
152 $params['file_id']['type']
156 CRM_Utils_Hook
::post($hook, 'MessageTemplate', $messageTemplates->id
, $messageTemplates);
157 return $messageTemplates;
161 * Delete the Message Templates.
163 * @param int $messageTemplatesID
165 * @throws \CRM_Core_Exception
167 public static function del($messageTemplatesID) {
168 // make sure messageTemplatesID is an integer
169 if (!CRM_Utils_Rule
::positiveInteger($messageTemplatesID)) {
170 throw new CRM_Core_Exception(ts('Invalid Message template'));
173 // Set mailing msg template col to NULL
174 $query = "UPDATE civicrm_mailing
175 SET msg_template_id = NULL
176 WHERE msg_template_id = %1";
178 $params = [1 => [$messageTemplatesID, 'Integer']];
179 CRM_Core_DAO
::executeQuery($query, $params);
181 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
182 $messageTemplates->id
= $messageTemplatesID;
183 $messageTemplates->delete();
184 CRM_Core_Session
::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
188 * Get the Message Templates.
197 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
200 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
201 $messageTemplates->is_active
= 1;
202 $messageTemplates->is_sms
= $isSMS;
205 $messageTemplates->workflow_id
= 'NULL';
207 $messageTemplates->find();
208 while ($messageTemplates->fetch()) {
209 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
216 * Revert a message template to its default subject+text+HTML state.
218 * @param int $id id of the template
220 * @throws \CRM_Core_Exception
222 public static function revert($id) {
223 $diverted = new CRM_Core_BAO_MessageTemplate();
224 $diverted->id
= (int) $id;
227 if ($diverted->N
!= 1) {
228 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
231 $orig = new CRM_Core_BAO_MessageTemplate();
232 $orig->workflow_id
= $diverted->workflow_id
;
233 $orig->is_reserved
= 1;
237 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
240 $diverted->msg_subject
= $orig->msg_subject
;
241 $diverted->msg_text
= $orig->msg_text
;
242 $diverted->msg_html
= $orig->msg_html
;
243 $diverted->pdf_format_id
= is_null($orig->pdf_format_id
) ?
'null' : $orig->pdf_format_id
;
248 * Render a message template.
250 * This method is very similar to `sendTemplate()` - accepting most of the same arguments
251 * and emitting similar hooks. However, it specifically precludes the possibility of
252 * sending a message. It only renders.
255 * Mixed render parameters. See sendTemplate() for more details.
257 * Rendered message, consistent of 'subject', 'text', 'html'
258 * Ex: ['subject' => 'Hello Bob', 'text' => 'It\'s been so long since we sent you an automated notification!']
259 * @throws \API_Exception
260 * @throws \CRM_Core_Exception
261 * @see sendTemplate()
263 public static function renderTemplate($params) {
264 $forbidden = ['from', 'toName', 'toEmail', 'cc', 'bcc', 'replyTo'];
265 $intersect = array_intersect($forbidden, array_keys($params));
266 if (!empty($intersect)) {
267 throw new \
CRM_Core_Exception(sprintf("renderTemplate() received forbidden fields (%s)",
268 implode(',', $intersect)));
272 // sendTemplate has had an obscure feature - if you omit `toEmail`, then it merely renders.
273 // At some point, we may want to invert the relation between renderTemplate/sendTemplate, but for now this is a smaller patch.
274 [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']] = static::sendTemplate($params);
279 * Send an email from the specified template based on an array of params.
281 * @param array $params
282 * A string-keyed array of function params, see function body for details.
285 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
286 * @throws \CRM_Core_Exception
287 * @throws \API_Exception
289 public static function sendTemplate($params) {
291 // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template
293 // Symbolic name of the workflow step. Matches the option-value-name of the template.
295 // additional template params (other than the ones already set in the template singleton)
297 // additional token params (passed to the TokenProcessor)
298 // INTERNAL: 'tokenContext' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
299 'tokenContext' => [],
300 // properties to import directly to the model object
301 'modelProps' => NULL,
302 // contact id if contact tokens are to be replaced; alias for tokenContext.contactId
306 // ID of the specific template to load
307 'messageTemplateID' => NULL,
308 // content of the message template
309 // Ex: ['msg_subject' => 'Hello {contact.display_name}', 'msg_html' => '...', 'msg_text' => '...']
310 // INTERNAL: 'messageTemplate' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
311 'messageTemplate' => NULL,
312 // whether this is a test email (and hence should include the test banner)
315 'disableSmarty' => FALSE,
317 $envelopeDefaults = [
320 // the recipient’s name
322 // the recipient’s email - mail is sent only if set
328 // the Reply-To: header
331 'attachments' => NULL,
332 // filename of optional PDF version to add as attachment (do not include path)
333 'PDFFilename' => NULL,
336 // Allow WorkflowMessage to run any filters/mappings/cleanups.
337 $model = $params['model'] ?? WorkflowMessage
::create($params['valueName'] ??
'UNKNOWN');
338 $params = WorkflowMessage
::exportAll(WorkflowMessage
::importAll($model, $params));
339 unset($params['model']);
340 // Subsequent hooks use $params. Retaining the $params['model'] might be nice - but don't do it unless you figure out how to ensure data-consistency (eg $params['tplParams'] <=> $params['model']).
341 // If you want to expose the model via hook, consider interjecting a new Hook::alterWorkflowMessage($model) between `importAll()` and `exportAll()`.
343 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
345 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
346 if (!is_int($params['messageTemplateID']) && !is_null($params['messageTemplateID'])) {
347 CRM_Core_Error
::deprecatedWarning('message template id should be an integer');
348 $params['messageTemplateID'] = (int) $params['messageTemplateID'];
350 $mailContent = self
::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ??
NULL, $params['groupName'] ??
'', $params['messageTemplate'], $params['subject'] ??
NULL);
352 $params['tokenContext'] = array_merge([
353 'smarty' => (bool) !$params['disableSmarty'],
354 'contactId' => $params['contactId'],
355 ], $params['tokenContext']);
356 $rendered = CRM_Core_TokenSmarty
::render(CRM_Utils_Array
::subset($mailContent, ['text', 'html', 'subject']), $params['tokenContext'], $params['tplParams']);
357 if (isset($rendered['subject'])) {
358 $rendered['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $rendered['subject']));
360 $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL];
361 $mailContent = array_merge($nullSet, $mailContent, $rendered);
363 // send the template, honouring the target user’s preferences (if any)
366 // create the params array
367 $params['subject'] = $mailContent['subject'];
368 $params['text'] = $mailContent['text'];
369 $params['html'] = $mailContent['html'];
371 if ($params['toEmail']) {
372 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
373 [$contact] = CRM_Contact_BAO_Query
::apiQuery($contactParams);
375 $prefs = array_pop($contact);
377 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
378 $params['text'] = NULL;
381 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
382 $params['html'] = NULL;
385 $config = CRM_Core_Config
::singleton();
386 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
387 // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId.
388 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
389 if (empty($params['attachments'])) {
390 $params['attachments'] = [];
392 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
395 if ($config->doNotAttachPDFReceipt
&&
396 $params['PDFFilename'] &&
399 if (empty($params['attachments'])) {
400 $params['attachments'] = [];
402 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
403 if (isset($params['tplParams']['email_comment'])) {
404 $params['html'] = $params['tplParams']['email_comment'];
405 $params['text'] = strip_tags($params['tplParams']['email_comment']);
409 $sent = CRM_Utils_Mail
::send($params);
412 unlink($pdf_filename);
416 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
420 * Create a map between workflow_name and workflow_id.
423 * Array(string $workflowName => int $workflowId)
425 protected static function getWorkflowNameIdMap() {
426 // There's probably some more clever way to do this, but this seems simple.
427 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', [
428 1 => ['msg_tpl_workflow_%', 'String'],
429 ])->fetchMap('name', 'id');
433 * Load the specified template.
435 * @param string $workflowName
436 * @param bool $isTest
437 * @param int|null $messageTemplateID
438 * @param string $groupName
439 * @param array|null $messageTemplateOverride
440 * Optionally, record with msg_subject, msg_text, msg_html.
441 * If omitted, the record will be loaded from workflowName/messageTemplateID.
442 * @param string|null $subjectOverride
443 * This option is the older, wonkier version of $messageTemplate['msg_subject']...
446 * @throws \API_Exception
447 * @throws \CRM_Core_Exception
449 protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL, ?
array $messageTemplateOverride = NULL, ?
string $subjectOverride = NULL): array {
450 $base = ['msg_subject' => NULL, 'msg_text' => NULL, 'msg_html' => NULL, 'pdf_format_id' => NULL];
451 if (!$workflowName && !$messageTemplateID) {
452 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
455 $apiCall = MessageTemplate
::get(FALSE)
456 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
457 ->addWhere('is_default', '=', 1);
459 if ($messageTemplateID) {
460 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
463 $apiCall->addWhere('workflow_name', '=', $workflowName);
465 $messageTemplate = array_merge($base, $apiCall->execute()->first() ?
: [], $messageTemplateOverride ?
: []);
466 if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) {
467 if ($messageTemplateID) {
468 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
470 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
474 'subject' => $messageTemplate['msg_subject'],
475 'text' => $messageTemplate['msg_text'],
476 'html' => $messageTemplate['msg_html'],
477 'format' => $messageTemplate['pdf_format_id'],
478 // Workflow name is the field in the message templates table that denotes the
479 // workflow the template is used for. This is intended to eventually
480 // replace the non-standard option value/group implementation - see
481 // https://github.com/civicrm/civicrm-core/pull/17227 and the longer
482 // discussion on https://github.com/civicrm/civicrm-core/pull/17180
483 'workflow_name' => $workflowName,
484 // Note messageTemplateID is the id but when present we also know it was specifically requested.
485 'messageTemplateID' => $messageTemplateID,
486 // Group name & valueName are deprecated parameters. At some point it will not be passed out.
487 // https://github.com/civicrm/civicrm-core/pull/17180
488 'groupName' => $groupName,
489 'valueName' => $workflowName,
492 CRM_Utils_Hook
::alterMailContent($mailContent);
494 // add the test banner (if requested)
496 $testText = MessageTemplate
::get(FALSE)
497 ->setSelect(['msg_subject', 'msg_text', 'msg_html'])
498 ->addWhere('workflow_name', '=', 'test_preview')
499 ->addWhere('is_default', '=', TRUE)
500 ->execute()->first();
502 $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject'];
503 $mailContent['text'] = $testText['msg_text'] . $mailContent['text'];
504 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']);
507 if (!empty($subjectOverride)) {
508 CRM_Core_Error
::deprecatedWarning('CRM_Core_BAO_MessageTemplate: $params[subject] is deprecated. Use $params[messageTemplate][msg_subject] instead.');
509 $mailContent['subject'] = $subjectOverride;