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\Core\HookInterface
{
29 * Retrieve DB object and copy to defaults array.
31 * @param array $params
32 * Array of criteria values.
33 * @param array $defaults
34 * Array to be populated with found values.
37 * The DAO object, if found.
41 public static function retrieve($params, &$defaults) {
42 return self
::commonRetrieve(self
::class, $params, $defaults);
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']) ||
!empty($details['workflow_name'])) {
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']) ||
!empty($params['workflow_name'])) {
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 // The workflow_id and workflow_name should be sync'd. But what mix of inputs do we have to work with?
110 $empty = function ($key) use (&$params) {
111 return empty($params[$key]) ||
$params[$key] === 'null';
113 switch (($empty('workflow_id') ?
'' : 'id') . ($empty('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 static::deleteRecord(['id' => $messageTemplatesID]);
174 // Yikes - bad idea setting status messages in BAO CRUD functions. Don't do this.
175 CRM_Core_Session
::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
179 * Callback for hook_civicrm_pre().
180 * @param \Civi\Core\Event\PreEvent $event
181 * @throws CRM_Core_Exception
183 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent
$event) {
184 if ($event->action
=== 'delete') {
185 // Set mailing msg template col to NULL
186 $query = "UPDATE civicrm_mailing
187 SET msg_template_id = NULL
188 WHERE msg_template_id = %1";
189 $params = [1 => [$event->id
, 'Integer']];
190 CRM_Core_DAO
::executeQuery($query, $params);
195 * Get the Message Templates.
204 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
207 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
208 $messageTemplates->is_active
= 1;
209 $messageTemplates->is_sms
= $isSMS;
212 $messageTemplates->workflow_id
= 'NULL';
214 $messageTemplates->find();
215 while ($messageTemplates->fetch()) {
216 $msgTpls[$messageTemplates->id
] = $messageTemplates->msg_title
;
223 * Revert a message template to its default subject+text+HTML state.
225 * @param int $id id of the template
227 * @throws \CRM_Core_Exception
229 public static function revert($id) {
230 $diverted = new CRM_Core_BAO_MessageTemplate();
231 $diverted->id
= (int) $id;
234 if ($diverted->N
!= 1) {
235 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
238 $orig = new CRM_Core_BAO_MessageTemplate();
239 $orig->workflow_name
= $diverted->workflow_name
;
240 $orig->is_reserved
= 1;
244 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
247 $diverted->msg_subject
= $orig->msg_subject
;
248 $diverted->msg_text
= $orig->msg_text
;
249 $diverted->msg_html
= $orig->msg_html
;
250 $diverted->pdf_format_id
= is_null($orig->pdf_format_id
) ?
'null' : $orig->pdf_format_id
;
255 * Render a message template.
257 * This method is very similar to `sendTemplate()` - accepting most of the same arguments
258 * and emitting similar hooks. However, it specifically precludes the possibility of
259 * sending a message. It only renders.
262 * Mixed render parameters. See sendTemplate() for more details.
264 * Rendered message, consistent of 'subject', 'text', 'html'
265 * Ex: ['subject' => 'Hello Bob', 'text' => 'It\'s been so long since we sent you an automated notification!']
266 * @throws \API_Exception
267 * @throws \CRM_Core_Exception
268 * @see sendTemplate()
270 public static function renderTemplate($params) {
271 [$mailContent, $params] = self
::renderTemplateRaw($params);
272 return CRM_Utils_Array
::subset($mailContent, ['subject', 'text', 'html']);
276 * Render a message template.
278 * @param array $params
279 * Mixed render parameters. See sendTemplate() for more details.
281 * Tuple of [$mailContent, $updatedParams].
282 * @throws \API_Exception
283 * @throws \CRM_Core_Exception
284 * @see sendTemplate()
286 protected static function renderTemplateRaw($params) {
288 // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template
290 // Symbolic name of the workflow step. Matches the option-value-name of the template.
292 // additional template params (other than the ones already set in the template singleton)
294 // additional token params (passed to the TokenProcessor)
295 // INTERNAL: 'tokenContext' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
296 'tokenContext' => [],
297 // properties to import directly to the model object
298 'modelProps' => NULL,
299 // contact id if contact tokens are to be replaced; alias for tokenContext.contactId
303 // ID of the specific template to load
304 'messageTemplateID' => NULL,
305 // content of the message template
306 // Ex: ['msg_subject' => 'Hello {contact.display_name}', 'msg_html' => '...', 'msg_text' => '...']
307 // INTERNAL: 'messageTemplate' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
308 'messageTemplate' => NULL,
309 // whether this is a test email (and hence should include the test banner)
312 'disableSmarty' => FALSE,
314 $envelopeDefaults = [
317 // the recipient’s name
319 // the recipient’s email - mail is sent only if set
325 // the Reply-To: header
328 'attachments' => NULL,
329 // filename of optional PDF version to add as attachment (do not include path)
330 'PDFFilename' => NULL,
333 // Some params have been deprecated/renamed. Synchronize old<=>new params. We periodically resync after exchanging data with other parties.
334 $sync = function () use (&$params, $modelDefaults, $viewDefaults) {
335 CRM_Utils_Array
::pathSync($params, ['workflow'], ['valueName']);
336 CRM_Utils_Array
::pathSync($params, ['tokenContext', 'contactId'], ['contactId']);
337 CRM_Utils_Array
::pathSync($params, ['tokenContext', 'smarty'], ['disableSmarty'], function ($v, bool $isCanon) {
341 // Core#644 - handle Email ID passed as "From".
342 if (isset($params['from'])) {
343 $params['from'] = \CRM_Utils_Mail
::formatFromAddress($params['from']);
348 // Allow WorkflowMessage to run any filters/mappings/cleanups.
349 $model = $params['model'] ?? WorkflowMessage
::create($params['workflow'] ??
'UNKNOWN');
350 $params = WorkflowMessage
::exportAll(WorkflowMessage
::importAll($model, $params));
351 unset($params['model']);
352 // 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']).
353 // If you want to expose the model via hook, consider interjecting a new Hook::alterWorkflowMessage($model) between `importAll()` and `exportAll()`.
356 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
358 CRM_Utils_Hook
::alterMailParams($params, 'messageTemplate');
359 $mailContent = self
::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ??
NULL, $params['groupName'] ??
'', $params['messageTemplate'], $params['subject'] ??
NULL);
362 $rendered = CRM_Core_TokenSmarty
::render(CRM_Utils_Array
::subset($mailContent, ['text', 'html', 'subject']), $params['tokenContext'], $params['tplParams']);
363 if (isset($rendered['subject'])) {
364 $rendered['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $rendered['subject']));
366 $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL];
367 $mailContent = array_merge($nullSet, $mailContent, $rendered);
368 return [$mailContent, $params];
372 * Send an email from the specified template based on an array of params.
374 * @param array $params
375 * A string-keyed array of function params, see function body for details.
378 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
379 * @throws \CRM_Core_Exception
380 * @throws \API_Exception
382 public static function sendTemplate(array $params): array {
383 // Handle isEmailPdf here as the unit test on that function deems it 'non-conforming'.
384 $isAttachPDF = !empty($params['isEmailPdf']);
385 unset($params['isEmailPdf']);
386 [$mailContent, $params] = self
::renderTemplateRaw($params);
388 // create the params array
389 $params['subject'] = $mailContent['subject'];
390 $params['text'] = $mailContent['text'];
391 $params['html'] = $mailContent['html'];
393 // send the template, honouring the target user’s preferences (if any)
395 if (!empty($params['toEmail'])) {
397 $config = CRM_Core_Config
::singleton();
399 // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId.
400 $pdfHtml = CRM_Contribute_BAO_ContributionPage
::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
401 if (empty($params['attachments'])) {
402 $params['attachments'] = [];
404 $params['attachments'][] = CRM_Utils_Mail
::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
407 if ($config->doNotAttachPDFReceipt
&&
408 $params['PDFFilename'] &&
411 if (empty($params['attachments'])) {
412 $params['attachments'] = [];
414 $params['attachments'][] = CRM_Utils_Mail
::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
415 if (isset($params['tplParams']['email_comment'])) {
416 $params['html'] = $params['tplParams']['email_comment'];
417 $params['text'] = strip_tags($params['tplParams']['email_comment']);
421 $sent = CRM_Utils_Mail
::send($params);
424 unlink($pdf_filename);
428 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
432 * Create a map between workflow_name and workflow_id.
435 * Array(string $workflowName => int $workflowId)
437 protected static function getWorkflowNameIdMap() {
438 // There's probably some more clever way to do this, but this seems simple.
439 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', [
440 1 => ['msg_tpl_workflow_%', 'String'],
441 ])->fetchMap('name', 'id');
445 * Load the specified template.
447 * @param string $workflowName
448 * @param bool $isTest
449 * @param int|null $messageTemplateID
450 * @param string $groupName
451 * @param array|null $messageTemplateOverride
452 * Optionally, record with msg_subject, msg_text, msg_html.
453 * If omitted, the record will be loaded from workflowName/messageTemplateID.
454 * @param string|null $subjectOverride
455 * This option is the older, wonkier version of $messageTemplate['msg_subject']...
458 * @throws \API_Exception
459 * @throws \CRM_Core_Exception
461 protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL, ?
array $messageTemplateOverride = NULL, ?
string $subjectOverride = NULL): array {
462 $base = ['msg_subject' => NULL, 'msg_text' => NULL, 'msg_html' => NULL, 'pdf_format_id' => NULL];
463 if (!$workflowName && !$messageTemplateID) {
464 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
467 $apiCall = MessageTemplate
::get(FALSE)
468 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
469 ->addWhere('is_default', '=', 1);
471 if ($messageTemplateID) {
472 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
475 $apiCall->addWhere('workflow_name', '=', $workflowName);
477 $messageTemplate = array_merge($base, $apiCall->execute()->first() ?
: [], $messageTemplateOverride ?
: []);
478 if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) {
479 if ($messageTemplateID) {
480 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
482 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
486 'subject' => $messageTemplate['msg_subject'],
487 'text' => $messageTemplate['msg_text'],
488 'html' => $messageTemplate['msg_html'],
489 'format' => $messageTemplate['pdf_format_id'],
490 // Workflow name is the field in the message templates table that denotes the
491 // workflow the template is used for. This is intended to eventually
492 // replace the non-standard option value/group implementation - see
493 // https://github.com/civicrm/civicrm-core/pull/17227 and the longer
494 // discussion on https://github.com/civicrm/civicrm-core/pull/17180
495 'workflow_name' => $workflowName,
496 // Note messageTemplateID is the id but when present we also know it was specifically requested.
497 'messageTemplateID' => $messageTemplateID,
498 // Group name & valueName are deprecated parameters. At some point it will not be passed out.
499 // https://github.com/civicrm/civicrm-core/pull/17180
500 'groupName' => $groupName,
501 'valueName' => $workflowName,
504 CRM_Utils_Hook
::alterMailContent($mailContent);
506 // add the test banner (if requested)
508 $testText = MessageTemplate
::get(FALSE)
509 ->setSelect(['msg_subject', 'msg_text', 'msg_html'])
510 ->addWhere('workflow_name', '=', 'test_preview')
511 ->addWhere('is_default', '=', TRUE)
512 ->execute()->first();
514 $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject'];
515 $mailContent['text'] = $testText['msg_text'] . $mailContent['text'];
516 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']);
519 if (!empty($subjectOverride)) {
520 CRM_Core_Error
::deprecatedWarning('CRM_Core_BAO_MessageTemplate: $params[subject] is deprecated. Use $params[messageTemplate][msg_subject] instead.');
521 $mailContent['subject'] = $subjectOverride;