Merge pull request #20119 from civicrm/5.37
[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 use Civi\Token\TokenProcessor;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19
20 use Civi\Api4\MessageTemplate;
21
22 require_once 'Mail/mime.php';
23
24 /**
25 * Class CRM_Core_BAO_MessageTemplate.
26 */
27 class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
28
29 /**
30 * Fetch object based on array of properties.
31 *
32 * @param array $params
33 * (reference ) an assoc array of name/value pairs.
34 * @param array $defaults
35 * (reference ) an assoc array to hold the flattened values.
36 *
37 * @return CRM_Core_DAO_MessageTemplate
38 */
39 public static function retrieve(&$params, &$defaults) {
40 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
41 $messageTemplates->copyValues($params);
42 if ($messageTemplates->find(TRUE)) {
43 CRM_Core_DAO::storeValues($messageTemplates, $defaults);
44 return $messageTemplates;
45 }
46 return NULL;
47 }
48
49 /**
50 * Update the is_active flag in the db.
51 *
52 * @param int $id
53 * Id of the database record.
54 * @param bool $is_active
55 * Value we want to set the is_active field.
56 *
57 * @return bool
58 * true if we found and updated the object, else false
59 */
60 public static function setIsActive($id, $is_active) {
61 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
62 }
63
64 /**
65 * Add the Message Templates.
66 *
67 * @param array $params
68 * Reference array contains the values submitted by the form.
69 *
70 *
71 * @return object
72 * @throws \CiviCRM_API3_Exception
73 * @throws \Civi\API\Exception\UnauthorizedException
74 */
75 public static function add(&$params) {
76 // System Workflow Templates have a specific wodkflow_id in them but normal user end message templates don't
77 // If we have an id check to see if we are update, and need to check if original is a system workflow or not.
78 $systemWorkflowPermissionDeniedMessage = 'Editing or creating system workflow messages requires edit system workflow message templates permission or the edit message templates permission';
79 $userWorkflowPermissionDeniedMessage = 'Editing or creating user driven workflow messages requires edit user-driven message templates or the edit message templates permission';
80 if (!empty($params['check_permissions'])) {
81 if (!CRM_Core_Permission::check('edit message templates')) {
82 if (!empty($params['id'])) {
83 $details = civicrm_api3('MessageTemplate', 'getSingle', ['id' => $params['id']]);
84 if (!empty($details['workflow_id']) || !empty($details['workflow_name'])) {
85 if (!CRM_Core_Permission::check('edit system workflow message templates')) {
86 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
87 }
88 }
89 elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
90 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
91 }
92 }
93 else {
94 if (!empty($params['workflow_id']) || !empty($params['workflow_name'])) {
95 if (!CRM_Core_Permission::check('edit system workflow message templates')) {
96 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
97 }
98 }
99 elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
100 throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
101 }
102 }
103 }
104 }
105 $hook = empty($params['id']) ? 'create' : 'edit';
106 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
107
108 if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
109 $fileParams = $params['file_id'];
110 unset($params['file_id']);
111 }
112
113 // The workflow_id and workflow_name should be sync'd. But what mix of inputs do we have to work with?
114 switch ((empty($params['workflow_id']) ? '' : 'id') . (empty($params['workflow_name']) ? '' : 'name')) {
115 case 'id':
116 $params['workflow_name'] = array_search($params['workflow_id'], self::getWorkflowNameIdMap());
117 break;
118
119 case 'name':
120 $params['workflow_id'] = self::getWorkflowNameIdMap()[$params['workflow_name']] ?? NULL;
121 break;
122
123 case 'idname':
124 $map = self::getWorkflowNameIdMap();
125 if ($map[$params['workflow_name']] != $params['workflow_id']) {
126 throw new CRM_Core_Exception("The workflow_id and workflow_name are mismatched. Note: You only need to submit one or the other.");
127 }
128 break;
129
130 case '':
131 // OK, don't care.
132 break;
133
134 default:
135 throw new \RuntimeException("Bad code");
136 }
137
138 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
139 $messageTemplates->copyValues($params);
140 $messageTemplates->save();
141
142 if (!empty($fileParams)) {
143 $params['file_id'] = $fileParams;
144 CRM_Core_BAO_File::filePostProcess(
145 $params['file_id']['location'],
146 NULL,
147 'civicrm_msg_template',
148 $messageTemplates->id,
149 NULL,
150 TRUE,
151 $params['file_id'],
152 'file_id',
153 $params['file_id']['type']
154 );
155 }
156
157 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
158 return $messageTemplates;
159 }
160
161 /**
162 * Delete the Message Templates.
163 *
164 * @param int $messageTemplatesID
165 *
166 * @throws \CRM_Core_Exception
167 */
168 public static function del($messageTemplatesID) {
169 // make sure messageTemplatesID is an integer
170 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
171 throw new CRM_Core_Exception(ts('Invalid Message template'));
172 }
173
174 // Set mailing msg template col to NULL
175 $query = "UPDATE civicrm_mailing
176 SET msg_template_id = NULL
177 WHERE msg_template_id = %1";
178
179 $params = [1 => [$messageTemplatesID, 'Integer']];
180 CRM_Core_DAO::executeQuery($query, $params);
181
182 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
183 $messageTemplates->id = $messageTemplatesID;
184 $messageTemplates->delete();
185 CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
186 }
187
188 /**
189 * Get the Message Templates.
190 *
191 *
192 * @param bool $all
193 *
194 * @param bool $isSMS
195 *
196 * @return array
197 */
198 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
199 $msgTpls = [];
200
201 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
202 $messageTemplates->is_active = 1;
203 $messageTemplates->is_sms = $isSMS;
204
205 if (!$all) {
206 $messageTemplates->workflow_id = 'NULL';
207 }
208 $messageTemplates->find();
209 while ($messageTemplates->fetch()) {
210 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
211 }
212 asort($msgTpls);
213 return $msgTpls;
214 }
215
216 /**
217 * @param int $contactId
218 * @param $email
219 * @param int $messageTemplateID
220 * @param $from
221 *
222 * @return bool|NULL
223 * @throws \CRM_Core_Exception
224 */
225 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
226 CRM_Core_Error::deprecatedWarning('CRM_Core_BAO_MessageTemplate::sendReminder is deprecated and will be removed in a future version of CiviCRM');
227
228 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
229 $messageTemplates->id = $messageTemplateID;
230
231 $domain = CRM_Core_BAO_Domain::getDomain();
232 $result = NULL;
233 $hookTokens = [];
234
235 if ($messageTemplates->find(TRUE)) {
236 $body_text = $messageTemplates->msg_text;
237 $body_html = $messageTemplates->msg_html;
238 $body_subject = $messageTemplates->msg_subject;
239 if (!$body_text) {
240 $body_text = CRM_Utils_String::htmlToText($body_html);
241 }
242
243 $params = [['contact_id', '=', $contactId, 0, 0]];
244 [$contact] = CRM_Contact_BAO_Query::apiQuery($params);
245
246 //CRM-4524
247 $contact = reset($contact);
248
249 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
250 return NULL;
251 }
252
253 //CRM-5734
254
255 // get tokens to be replaced
256 $tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
257 CRM_Utils_Token::getTokens($body_html),
258 CRM_Utils_Token::getTokens($body_subject));
259
260 // get replacement text for these tokens
261 $returnProperties = ["preferred_mail_format" => 1];
262 if (isset($tokens['contact'])) {
263 foreach ($tokens['contact'] as $key => $value) {
264 $returnProperties[$value] = 1;
265 }
266 }
267 [$details] = CRM_Utils_Token::getTokenDetails([$contactId],
268 $returnProperties,
269 NULL, NULL, FALSE,
270 $tokens,
271 'CRM_Core_BAO_MessageTemplate');
272 $contact = reset($details);
273
274 // call token hook
275 $hookTokens = [];
276 CRM_Utils_Hook::tokens($hookTokens);
277 $categories = array_keys($hookTokens);
278
279 // do replacements in text and html body
280 $type = ['html', 'text'];
281 foreach ($type as $key => $value) {
282 $bodyType = "body_{$value}";
283 if ($$bodyType) {
284 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
285 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens, TRUE);
286 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
287 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, TRUE);
288 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
289 }
290 }
291 $html = $body_html;
292 $text = $body_text;
293
294 $smarty = CRM_Core_Smarty::singleton();
295 foreach ([
296 'text',
297 'html',
298 ] as $elem) {
299 $$elem = $smarty->fetch("string:{$$elem}");
300 }
301
302 // do replacements in message subject
303 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
304 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
305 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
306 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
307
308 $messageSubject = $smarty->fetch("string:{$messageSubject}");
309
310 // set up the parameters for CRM_Utils_Mail::send
311 $mailParams = [
312 'groupName' => 'Scheduled Reminder Sender',
313 'from' => $from,
314 'toName' => $contact['display_name'],
315 'toEmail' => $email,
316 'subject' => $messageSubject,
317 ];
318 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
319 $contact['preferred_mail_format'] == 'Both'
320 ) {
321 // render the &amp; entities in text mode, so that the links work
322 $mailParams['text'] = str_replace('&amp;', '&', $text);
323 }
324 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
325 $contact['preferred_mail_format'] == 'Both'
326 )
327 ) {
328 $mailParams['html'] = $html;
329 }
330
331 $result = CRM_Utils_Mail::send($mailParams);
332 }
333
334 return $result;
335 }
336
337 /**
338 * Revert a message template to its default subject+text+HTML state.
339 *
340 * @param int $id id of the template
341 *
342 * @throws \CRM_Core_Exception
343 */
344 public static function revert($id) {
345 $diverted = new CRM_Core_BAO_MessageTemplate();
346 $diverted->id = (int) $id;
347 $diverted->find(1);
348
349 if ($diverted->N != 1) {
350 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
351 }
352
353 $orig = new CRM_Core_BAO_MessageTemplate();
354 $orig->workflow_id = $diverted->workflow_id;
355 $orig->is_reserved = 1;
356 $orig->find(1);
357
358 if ($orig->N != 1) {
359 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
360 }
361
362 $diverted->msg_subject = $orig->msg_subject;
363 $diverted->msg_text = $orig->msg_text;
364 $diverted->msg_html = $orig->msg_html;
365 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
366 $diverted->save();
367 }
368
369 /**
370 * Send an email from the specified template based on an array of params.
371 *
372 * @param array $params
373 * A string-keyed array of function params, see function body for details.
374 *
375 * @return array
376 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
377 * @throws \CRM_Core_Exception
378 * @throws \API_Exception
379 */
380 public static function sendTemplate($params) {
381 $defaults = [
382 // option value name of the template
383 'valueName' => NULL,
384 // ID of the template
385 'messageTemplateID' => NULL,
386 // contact id if contact tokens are to be replaced
387 'contactId' => NULL,
388 // additional template params (other than the ones already set in the template singleton)
389 'tplParams' => [],
390 // the From: header
391 'from' => NULL,
392 // the recipient’s name
393 'toName' => NULL,
394 // the recipient’s email - mail is sent only if set
395 'toEmail' => NULL,
396 // the Cc: header
397 'cc' => NULL,
398 // the Bcc: header
399 'bcc' => NULL,
400 // the Reply-To: header
401 'replyTo' => NULL,
402 // email attachments
403 'attachments' => NULL,
404 // whether this is a test email (and hence should include the test banner)
405 'isTest' => FALSE,
406 // filename of optional PDF version to add as attachment (do not include path)
407 'PDFFilename' => NULL,
408 // Disable Smarty?
409 'disableSmarty' => FALSE,
410 ];
411 $params = array_merge($defaults, $params);
412
413 // Core#644 - handle Email ID passed as "From".
414 if (isset($params['from'])) {
415 $params['from'] = CRM_Utils_Mail::formatFromAddress($params['from']);
416 }
417
418 CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
419 if (!is_int($params['messageTemplateID']) && !is_null($params['messageTemplateID'])) {
420 CRM_Core_Error::deprecatedWarning('message template id should be an integer');
421 $params['messageTemplateID'] = (int) $params['messageTemplateID'];
422 }
423 $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '');
424
425 // Overwrite subject from form field
426 if (!empty($params['subject'])) {
427 $mailContent['subject'] = $params['subject'];
428 }
429
430 $mailContent = self::renderMessageTemplate($mailContent, (bool) $params['disableSmarty'], $params['contactId'] ?? NULL, $params['tplParams']);
431
432 // send the template, honouring the target user’s preferences (if any)
433 $sent = FALSE;
434
435 // create the params array
436 $params['subject'] = $mailContent['subject'];
437 $params['text'] = $mailContent['text'];
438 $params['html'] = $mailContent['html'];
439
440 if ($params['toEmail']) {
441 $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
442 [$contact] = CRM_Contact_BAO_Query::apiQuery($contactParams);
443
444 $prefs = array_pop($contact);
445
446 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'HTML') {
447 $params['text'] = NULL;
448 }
449
450 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] === 'Text') {
451 $params['html'] = NULL;
452 }
453
454 $config = CRM_Core_Config::singleton();
455 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
456 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
457 if (empty($params['attachments'])) {
458 $params['attachments'] = [];
459 }
460 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
461 }
462 $pdf_filename = '';
463 if ($config->doNotAttachPDFReceipt &&
464 $params['PDFFilename'] &&
465 $params['html']
466 ) {
467 if (empty($params['attachments'])) {
468 $params['attachments'] = [];
469 }
470 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
471 if (isset($params['tplParams']['email_comment'])) {
472 $params['html'] = $params['tplParams']['email_comment'];
473 $params['text'] = strip_tags($params['tplParams']['email_comment']);
474 }
475 }
476
477 $sent = CRM_Utils_Mail::send($params);
478
479 if ($pdf_filename) {
480 unlink($pdf_filename);
481 }
482 }
483
484 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
485 }
486
487 /**
488 * Create a map between workflow_name and workflow_id.
489 *
490 * @return array
491 * Array(string $workflowName => int $workflowId)
492 */
493 protected static function getWorkflowNameIdMap() {
494 // There's probably some more clever way to do this, but this seems simple.
495 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', [
496 1 => ['msg_tpl_workflow_%', 'String'],
497 ])->fetchMap('name', 'id');
498 }
499
500 /**
501 * Load the specified template.
502 *
503 * @param string $workflowName
504 * @param bool $isTest
505 * @param int|null $messageTemplateID
506 * @param string $groupName
507 *
508 * @return array
509 * @throws \API_Exception
510 * @throws \CRM_Core_Exception
511 */
512 protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL): array {
513 if (!$workflowName && !$messageTemplateID) {
514 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
515 }
516
517 $apiCall = MessageTemplate::get(FALSE)
518 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
519 ->addWhere('is_default', '=', 1);
520
521 if ($messageTemplateID) {
522 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
523 }
524 else {
525 $apiCall->addWhere('workflow_name', '=', $workflowName);
526 }
527 $messageTemplate = $apiCall->execute()->first();
528 if (empty($messageTemplate['id'])) {
529 if ($messageTemplateID) {
530 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
531 }
532 throw new CRM_Core_Exception(ts('No message template with workflow name %2.', [2 => $workflowName]));
533 }
534
535 $mailContent = [
536 'subject' => $messageTemplate['msg_subject'],
537 'text' => $messageTemplate['msg_text'],
538 'html' => $messageTemplate['msg_html'],
539 'format' => $messageTemplate['pdf_format_id'],
540 // Workflow name is the field in the message templates table that denotes the
541 // workflow the template is used for. This is intended to eventually
542 // replace the non-standard option value/group implementation - see
543 // https://github.com/civicrm/civicrm-core/pull/17227 and the longer
544 // discussion on https://github.com/civicrm/civicrm-core/pull/17180
545 'workflow_name' => $workflowName,
546 // Note messageTemplateID is the id but when present we also know it was specifically requested.
547 'messageTemplateID' => $messageTemplateID,
548 // Group name & valueName are deprecated parameters. At some point it will not be passed out.
549 // https://github.com/civicrm/civicrm-core/pull/17180
550 'groupName' => $groupName,
551 'valueName' => $workflowName,
552 ];
553
554 CRM_Utils_Hook::alterMailContent($mailContent);
555
556 // add the test banner (if requested)
557 if ($isTest) {
558 $testText = MessageTemplate::get(FALSE)
559 ->setSelect(['msg_subject', 'msg_text', 'msg_html'])
560 ->addWhere('workflow_name', '=', 'test_preview')
561 ->addWhere('is_default', '=', TRUE)
562 ->execute()->first();
563
564 $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject'];
565 $mailContent['text'] = $testText['msg_text'] . $mailContent['text'];
566 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']);
567 }
568
569 return $mailContent;
570 }
571
572 /**
573 * Render the message template, resolving tokens and smarty tokens.
574 *
575 * As with all BAO methods this should not be called directly outside
576 * of tested core code and is highly likely to change.
577 *
578 * @param array $mailContent
579 * @param bool $disableSmarty
580 * @param int|NULL $contactID
581 * @param array $smartyAssigns
582 *
583 * @return array
584 */
585 public static function renderMessageTemplate(array $mailContent, bool $disableSmarty, $contactID, array $smartyAssigns): array {
586 CRM_Core_Smarty::singleton()->pushScope($smartyAssigns);
587 $tokenProcessor = new TokenProcessor(\Civi::dispatcher(), ['smarty' => !$disableSmarty]);
588 $tokenProcessor->addMessage('html', $mailContent['html'], 'text/html');
589 $tokenProcessor->addMessage('text', $mailContent['text'], 'text/plain');
590 $tokenProcessor->addMessage('subject', $mailContent['subject'], 'text/plain');
591 $tokenProcessor->addRow($contactID ? ['contactId' => $contactID] : []);
592 $tokenProcessor->evaluate();
593 foreach ($tokenProcessor->getRows() as $row) {
594 $mailContent['html'] = $row->render('html');
595 $mailContent['text'] = $row->render('text');
596 $mailContent['subject'] = $row->render('subject');
597 }
598 CRM_Core_Smarty::singleton()->popScope();
599 $mailContent['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $mailContent['subject']));
600 return $mailContent;
601 }
602
603 }