[REF] Remove illusion of looping
[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 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 * Revert a message template to its default subject+text+HTML state.
218 *
219 * @param int $id id of the template
220 *
221 * @throws \CRM_Core_Exception
222 */
223 public static function revert($id) {
224 $diverted = new CRM_Core_BAO_MessageTemplate();
225 $diverted->id = (int) $id;
226 $diverted->find(1);
227
228 if ($diverted->N != 1) {
229 throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id]));
230 }
231
232 $orig = new CRM_Core_BAO_MessageTemplate();
233 $orig->workflow_id = $diverted->workflow_id;
234 $orig->is_reserved = 1;
235 $orig->find(1);
236
237 if ($orig->N != 1) {
238 throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
239 }
240
241 $diverted->msg_subject = $orig->msg_subject;
242 $diverted->msg_text = $orig->msg_text;
243 $diverted->msg_html = $orig->msg_html;
244 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
245 $diverted->save();
246 }
247
248 /**
249 * Render a message template.
250 *
251 * This method is very similar to `sendTemplate()` - accepting most of the same arguments
252 * and emitting similar hooks. However, it specifically precludes the possibility of
253 * sending a message. It only renders.
254 *
255 * @param $params
256 * Mixed render parameters. See sendTemplate() for more details.
257 * @return array
258 * Rendered message, consistent of 'subject', 'text', 'html'
259 * Ex: ['subject' => 'Hello Bob', 'text' => 'It\'s been so long since we sent you an automated notification!']
260 * @throws \API_Exception
261 * @throws \CRM_Core_Exception
262 * @see sendTemplate()
263 */
264 public static function renderTemplate($params) {
265 $forbidden = ['from', 'toName', 'toEmail', 'cc', 'bcc', 'replyTo'];
266 $intersect = array_intersect($forbidden, array_keys($params));
267 if (!empty($intersect)) {
268 throw new \CRM_Core_Exception(sprintf("renderTemplate() received forbidden fields (%s)",
269 implode(',', $intersect)));
270 }
271
272 $mailContent = [];
273 // sendTemplate has had an obscure feature - if you omit `toEmail`, then it merely renders.
274 // At some point, we may want to invert the relation between renderTemplate/sendTemplate, but for now this is a smaller patch.
275 [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']] = static::sendTemplate($params);
276 return $mailContent;
277 }
278
279 /**
280 * Send an email from the specified template based on an array of params.
281 *
282 * @param array $params
283 * A string-keyed array of function params, see function body for details.
284 *
285 * @return array
286 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
287 * @throws \CRM_Core_Exception
288 * @throws \API_Exception
289 */
290 public static function sendTemplate($params) {
291 $modelDefaults = [
292 // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template
293 'model' => NULL,
294 // Symbolic name of the workflow step. Matches the option-value-name of the template.
295 'valueName' => NULL,
296 // additional template params (other than the ones already set in the template singleton)
297 'tplParams' => [],
298 // additional token params (passed to the TokenProcessor)
299 // INTERNAL: 'tokenContext' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
300 'tokenContext' => [],
301 // properties to import directly to the model object
302 'modelProps' => NULL,
303 // contact id if contact tokens are to be replaced; alias for tokenContext.contactId
304 'contactId' => NULL,
305 ];
306 $viewDefaults = [
307 // ID of the specific template to load
308 'messageTemplateID' => NULL,
309 // content of the message template
310 // Ex: ['msg_subject' => 'Hello {contact.display_name}', 'msg_html' => '...', 'msg_text' => '...']
311 // INTERNAL: 'messageTemplate' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs.
312 'messageTemplate' => NULL,
313 // whether this is a test email (and hence should include the test banner)
314 'isTest' => FALSE,
315 // Disable Smarty?
316 'disableSmarty' => FALSE,
317 ];
318 $envelopeDefaults = [
319 // the From: header
320 'from' => NULL,
321 // the recipient’s name
322 'toName' => NULL,
323 // the recipient’s email - mail is sent only if set
324 'toEmail' => NULL,
325 // the Cc: header
326 'cc' => NULL,
327 // the Bcc: header
328 'bcc' => NULL,
329 // the Reply-To: header
330 'replyTo' => NULL,
331 // email attachments
332 'attachments' => NULL,
333 // filename of optional PDF version to add as attachment (do not include path)
334 'PDFFilename' => NULL,
335 ];
336
337 // Allow WorkflowMessage to run any filters/mappings/cleanups.
338 $model = $params['model'] ?? WorkflowMessage::create($params['valueName'] ?? 'UNKNOWN');
339 $params = WorkflowMessage::exportAll(WorkflowMessage::importAll($model, $params));
340 unset($params['model']);
341 // 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']).
342 // If you want to expose the model via hook, consider interjecting a new Hook::alterWorkflowMessage($model) between `importAll()` and `exportAll()`.
343
344 $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params);
345
346 CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
347 if (!is_int($params['messageTemplateID']) && !is_null($params['messageTemplateID'])) {
348 CRM_Core_Error::deprecatedWarning('message template id should be an integer');
349 $params['messageTemplateID'] = (int) $params['messageTemplateID'];
350 }
351 $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '', $params['messageTemplate'], $params['subject'] ?? NULL);
352
353 $params['tokenContext'] = array_merge([
354 'smarty' => (bool) !$params['disableSmarty'],
355 'contactId' => $params['contactId'],
356 ], $params['tokenContext']);
357 $rendered = CRM_Core_TokenSmarty::render(CRM_Utils_Array::subset($mailContent, ['text', 'html', 'subject']), $params['tokenContext'], $params['tplParams']);
358 if (isset($rendered['subject'])) {
359 $rendered['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $rendered['subject']));
360 }
361 $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL];
362 $mailContent = array_merge($nullSet, $mailContent, $rendered);
363
364 // send the template, honouring the target user’s preferences (if any)
365 $sent = FALSE;
366
367 // create the params array
368 $params['subject'] = $mailContent['subject'];
369 $params['text'] = $mailContent['text'];
370 $params['html'] = $mailContent['html'];
371
372 if ($params['toEmail']) {
373 // @todo - consider whether we really should be loading
374 // this based on 'the first email in the db that matches'.
375 // when we likely have the contact id. OTOH people probably barely
376 // use preferredMailFormat these days - the good fight against html
377 // emails was lost a decade ago...
378 $preferredMailFormatArray = Email::get(FALSE)->addWhere('email', '=', $params['toEmail'])->addSelect('contact_id.preferred_mail_format')->execute()->first();
379 $preferredMailFormat = $preferredMailFormatArray['contact_id.preferred_mail_format'] ?? 'Both';
380
381 if ($preferredMailFormat === 'HTML') {
382 $params['text'] = NULL;
383 }
384 if ($preferredMailFormat === 'Text') {
385 $params['html'] = NULL;
386 }
387
388 $config = CRM_Core_Config::singleton();
389 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
390 // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId.
391 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
392 if (empty($params['attachments'])) {
393 $params['attachments'] = [];
394 }
395 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
396 }
397 $pdf_filename = '';
398 if ($config->doNotAttachPDFReceipt &&
399 $params['PDFFilename'] &&
400 $params['html']
401 ) {
402 if (empty($params['attachments'])) {
403 $params['attachments'] = [];
404 }
405 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
406 if (isset($params['tplParams']['email_comment'])) {
407 $params['html'] = $params['tplParams']['email_comment'];
408 $params['text'] = strip_tags($params['tplParams']['email_comment']);
409 }
410 }
411
412 $sent = CRM_Utils_Mail::send($params);
413
414 if ($pdf_filename) {
415 unlink($pdf_filename);
416 }
417 }
418
419 return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
420 }
421
422 /**
423 * Create a map between workflow_name and workflow_id.
424 *
425 * @return array
426 * Array(string $workflowName => int $workflowId)
427 */
428 protected static function getWorkflowNameIdMap() {
429 // There's probably some more clever way to do this, but this seems simple.
430 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', [
431 1 => ['msg_tpl_workflow_%', 'String'],
432 ])->fetchMap('name', 'id');
433 }
434
435 /**
436 * Load the specified template.
437 *
438 * @param string $workflowName
439 * @param bool $isTest
440 * @param int|null $messageTemplateID
441 * @param string $groupName
442 * @param array|null $messageTemplateOverride
443 * Optionally, record with msg_subject, msg_text, msg_html.
444 * If omitted, the record will be loaded from workflowName/messageTemplateID.
445 * @param string|null $subjectOverride
446 * This option is the older, wonkier version of $messageTemplate['msg_subject']...
447 *
448 * @return array
449 * @throws \API_Exception
450 * @throws \CRM_Core_Exception
451 */
452 protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL, ?array $messageTemplateOverride = NULL, ?string $subjectOverride = NULL): array {
453 $base = ['msg_subject' => NULL, 'msg_text' => NULL, 'msg_html' => NULL, 'pdf_format_id' => NULL];
454 if (!$workflowName && !$messageTemplateID) {
455 throw new CRM_Core_Exception(ts("Message template's option value or ID missing."));
456 }
457
458 $apiCall = MessageTemplate::get(FALSE)
459 ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id')
460 ->addWhere('is_default', '=', 1);
461
462 if ($messageTemplateID) {
463 $apiCall->addWhere('id', '=', (int) $messageTemplateID);
464 }
465 else {
466 $apiCall->addWhere('workflow_name', '=', $workflowName);
467 }
468 $messageTemplate = array_merge($base, $apiCall->execute()->first() ?: [], $messageTemplateOverride ?: []);
469 if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) {
470 if ($messageTemplateID) {
471 throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID]));
472 }
473 throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName]));
474 }
475
476 $mailContent = [
477 'subject' => $messageTemplate['msg_subject'],
478 'text' => $messageTemplate['msg_text'],
479 'html' => $messageTemplate['msg_html'],
480 'format' => $messageTemplate['pdf_format_id'],
481 // Workflow name is the field in the message templates table that denotes the
482 // workflow the template is used for. This is intended to eventually
483 // replace the non-standard option value/group implementation - see
484 // https://github.com/civicrm/civicrm-core/pull/17227 and the longer
485 // discussion on https://github.com/civicrm/civicrm-core/pull/17180
486 'workflow_name' => $workflowName,
487 // Note messageTemplateID is the id but when present we also know it was specifically requested.
488 'messageTemplateID' => $messageTemplateID,
489 // Group name & valueName are deprecated parameters. At some point it will not be passed out.
490 // https://github.com/civicrm/civicrm-core/pull/17180
491 'groupName' => $groupName,
492 'valueName' => $workflowName,
493 ];
494
495 CRM_Utils_Hook::alterMailContent($mailContent);
496
497 // add the test banner (if requested)
498 if ($isTest) {
499 $testText = MessageTemplate::get(FALSE)
500 ->setSelect(['msg_subject', 'msg_text', 'msg_html'])
501 ->addWhere('workflow_name', '=', 'test_preview')
502 ->addWhere('is_default', '=', TRUE)
503 ->execute()->first();
504
505 $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject'];
506 $mailContent['text'] = $testText['msg_text'] . $mailContent['text'];
507 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']);
508 }
509
510 if (!empty($subjectOverride)) {
511 CRM_Core_Error::deprecatedWarning('CRM_Core_BAO_MessageTemplate: $params[subject] is deprecated. Use $params[messageTemplate][msg_subject] instead.');
512 $mailContent['subject'] = $subjectOverride;
513 }
514
515 return $mailContent;
516 }
517
518 }