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
implements \Civi\Test\HookInterface
{
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 $empty = function ($key) use (&$params) {
114 return empty($params[$key]) ||
$params[$key] === 'null';
116 switch (($empty('workflow_id') ?
'' : 'id') . ($empty('workflow_name') ?
'' : 'name')) {
118 $params['workflow_name'] = array_search($params['workflow_id'], self
::getWorkflowNameIdMap());
122 $params['workflow_id'] = self
::getWorkflowNameIdMap()[$params['workflow_name']] ??
NULL;
126 $map = self
::getWorkflowNameIdMap();
127 if ($map[$params['workflow_name']] != $params['workflow_id']) {
128 throw new CRM_Core_Exception("The workflow_id and workflow_name are mismatched. Note: You only need to submit one or the other.");
137 throw new \
RuntimeException("Bad code");
140 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
141 $messageTemplates->copyValues($params);
142 $messageTemplates->save();
144 if (!empty($fileParams)) {
145 $params['file_id'] = $fileParams;
146 CRM_Core_BAO_File
::filePostProcess(
147 $params['file_id']['location'],
149 'civicrm_msg_template',
150 $messageTemplates->id
,
155 $params['file_id']['type']
159 CRM_Utils_Hook
::post($hook, 'MessageTemplate', $messageTemplates->id
, $messageTemplates);
160 return $messageTemplates;
164 * Delete the Message Templates.
166 * @param int $messageTemplatesID
168 * @throws \CRM_Core_Exception
170 public static function del($messageTemplatesID) {
171 // make sure messageTemplatesID is an integer
172 if (!CRM_Utils_Rule
::positiveInteger($messageTemplatesID)) {
173 throw new CRM_Core_Exception(ts('Invalid Message template'));
176 static::deleteRecord(['id' => $messageTemplatesID]);
177 // Yikes - bad idea setting status messages in BAO CRUD functions. Don't do this.
178 CRM_Core_Session
::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
182 * Callback for hook_civicrm_pre().
183 * @param \Civi\Core\Event\PreEvent $event
184 * @throws CRM_Core_Exception
186 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent
$event) {
187 if ($event->action
=== 'delete') {
188 // Set mailing msg template col to NULL
189 $query = "UPDATE civicrm_mailing
190 SET msg_template_id = NULL
191 WHERE msg_template_id = %1";
192 $params = [1 => [$event->id
, 'Integer']];
193 CRM_Core_DAO
::executeQuery($query, $params);
198 * Get the Message Templates.
207 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
210 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
211 $messageTemplates->is_active
= 1;
212 $messageTemplates->is_sms
= $isSMS;
215 $messageTemplates->workflow_id
= 'NULL';
217 $messageTemplates->find();
218 while ($messageTemplates->fetch()) {
219 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
226 * Revert a message template to its default subject+text+HTML state.
228 * @param int $id id of the template
230 * @throws \CRM_Core_Exception
232 public static function revert($id) {
233 $diverted = new CRM_Core_BAO_MessageTemplate();
234 $diverted->id
= (int) $id;
237 if ($diverted->N
!= 1) {
238 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
241 $orig = new CRM_Core_BAO_MessageTemplate();
242 $orig->workflow_name
= $diverted->workflow_name
;
243 $orig->is_reserved
= 1;
247 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
250 $diverted->msg_subject
= $orig->msg_subject
;
251 $diverted->msg_text
= $orig->msg_text
;
252 $diverted->msg_html
= $orig->msg_html
;
253 $diverted->pdf_format_id
= is_null($orig->pdf_format_id
) ?
'null' : $orig->pdf_format_id
;
258 * Render a message template.
260 * This method is very similar to `sendTemplate()` - accepting most of the same arguments
261 * and emitting similar hooks. However, it specifically precludes the possibility of
262 * sending a message. It only renders.
265 * Mixed render parameters. See sendTemplate() for more details.
267 * Rendered message, consistent of 'subject', 'text', 'html'
268 * Ex: ['subject' => 'Hello Bob', 'text' => 'It\'s been so long since we sent you an automated notification!']
269 * @throws \API_Exception
270 * @throws \CRM_Core_Exception
271 * @see sendTemplate()
273 public static function renderTemplate($params) {
274 [$mailContent, $params] = self
::renderTemplateRaw($params);
275 return CRM_Utils_Array
::subset($mailContent, ['subject', 'text', 'html']);
279 * Render a message template.
281 * @param array $params
282 * Mixed render parameters. See sendTemplate() for more details.
284 * Tuple of [$mailContent, $updatedParams].
285 * @throws \API_Exception
286 * @throws \CRM_Core_Exception
287 * @see sendTemplate()
289 protected static function renderTemplateRaw($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 // Some params have been deprecated/renamed. Synchronize old<=>new params. We periodically resync after exchanging data with other parties.
337 $sync = function () use (&$params, $modelDefaults, $viewDefaults) {
338 CRM_Utils_Array
::pathSync($params, ['workflow'], ['valueName']);
339 CRM_Utils_Array
::pathSync($params, ['tokenContext', 'contactId'], ['contactId']);
340 CRM_Utils_Array
::pathSync($params, ['tokenContext', 'smarty'], ['disableSmarty'], function ($v, bool $isCanon) {
344 // Core#644 - handle Email ID passed as "From".
345 if (isset($params['from'])) {
346 $params['from'] = \CRM_Utils_Mail
::formatFromAddress($params['from']);
351 // Allow WorkflowMessage to run any filters/mappings/cleanups.
352 $model = $params['model'] ?? WorkflowMessage
::create($params['workflow'] ??
'UNKNOWN');
353 $params = WorkflowMessage
::exportAll(WorkflowMessage
::importAll($model, $params));
354 unset($params['model']);
355 // 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']).
356 // If you want to expose the model via hook, consider interjecting a new Hook::alterWorkflowMessage($model) between `importAll()` and `exportAll()`.
359 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
361 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
362 $mailContent = self
::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ??
NULL, $params['groupName'] ??
'', $params['messageTemplate'], $params['subject'] ??
NULL);
365 $rendered = CRM_Core_TokenSmarty
::render(CRM_Utils_Array
::subset($mailContent, ['text', 'html', 'subject']), $params['tokenContext'], $params['tplParams']);
366 if (isset($rendered['subject'])) {
367 $rendered['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $rendered['subject']));
369 $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL];
370 $mailContent = array_merge($nullSet, $mailContent, $rendered);
371 return [$mailContent, $params];
375 * Send an email from the specified template based on an array of params.
377 * @param array $params
378 * A string-keyed array of function params, see function body for details.
381 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
382 * @throws \CRM_Core_Exception
383 * @throws \API_Exception
385 public static function sendTemplate(array $params): array {
386 // Handle isEmailPdf here as the unit test on that function deems it 'non-conforming'.
387 $isAttachPDF = !empty($params['isEmailPdf']);
388 unset($params['isEmailPdf']);
389 [$mailContent, $params] = self
::renderTemplateRaw($params);
391 // create the params array
392 $params['subject'] = $mailContent['subject'];
393 $params['text'] = $mailContent['text'];
394 $params['html'] = $mailContent['html'];
396 // send the template, honouring the target user’s preferences (if any)
398 if (!empty($params['toEmail'])) {
400 $config = CRM_Core_Config
::singleton();
402 // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId.
403 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
404 if (empty($params['attachments'])) {
405 $params['attachments'] = [];
407 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
410 if ($config->doNotAttachPDFReceipt
&&
411 $params['PDFFilename'] &&
414 if (empty($params['attachments'])) {
415 $params['attachments'] = [];
417 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
418 if (isset($params['tplParams']['email_comment'])) {
419 $params['html'] = $params['tplParams']['email_comment'];
420 $params['text'] = strip_tags($params['tplParams']['email_comment']);
424 $sent = CRM_Utils_Mail
::send($params);
427 unlink($pdf_filename);
431 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
435 * Create a map between workflow_name and workflow_id.
438 * Array(string $workflowName => int $workflowId)
440 protected static function getWorkflowNameIdMap() {
441 // There's probably some more clever way to do this, but this seems simple.
442 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', [
443 1 => ['msg_tpl_workflow_%', 'String'],
444 ])->fetchMap('name', 'id');
448 * Load the specified template.
450 * @param string $workflowName
451 * @param bool $isTest
452 * @param int|null $messageTemplateID
453 * @param string $groupName
454 * @param array|null $messageTemplateOverride
455 * Optionally, record with msg_subject, msg_text, msg_html.
456 * If omitted, the record will be loaded from workflowName/messageTemplateID.
457 * @param string|null $subjectOverride
458 * This option is the older, wonkier version of $messageTemplate['msg_subject']...
461 * @throws \API_Exception
462 * @throws \CRM_Core_Exception
464 protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL, ?
array $messageTemplateOverride = NULL, ?
string $subjectOverride = NULL): array {
465 $base = ['msg_subject' => NULL, 'msg_text' => NULL, 'msg_html' => NULL, 'pdf_format_id' => NULL];
466 if (!$workflowName && !$messageTemplateID) {
467 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
470 $apiCall = MessageTemplate
::get(FALSE)
471 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
472 ->addWhere('is_default', '=', 1);
474 if ($messageTemplateID) {
475 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
478 $apiCall->addWhere('workflow_name', '=', $workflowName);
480 $messageTemplate = array_merge($base, $apiCall->execute()->first() ?
: [], $messageTemplateOverride ?
: []);
481 if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) {
482 if ($messageTemplateID) {
483 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
485 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
489 'subject' => $messageTemplate['msg_subject'],
490 'text' => $messageTemplate['msg_text'],
491 'html' => $messageTemplate['msg_html'],
492 'format' => $messageTemplate['pdf_format_id'],
493 // Workflow name is the field in the message templates table that denotes the
494 // workflow the template is used for. This is intended to eventually
495 // replace the non-standard option value/group implementation - see
496 // https://github.com/civicrm/civicrm-core/pull/17227 and the longer
497 // discussion on https://github.com/civicrm/civicrm-core/pull/17180
498 'workflow_name' => $workflowName,
499 // Note messageTemplateID is the id but when present we also know it was specifically requested.
500 'messageTemplateID' => $messageTemplateID,
501 // Group name & valueName are deprecated parameters. At some point it will not be passed out.
502 // https://github.com/civicrm/civicrm-core/pull/17180
503 'groupName' => $groupName,
504 'valueName' => $workflowName,
507 CRM_Utils_Hook
::alterMailContent($mailContent);
509 // add the test banner (if requested)
511 $testText = MessageTemplate
::get(FALSE)
512 ->setSelect(['msg_subject', 'msg_text', 'msg_html'])
513 ->addWhere('workflow_name', '=', 'test_preview')
514 ->addWhere('is_default', '=', TRUE)
515 ->execute()->first();
517 $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject'];
518 $mailContent['text'] = $testText['msg_text'] . $mailContent['text'];
519 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']);
522 if (!empty($subjectOverride)) {
523 CRM_Core_Error
::deprecatedWarning('CRM_Core_BAO_MessageTemplate: $params[subject] is deprecated. Use $params[messageTemplate][msg_subject] instead.');
524 $mailContent['subject'] = $subjectOverride;