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