Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
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 | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | ||
c4d7103b | 18 | use Civi\Api4\MessageTemplate; |
3dccbd4b | 19 | use Civi\WorkflowMessage\WorkflowMessage; |
c4d7103b | 20 | |
6a488035 | 21 | require_once 'Mail/mime.php'; |
b5c2afd0 EM |
22 | |
23 | /** | |
8eedd10a | 24 | * Class CRM_Core_BAO_MessageTemplate. |
b5c2afd0 | 25 | */ |
ee44263e | 26 | class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate implements \Civi\Core\HookInterface { |
6a488035 TO |
27 | |
28 | /** | |
4f940304 | 29 | * Retrieve DB object and copy to defaults array. |
6a488035 | 30 | * |
6a0b768e | 31 | * @param array $params |
4f940304 | 32 | * Array of criteria values. |
6a0b768e | 33 | * @param array $defaults |
4f940304 | 34 | * Array to be populated with found values. |
6a488035 | 35 | * |
4f940304 CW |
36 | * @return self|null |
37 | * The DAO object, if found. | |
38 | * | |
39 | * @deprecated | |
6a488035 | 40 | */ |
4f940304 CW |
41 | public static function retrieve($params, &$defaults) { |
42 | return self::commonRetrieve(self::class, $params, $defaults); | |
6a488035 TO |
43 | } |
44 | ||
45 | /** | |
fe482240 | 46 | * Update the is_active flag in the db. |
6a488035 | 47 | * |
6a0b768e TO |
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. | |
6a488035 | 52 | * |
8a4fede3 | 53 | * @return bool |
54 | * true if we found and updated the object, else false | |
6a488035 | 55 | */ |
00be9182 | 56 | public static function setIsActive($id, $is_active) { |
c6327d7d | 57 | return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active); |
6a488035 TO |
58 | } |
59 | ||
60 | /** | |
fe482240 | 61 | * Add the Message Templates. |
6a488035 | 62 | * |
6a0b768e TO |
63 | * @param array $params |
64 | * Reference array contains the values submitted by the form. | |
6a488035 | 65 | * |
6a488035 TO |
66 | * |
67 | * @return object | |
8f86a9e5 | 68 | * @throws \CiviCRM_API3_Exception |
69 | * @throws \Civi\API\Exception\UnauthorizedException | |
6a488035 | 70 | */ |
00be9182 | 71 | public static function add(&$params) { |
781ed314 SL |
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']]); | |
0c5781ae | 80 | if (!empty($details['workflow_id']) || !empty($details['workflow_name'])) { |
781ed314 SL |
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 { | |
0c5781ae | 90 | if (!empty($params['workflow_id']) || !empty($params['workflow_name'])) { |
36111e9f SL |
91 | if (!CRM_Core_Permission::check('edit system workflow message templates')) { |
92 | throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage])); | |
93 | } | |
781ed314 | 94 | } |
36111e9f | 95 | elseif (!CRM_Core_Permission::check('edit user-driven message templates')) { |
781ed314 SL |
96 | throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage])); |
97 | } | |
98 | } | |
99 | } | |
100 | } | |
3c8059c8 KM |
101 | $hook = empty($params['id']) ? 'create' : 'edit'; |
102 | CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params); | |
c39c0aa1 | 103 | |
90a73810 | 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 | ||
0c5781ae | 109 | // The workflow_id and workflow_name should be sync'd. But what mix of inputs do we have to work with? |
d53da69a TO |
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')) { | |
0c5781ae TO |
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 | ||
c6327d7d | 137 | $messageTemplates = new CRM_Core_DAO_MessageTemplate(); |
6a488035 | 138 | $messageTemplates->copyValues($params); |
6a488035 | 139 | $messageTemplates->save(); |
c39c0aa1 | 140 | |
90a73810 | 141 | if (!empty($fileParams)) { |
142 | $params['file_id'] = $fileParams; | |
04a76231 | 143 | CRM_Core_BAO_File::filePostProcess( |
90a73810 | 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 | ); | |
90a73810 | 154 | } |
155 | ||
c9606a53 | 156 | CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates); |
6a488035 TO |
157 | return $messageTemplates; |
158 | } | |
159 | ||
160 | /** | |
fe482240 | 161 | * Delete the Message Templates. |
6a488035 | 162 | * |
100fef9d | 163 | * @param int $messageTemplatesID |
ec7e0f40 | 164 | * @deprecated |
8f86a9e5 | 165 | * @throws \CRM_Core_Exception |
6a488035 | 166 | */ |
00be9182 | 167 | public static function del($messageTemplatesID) { |
6a488035 TO |
168 | // make sure messageTemplatesID is an integer |
169 | if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) { | |
8f86a9e5 | 170 | throw new CRM_Core_Exception(ts('Invalid Message template')); |
6a488035 TO |
171 | } |
172 | ||
ec7e0f40 CW |
173 | static::deleteRecord(['id' => $messageTemplatesID]); |
174 | // Yikes - bad idea setting status messages in BAO CRUD functions. Don't do this. | |
6a488035 TO |
175 | CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success'); |
176 | } | |
177 | ||
ec7e0f40 CW |
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 | ||
6a488035 | 194 | /** |
fe482240 | 195 | * Get the Message Templates. |
6a488035 | 196 | * |
6a488035 | 197 | * |
dd244018 EM |
198 | * @param bool $all |
199 | * | |
ad37ac8e | 200 | * @param bool $isSMS |
201 | * | |
8f86a9e5 | 202 | * @return array |
6a488035 | 203 | */ |
00be9182 | 204 | public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) { |
be2fb01f | 205 | $msgTpls = []; |
6a488035 | 206 | |
c6327d7d | 207 | $messageTemplates = new CRM_Core_DAO_MessageTemplate(); |
6a488035 | 208 | $messageTemplates->is_active = 1; |
1e035d58 | 209 | $messageTemplates->is_sms = $isSMS; |
6a488035 TO |
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 | ||
6a488035 | 222 | /** |
8eedd10a | 223 | * Revert a message template to its default subject+text+HTML state. |
6a488035 | 224 | * |
608e6658 | 225 | * @param int $id id of the template |
8f86a9e5 | 226 | * |
227 | * @throws \CRM_Core_Exception | |
6a488035 | 228 | */ |
00be9182 | 229 | public static function revert($id) { |
608e6658 | 230 | $diverted = new CRM_Core_BAO_MessageTemplate(); |
6a488035 TO |
231 | $diverted->id = (int) $id; |
232 | $diverted->find(1); | |
233 | ||
234 | if ($diverted->N != 1) { | |
8f86a9e5 | 235 | throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id])); |
6a488035 TO |
236 | } |
237 | ||
608e6658 | 238 | $orig = new CRM_Core_BAO_MessageTemplate(); |
c46ba93e | 239 | $orig->workflow_name = $diverted->workflow_name; |
6a488035 TO |
240 | $orig->is_reserved = 1; |
241 | $orig->find(1); | |
242 | ||
243 | if ($orig->N != 1) { | |
8f86a9e5 | 244 | throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id])); |
6a488035 TO |
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 | ||
fa78ca24 TO |
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) { | |
bd010d53 TO |
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) { | |
3ace1ae5 | 287 | $modelDefaults = [ |
3dccbd4b TO |
288 | // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template |
289 | 'model' => NULL, | |
3ace1ae5 | 290 | // Symbolic name of the workflow step. Matches the option-value-name of the template. |
6a488035 | 291 | 'valueName' => NULL, |
6a488035 | 292 | // additional template params (other than the ones already set in the template singleton) |
be2fb01f | 293 | 'tplParams' => [], |
0238a01e | 294 | // additional token params (passed to the TokenProcessor) |
7a46f8e3 | 295 | // INTERNAL: 'tokenContext' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs. |
0238a01e | 296 | 'tokenContext' => [], |
3ace1ae5 TO |
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 = [ | |
6a488035 TO |
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, | |
6a488035 TO |
329 | // filename of optional PDF version to add as attachment (do not include path) |
330 | 'PDFFilename' => NULL, | |
be2fb01f | 331 | ]; |
6a488035 | 332 | |
b7ade3e0 TO |
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 | ||
3dccbd4b | 348 | // Allow WorkflowMessage to run any filters/mappings/cleanups. |
b7ade3e0 | 349 | $model = $params['model'] ?? WorkflowMessage::create($params['workflow'] ?? 'UNKNOWN'); |
3dccbd4b TO |
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 | ||
b7ade3e0 | 355 | $sync(); |
3ace1ae5 | 356 | $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params); |
4335f229 | 357 | |
ededcdab | 358 | CRM_Utils_Hook::alterMailParams($params, 'messageTemplate'); |
e2615a28 | 359 | $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '', $params['messageTemplate'], $params['subject'] ?? NULL); |
c8025280 | 360 | |
b7ade3e0 | 361 | $sync(); |
3151fc5d TO |
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]; | |
bd010d53 TO |
367 | $mailContent = array_merge($nullSet, $mailContent, $rendered); |
368 | return [$mailContent, $params]; | |
fd0e4bde | 369 | } |
4ee279f4 | 370 | |
fd0e4bde EM |
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 | */ | |
d3e8674a EM |
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']); | |
bd010d53 TO |
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 | ||
6a488035 TO |
393 | // send the template, honouring the target user’s preferences (if any) |
394 | $sent = FALSE; | |
fd0e4bde | 395 | if (!empty($params['toEmail'])) { |
6a488035 TO |
396 | |
397 | $config = CRM_Core_Config::singleton(); | |
d3e8674a | 398 | if ($isAttachPDF) { |
3ace1ae5 | 399 | // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId. |
d141946b | 400 | $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']); |
9161952c | 401 | if (empty($params['attachments'])) { |
be2fb01f | 402 | $params['attachments'] = []; |
9161952c | 403 | } |
bd010d53 | 404 | $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']); |
9161952c | 405 | } |
6a488035 TO |
406 | $pdf_filename = ''; |
407 | if ($config->doNotAttachPDFReceipt && | |
408 | $params['PDFFilename'] && | |
409 | $params['html'] | |
410 | ) { | |
6a488035 | 411 | if (empty($params['attachments'])) { |
be2fb01f | 412 | $params['attachments'] = []; |
6a488035 | 413 | } |
14bf6806 | 414 | $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']); |
9849720e RK |
415 | if (isset($params['tplParams']['email_comment'])) { |
416 | $params['html'] = $params['tplParams']['email_comment']; | |
d9e4ebe7 | 417 | $params['text'] = strip_tags($params['tplParams']['email_comment']); |
9849720e | 418 | } |
6a488035 TO |
419 | } |
420 | ||
421 | $sent = CRM_Utils_Mail::send($params); | |
422 | ||
423 | if ($pdf_filename) { | |
424 | unlink($pdf_filename); | |
425 | } | |
426 | } | |
427 | ||
bd010d53 | 428 | return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']]; |
6a488035 | 429 | } |
96025800 | 430 | |
0c5781ae TO |
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 | ||
a4965e0c | 444 | /** |
445 | * Load the specified template. | |
446 | * | |
447 | * @param string $workflowName | |
448 | * @param bool $isTest | |
449 | * @param int|null $messageTemplateID | |
450 | * @param string $groupName | |
e2615a28 TO |
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']... | |
a4965e0c | 456 | * |
457 | * @return array | |
458 | * @throws \API_Exception | |
459 | * @throws \CRM_Core_Exception | |
460 | */ | |
e2615a28 TO |
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]; | |
a4965e0c | 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 | } | |
e2615a28 TO |
477 | $messageTemplate = array_merge($base, $apiCall->execute()->first() ?: [], $messageTemplateOverride ?: []); |
478 | if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) { | |
a4965e0c | 479 | if ($messageTemplateID) { |
480 | throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID])); | |
481 | } | |
e2615a28 | 482 | throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName])); |
a4965e0c | 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'], | |
87c4c149 | 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 | |
a4965e0c | 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 | ||
e2615a28 TO |
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 | ||
a4965e0c | 524 | return $mailContent; |
525 | } | |
526 | ||
6a488035 | 527 | } |