Merge pull request #21354 from andyburnsco/patch-1
[civicrm-core.git] / CRM / Core / BAO / MessageTemplate.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 use Civi\Api4\MessageTemplate;
19 use Civi\WorkflowMessage\WorkflowMessage;
20
21 require_once 'Mail/mime.php';
22
23 /**
24 * Class CRM_Core_BAO_MessageTemplate.
25 */
26 class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
27
28 /**
29 * Fetch object based on array of properties.
30 *
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.
35 *
36 * @return CRM_Core_DAO_MessageTemplate
37 */
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;
44 }
45 return NULL;
46 }
47
48 /**
49 * Update the is_active flag in the db.
50 *
51 * @param int $id
52 * Id of the database record.
53 * @param bool $is_active
54 * Value we want to set the is_active field.
55 *
56 * @return bool
57 * true if we found and updated the object, else false
58 */
59 public static function setIsActive($id, $is_active) {
60 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
61 }
62
63 /**
64 * Add the Message Templates.
65 *
66 * @param array $params
67 * Reference array contains the values submitted by the form.
68 *
69 *
70 * @return object
71 * @throws \CiviCRM_API3_Exception
72 * @throws \Civi\API\Exception\UnauthorizedException
73 */
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]));
86 }
87 }
88 elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
89 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
90 }
91 }
92 else {
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]));
96 }
97 }
98 elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
99 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
100 }
101 }
102 }
103 }
104 $hook = empty($params['id']) ? 'create' : 'edit';
105 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
106
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']);
110 }
111
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')) {
114 case 'id':
115 $params['workflow_name'] = array_search($params['workflow_id'], self::getWorkflowNameIdMap());
116 break;
117
118 case 'name':
119 $params['workflow_id'] = self::getWorkflowNameIdMap()[$params['workflow_name']] ?? NULL;
120 break;
121
122 case 'idname':
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.");
126 }
127 break;
128
129 case '':
130 // OK, don't care.
131 break;
132
133 default:
134 throw new \RuntimeException("Bad code");
135 }
136
137 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
138 $messageTemplates->copyValues($params);
139 $messageTemplates->save();
140
141 if (!empty($fileParams)) {
142 $params['file_id'] = $fileParams;
143 CRM_Core_BAO_File::filePostProcess(
144 $params['file_id']['location'],
145 NULL,
146 'civicrm_msg_template',
147 $messageTemplates->id,
148 NULL,
149 TRUE,
150 $params['file_id'],
151 'file_id',
152 $params['file_id']['type']
153 );
154 }
155
156 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
157 return $messageTemplates;
158 }
159
160 /**
161 * Delete the Message Templates.
162 *
163 * @param int $messageTemplatesID
164 *
165 * @throws \CRM_Core_Exception
166 */
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'));
171 }
172
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";
177
178 $params = [1 => [$messageTemplatesID, 'Integer']];
179 CRM_Core_DAO::executeQuery($query, $params);
180
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');
185 }
186
187 /**
188 * Get the Message Templates.
189 *
190 *
191 * @param bool $all
192 *
193 * @param bool $isSMS
194 *
195 * @return array
196 */
197 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
198 $msgTpls = [];
199
200 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
201 $messageTemplates->is_active = 1;
202 $messageTemplates->is_sms = $isSMS;
203
204 if (!$all) {
205 $messageTemplates->workflow_id = 'NULL';
206 }
207 $messageTemplates->find();
208 while ($messageTemplates->fetch()) {
209 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
210 }
211 asort($msgTpls);
212 return $msgTpls;
213 }
214
215 /**
216 * Revert a message template to its default subject+text+HTML state.
217 *
218 * @param int $id id of the template
219 *
220 * @throws \CRM_Core_Exception
221 */
222 public static function revert($id) {
223 $diverted = new CRM_Core_BAO_MessageTemplate();
224 $diverted->id = (int) $id;
225 $diverted->find(1);
226
227 if ($diverted->N != 1) {
228 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
229 }
230
231 $orig = new CRM_Core_BAO_MessageTemplate();
232 $orig->workflow_id = $diverted->workflow_id;
233 $orig->is_reserved = 1;
234 $orig->find(1);
235
236 if ($orig->N != 1) {
237 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
238 }
239
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;
244 $diverted->save();
245 }
246
247 /**
248 * Render a message template.
249 *
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.
253 *
254 * @param $params
255 * Mixed render parameters. See sendTemplate() for more details.
256 * @return array
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()
262 */
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)));
269 }
270
271 $mailContent = [];
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);
275 return $mailContent;
276 }
277
278 /**
279 * Send an email from the specified template based on an array of params.
280 *
281 * @param array $params
282 * A string-keyed array of function params, see function body for details.
283 *
284 * @return array
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
288 */
289 public static function sendTemplate($params) {
290 $modelDefaults = [
291 // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template
292 'model' => NULL,
293 // Symbolic name of the workflow step. Matches the option-value-name of the template.
294 'valueName' => NULL,
295 // additional template params (other than the ones already set in the template singleton)
296 'tplParams' => [],
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
303 'contactId' => NULL,
304 ];
305 $viewDefaults = [
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)
313 'isTest' => FALSE,
314 // Disable Smarty?
315 'disableSmarty' => FALSE,
316 ];
317 $envelopeDefaults = [
318 // the From: header
319 'from' => NULL,
320 // the recipient’s name
321 'toName' => NULL,
322 // the recipient’s email - mail is sent only if set
323 'toEmail' => NULL,
324 // the Cc: header
325 'cc' => NULL,
326 // the Bcc: header
327 'bcc' => NULL,
328 // the Reply-To: header
329 'replyTo' => NULL,
330 // email attachments
331 'attachments' => NULL,
332 // filename of optional PDF version to add as attachment (do not include path)
333 'PDFFilename' => NULL,
334 ];
335
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()`.
342
343 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
344
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'];
349 }
350 $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '', $params['messageTemplate'], $params['subject'] ?? NULL);
351
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']));
359 }
360 $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL];
361 $mailContent = array_merge($nullSet, $mailContent, $rendered);
362
363 // send the template, honouring the target user’s preferences (if any)
364 $sent = FALSE;
365
366 // create the params array
367 $params['subject'] = $mailContent['subject'];
368 $params['text'] = $mailContent['text'];
369 $params['html'] = $mailContent['html'];
370
371 if ($params['toEmail']) {
372 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
373 [$contact] = CRM_Contact_BAO_Query::apiQuery($contactParams);
374
375 $prefs = array_pop($contact);
376
377 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
378 $params['text'] = NULL;
379 }
380
381 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
382 $params['html'] = NULL;
383 }
384
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'] = [];
391 }
392 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
393 }
394 $pdf_filename = '';
395 if ($config->doNotAttachPDFReceipt &&
396 $params['PDFFilename'] &&
397 $params['html']
398 ) {
399 if (empty($params['attachments'])) {
400 $params['attachments'] = [];
401 }
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']);
406 }
407 }
408
409 $sent = CRM_Utils_Mail::send($params);
410
411 if ($pdf_filename) {
412 unlink($pdf_filename);
413 }
414 }
415
416 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
417 }
418
419 /**
420 * Create a map between workflow_name and workflow_id.
421 *
422 * @return array
423 * Array(string $workflowName => int $workflowId)
424 */
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');
430 }
431
432 /**
433 * Load the specified template.
434 *
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']...
444 *
445 * @return array
446 * @throws \API_Exception
447 * @throws \CRM_Core_Exception
448 */
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."));
453 }
454
455 $apiCall = MessageTemplate::get(FALSE)
456 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
457 ->addWhere('is_default', '=', 1);
458
459 if ($messageTemplateID) {
460 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
461 }
462 else {
463 $apiCall->addWhere('workflow_name', '=', $workflowName);
464 }
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]));
469 }
470 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
471 }
472
473 $mailContent = [
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,
490 ];
491
492 CRM_Utils_Hook::alterMailContent($mailContent);
493
494 // add the test banner (if requested)
495 if ($isTest) {
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();
501
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']);
505 }
506
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;
510 }
511
512 return $mailContent;
513 }
514
515 }