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