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