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