Merge pull request #21919 from braders/deprecated-jquery-xhr-usage
[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\Email;
19 use Civi\Api4\MessageTemplate;
20 use Civi\WorkflowMessage\WorkflowMessage;
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 $empty = function ($key) use (&$params) {
115 return empty($params[$key]) || $params[$key] === 'null';
116 };
117 switch (($empty('workflow_id') ? '' : 'id') . ($empty('workflow_name') ? '' : 'name')) {
118 case 'id':
119 $params['workflow_name'] = array_search($params['workflow_id'], self::getWorkflowNameIdMap());
120 break;
121
122 case 'name':
123 $params['workflow_id'] = self::getWorkflowNameIdMap()[$params['workflow_name']] ?? NULL;
124 break;
125
126 case 'idname':
127 $map = self::getWorkflowNameIdMap();
128 if ($map[$params['workflow_name']] != $params['workflow_id']) {
129 throw new CRM_Core_Exception("The workflow_id and workflow_name are mismatched. Note: You only need to submit one or the other.");
130 }
131 break;
132
133 case '':
134 // OK, don't care.
135 break;
136
137 default:
138 throw new \RuntimeException("Bad code");
139 }
140
141 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
142 $messageTemplates->copyValues($params);
143 $messageTemplates->save();
144
145 if (!empty($fileParams)) {
146 $params['file_id'] = $fileParams;
147 CRM_Core_BAO_File::filePostProcess(
148 $params['file_id']['location'],
149 NULL,
150 'civicrm_msg_template',
151 $messageTemplates->id,
152 NULL,
153 TRUE,
154 $params['file_id'],
155 'file_id',
156 $params['file_id']['type']
157 );
158 }
159
160 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
161 return $messageTemplates;
162 }
163
164 /**
165 * Delete the Message Templates.
166 *
167 * @param int $messageTemplatesID
168 *
169 * @throws \CRM_Core_Exception
170 */
171 public static function del($messageTemplatesID) {
172 // make sure messageTemplatesID is an integer
173 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
174 throw new CRM_Core_Exception(ts('Invalid Message template'));
175 }
176
177 // Set mailing msg template col to NULL
178 $query = "UPDATE civicrm_mailing
179 SET msg_template_id = NULL
180 WHERE msg_template_id = %1";
181
182 $params = [1 => [$messageTemplatesID, 'Integer']];
183 CRM_Core_DAO::executeQuery($query, $params);
184
185 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
186 $messageTemplates->id = $messageTemplatesID;
187 $messageTemplates->delete();
188 CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
189 }
190
191 /**
192 * Get the Message Templates.
193 *
194 *
195 * @param bool $all
196 *
197 * @param bool $isSMS
198 *
199 * @return array
200 */
201 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
202 $msgTpls = [];
203
204 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
205 $messageTemplates->is_active = 1;
206 $messageTemplates->is_sms = $isSMS;
207
208 if (!$all) {
209 $messageTemplates->workflow_id = 'NULL';
210 }
211 $messageTemplates->find();
212 while ($messageTemplates->fetch()) {
213 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
214 }
215 asort($msgTpls);
216 return $msgTpls;
217 }
218
219 /**
220 * Revert a message template to its default subject+text+HTML state.
221 *
222 * @param int $id id of the template
223 *
224 * @throws \CRM_Core_Exception
225 */
226 public static function revert($id) {
227 $diverted = new CRM_Core_BAO_MessageTemplate();
228 $diverted->id = (int) $id;
229 $diverted->find(1);
230
231 if ($diverted->N != 1) {
232 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
233 }
234
235 $orig = new CRM_Core_BAO_MessageTemplate();
236 $orig->workflow_name = $diverted->workflow_name;
237 $orig->is_reserved = 1;
238 $orig->find(1);
239
240 if ($orig->N != 1) {
241 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
242 }
243
244 $diverted->msg_subject = $orig->msg_subject;
245 $diverted->msg_text = $orig->msg_text;
246 $diverted->msg_html = $orig->msg_html;
247 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
248 $diverted->save();
249 }
250
251 /**
252 * Render a message template.
253 *
254 * This method is very similar to `sendTemplate()` - accepting most of the same arguments
255 * and emitting similar hooks. However, it specifically precludes the possibility of
256 * sending a message. It only renders.
257 *
258 * @param $params
259 * Mixed render parameters. See sendTemplate() for more details.
260 * @return array
261 * Rendered message, consistent of 'subject', 'text', 'html'
262 * Ex: ['subject' => 'Hello Bob', 'text' => 'It\'s been so long since we sent you an automated notification!']
263 * @throws \API_Exception
264 * @throws \CRM_Core_Exception
265 * @see sendTemplate()
266 */
267 public static function renderTemplate($params) {
268 [$mailContent, $params] = self::renderTemplateRaw($params);
269 return CRM_Utils_Array::subset($mailContent, ['subject', 'text', 'html']);
270 }
271
272 /**
273 * Render a message template.
274 *
275 * @param array $params
276 * Mixed render parameters. See sendTemplate() for more details.
277 * @return array
278 * Tuple of [$mailContent, $updatedParams].
279 * @throws \API_Exception
280 * @throws \CRM_Core_Exception
281 * @see sendTemplate()
282 */
283 protected static function renderTemplateRaw($params) {
284 $modelDefaults = [
285 // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template
286 'model' => NULL,
287 // Symbolic name of the workflow step. Matches the option-value-name of the template.
288 'valueName' => NULL,
289 // additional template params (other than the ones already set in the template singleton)
290 'tplParams' => [],
291 // additional token params (passed to the TokenProcessor)
292 // INTERNAL: 'tokenContext' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
293 'tokenContext' => [],
294 // properties to import directly to the model object
295 'modelProps' => NULL,
296 // contact id if contact tokens are to be replaced; alias for tokenContext.contactId
297 'contactId' => NULL,
298 ];
299 $viewDefaults = [
300 // ID of the specific template to load
301 'messageTemplateID' => NULL,
302 // content of the message template
303 // Ex: ['msg_subject' => 'Hello {contact.display_name}', 'msg_html' => '...', 'msg_text' => '...']
304 // INTERNAL: 'messageTemplate' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
305 'messageTemplate' => NULL,
306 // whether this is a test email (and hence should include the test banner)
307 'isTest' => FALSE,
308 // Disable Smarty?
309 'disableSmarty' => FALSE,
310 ];
311 $envelopeDefaults = [
312 // the From: header
313 'from' => NULL,
314 // the recipient’s name
315 'toName' => NULL,
316 // the recipient’s email - mail is sent only if set
317 'toEmail' => NULL,
318 // the Cc: header
319 'cc' => NULL,
320 // the Bcc: header
321 'bcc' => NULL,
322 // the Reply-To: header
323 'replyTo' => NULL,
324 // email attachments
325 'attachments' => NULL,
326 // filename of optional PDF version to add as attachment (do not include path)
327 'PDFFilename' => NULL,
328 ];
329
330 // Some params have been deprecated/renamed. Synchronize old<=>new params. We periodically resync after exchanging data with other parties.
331 $sync = function () use (&$params, $modelDefaults, $viewDefaults) {
332 CRM_Utils_Array::pathSync($params, ['workflow'], ['valueName']);
333 CRM_Utils_Array::pathSync($params, ['tokenContext', 'contactId'], ['contactId']);
334 CRM_Utils_Array::pathSync($params, ['tokenContext', 'smarty'], ['disableSmarty'], function ($v, bool $isCanon) {
335 return !$v;
336 });
337
338 // Core#644 - handle Email ID passed as "From".
339 if (isset($params['from'])) {
340 $params['from'] = \CRM_Utils_Mail::formatFromAddress($params['from']);
341 }
342 };
343 $sync();
344
345 // Allow WorkflowMessage to run any filters/mappings/cleanups.
346 $model = $params['model'] ?? WorkflowMessage::create($params['workflow'] ?? 'UNKNOWN');
347 $params = WorkflowMessage::exportAll(WorkflowMessage::importAll($model, $params));
348 unset($params['model']);
349 // 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']).
350 // If you want to expose the model via hook, consider interjecting a new Hook::alterWorkflowMessage($model) between `importAll()` and `exportAll()`.
351
352 $sync();
353 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
354
355 CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
356 $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '', $params['messageTemplate'], $params['subject'] ?? NULL);
357
358 $sync();
359 $rendered = CRM_Core_TokenSmarty::render(CRM_Utils_Array::subset($mailContent, ['text', 'html', 'subject']), $params['tokenContext'], $params['tplParams']);
360 if (isset($rendered['subject'])) {
361 $rendered['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $rendered['subject']));
362 }
363 $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL];
364 $mailContent = array_merge($nullSet, $mailContent, $rendered);
365 return [$mailContent, $params];
366 }
367
368 /**
369 * Send an email from the specified template based on an array of params.
370 *
371 * @param array $params
372 * A string-keyed array of function params, see function body for details.
373 *
374 * @return array
375 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
376 * @throws \CRM_Core_Exception
377 * @throws \API_Exception
378 */
379 public static function sendTemplate(array $params): array {
380 // Handle isEmailPdf here as the unit test on that function deems it 'non-conforming'.
381 $isAttachPDF = !empty($params['isEmailPdf']);
382 unset($params['isEmailPdf']);
383 [$mailContent, $params] = self::renderTemplateRaw($params);
384
385 // create the params array
386 $params['subject'] = $mailContent['subject'];
387 $params['text'] = $mailContent['text'];
388 $params['html'] = $mailContent['html'];
389
390 // send the template, honouring the target user’s preferences (if any)
391 $sent = FALSE;
392 if (!empty($params['toEmail'])) {
393 // @todo - consider whether we really should be loading
394 // this based on 'the first email in the db that matches'.
395 // when we likely have the contact id. OTOH people probably barely
396 // use preferredMailFormat these days - the good fight against html
397 // emails was lost a decade ago...
398 $preferredMailFormatArray = Email::get(FALSE)->addWhere('email', '=', $params['toEmail'])->addSelect('contact_id.preferred_mail_format')->execute()->first();
399 $preferredMailFormat = $preferredMailFormatArray['contact_id.preferred_mail_format'] ?? 'Both';
400
401 if ($preferredMailFormat === 'HTML') {
402 $params['text'] = NULL;
403 }
404 if ($preferredMailFormat === 'Text') {
405 $params['html'] = NULL;
406 }
407
408 $config = CRM_Core_Config::singleton();
409 if ($isAttachPDF) {
410 // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId.
411 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
412 if (empty($params['attachments'])) {
413 $params['attachments'] = [];
414 }
415 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
416 }
417 $pdf_filename = '';
418 if ($config->doNotAttachPDFReceipt &&
419 $params['PDFFilename'] &&
420 $params['html']
421 ) {
422 if (empty($params['attachments'])) {
423 $params['attachments'] = [];
424 }
425 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
426 if (isset($params['tplParams']['email_comment'])) {
427 $params['html'] = $params['tplParams']['email_comment'];
428 $params['text'] = strip_tags($params['tplParams']['email_comment']);
429 }
430 }
431
432 $sent = CRM_Utils_Mail::send($params);
433
434 if ($pdf_filename) {
435 unlink($pdf_filename);
436 }
437 }
438
439 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
440 }
441
442 /**
443 * Create a map between workflow_name and workflow_id.
444 *
445 * @return array
446 * Array(string $workflowName => int $workflowId)
447 */
448 protected static function getWorkflowNameIdMap() {
449 // There's probably some more clever way to do this, but this seems simple.
450 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', [
451 1 => ['msg_tpl_workflow_%', 'String'],
452 ])->fetchMap('name', 'id');
453 }
454
455 /**
456 * Load the specified template.
457 *
458 * @param string $workflowName
459 * @param bool $isTest
460 * @param int|null $messageTemplateID
461 * @param string $groupName
462 * @param array|null $messageTemplateOverride
463 * Optionally, record with msg_subject, msg_text, msg_html.
464 * If omitted, the record will be loaded from workflowName/messageTemplateID.
465 * @param string|null $subjectOverride
466 * This option is the older, wonkier version of $messageTemplate['msg_subject']...
467 *
468 * @return array
469 * @throws \API_Exception
470 * @throws \CRM_Core_Exception
471 */
472 protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL, ?array $messageTemplateOverride = NULL, ?string $subjectOverride = NULL): array {
473 $base = ['msg_subject' => NULL, 'msg_text' => NULL, 'msg_html' => NULL, 'pdf_format_id' => NULL];
474 if (!$workflowName && !$messageTemplateID) {
475 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
476 }
477
478 $apiCall = MessageTemplate::get(FALSE)
479 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
480 ->addWhere('is_default', '=', 1);
481
482 if ($messageTemplateID) {
483 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
484 }
485 else {
486 $apiCall->addWhere('workflow_name', '=', $workflowName);
487 }
488 $messageTemplate = array_merge($base, $apiCall->execute()->first() ?: [], $messageTemplateOverride ?: []);
489 if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) {
490 if ($messageTemplateID) {
491 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
492 }
493 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
494 }
495
496 $mailContent = [
497 'subject' => $messageTemplate['msg_subject'],
498 'text' => $messageTemplate['msg_text'],
499 'html' => $messageTemplate['msg_html'],
500 'format' => $messageTemplate['pdf_format_id'],
501 // Workflow name is the field in the message templates table that denotes the
502 // workflow the template is used for. This is intended to eventually
503 // replace the non-standard option value/group implementation - see
504 // https://github.com/civicrm/civicrm-core/pull/17227 and the longer
505 // discussion on https://github.com/civicrm/civicrm-core/pull/17180
506 'workflow_name' => $workflowName,
507 // Note messageTemplateID is the id but when present we also know it was specifically requested.
508 'messageTemplateID' => $messageTemplateID,
509 // Group name & valueName are deprecated parameters. At some point it will not be passed out.
510 // https://github.com/civicrm/civicrm-core/pull/17180
511 'groupName' => $groupName,
512 'valueName' => $workflowName,
513 ];
514
515 CRM_Utils_Hook::alterMailContent($mailContent);
516
517 // add the test banner (if requested)
518 if ($isTest) {
519 $testText = MessageTemplate::get(FALSE)
520 ->setSelect(['msg_subject', 'msg_text', 'msg_html'])
521 ->addWhere('workflow_name', '=', 'test_preview')
522 ->addWhere('is_default', '=', TRUE)
523 ->execute()->first();
524
525 $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject'];
526 $mailContent['text'] = $testText['msg_text'] . $mailContent['text'];
527 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']);
528 }
529
530 if (!empty($subjectOverride)) {
531 CRM_Core_Error::deprecatedWarning('CRM_Core_BAO_MessageTemplate: $params[subject] is deprecated. Use $params[messageTemplate][msg_subject] instead.');
532 $mailContent['subject'] = $subjectOverride;
533 }
534
535 return $mailContent;
536 }
537
538 }