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 | |
12838694 | 333 | self::synchronizeLegacyParameters($params); |
b7ade3e0 | 334 | |
3dccbd4b | 335 | // Allow WorkflowMessage to run any filters/mappings/cleanups. |
b7ade3e0 | 336 | $model = $params['model'] ?? WorkflowMessage::create($params['workflow'] ?? 'UNKNOWN'); |
3dccbd4b TO |
337 | $params = WorkflowMessage::exportAll(WorkflowMessage::importAll($model, $params)); |
338 | unset($params['model']); | |
339 | // 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']). | |
340 | // If you want to expose the model via hook, consider interjecting a new Hook::alterWorkflowMessage($model) between `importAll()` and `exportAll()`. | |
341 | ||
12838694 | 342 | self::synchronizeLegacyParameters($params); |
3ace1ae5 | 343 | $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params); |
4335f229 | 344 | |
ededcdab | 345 | CRM_Utils_Hook::alterMailParams($params, 'messageTemplate'); |
e2615a28 | 346 | $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '', $params['messageTemplate'], $params['subject'] ?? NULL); |
c8025280 | 347 | |
12838694 | 348 | self::synchronizeLegacyParameters($params); |
3151fc5d TO |
349 | $rendered = CRM_Core_TokenSmarty::render(CRM_Utils_Array::subset($mailContent, ['text', 'html', 'subject']), $params['tokenContext'], $params['tplParams']); |
350 | if (isset($rendered['subject'])) { | |
351 | $rendered['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $rendered['subject'])); | |
352 | } | |
353 | $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL]; | |
bd010d53 TO |
354 | $mailContent = array_merge($nullSet, $mailContent, $rendered); |
355 | return [$mailContent, $params]; | |
fd0e4bde | 356 | } |
4ee279f4 | 357 | |
12838694 EM |
358 | /** |
359 | * Some params have been deprecated/renamed. Synchronize old<=>new params. | |
360 | * | |
361 | * We periodically resync after exchanging data with other parties. | |
362 | * | |
363 | * @param array $params | |
364 | */ | |
365 | private static function synchronizeLegacyParameters(&$params) { | |
366 | CRM_Utils_Array::pathSync($params, ['workflow'], ['valueName']); | |
367 | CRM_Utils_Array::pathSync($params, ['tokenContext', 'contactId'], ['contactId']); | |
368 | CRM_Utils_Array::pathSync($params, ['tokenContext', 'smarty'], ['disableSmarty'], function ($v, bool $isCanon) { | |
369 | return !$v; | |
370 | }); | |
371 | ||
372 | // Core#644 - handle Email ID passed as "From". | |
373 | if (isset($params['from'])) { | |
374 | $params['from'] = \CRM_Utils_Mail::formatFromAddress($params['from']); | |
375 | } | |
376 | } | |
377 | ||
fd0e4bde EM |
378 | /** |
379 | * Send an email from the specified template based on an array of params. | |
380 | * | |
381 | * @param array $params | |
382 | * A string-keyed array of function params, see function body for details. | |
383 | * | |
384 | * @return array | |
385 | * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates | |
386 | * @throws \CRM_Core_Exception | |
387 | * @throws \API_Exception | |
388 | */ | |
d3e8674a EM |
389 | public static function sendTemplate(array $params): array { |
390 | // Handle isEmailPdf here as the unit test on that function deems it 'non-conforming'. | |
391 | $isAttachPDF = !empty($params['isEmailPdf']); | |
392 | unset($params['isEmailPdf']); | |
bd010d53 TO |
393 | [$mailContent, $params] = self::renderTemplateRaw($params); |
394 | ||
395 | // create the params array | |
396 | $params['subject'] = $mailContent['subject']; | |
397 | $params['text'] = $mailContent['text']; | |
398 | $params['html'] = $mailContent['html']; | |
399 | ||
6a488035 TO |
400 | // send the template, honouring the target user’s preferences (if any) |
401 | $sent = FALSE; | |
fd0e4bde | 402 | if (!empty($params['toEmail'])) { |
6a488035 TO |
403 | |
404 | $config = CRM_Core_Config::singleton(); | |
d3e8674a | 405 | if ($isAttachPDF) { |
3ace1ae5 | 406 | // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId. |
d141946b | 407 | $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']); |
9161952c | 408 | if (empty($params['attachments'])) { |
be2fb01f | 409 | $params['attachments'] = []; |
9161952c | 410 | } |
bd010d53 | 411 | $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']); |
9161952c | 412 | } |
6a488035 TO |
413 | $pdf_filename = ''; |
414 | if ($config->doNotAttachPDFReceipt && | |
415 | $params['PDFFilename'] && | |
416 | $params['html'] | |
417 | ) { | |
6a488035 | 418 | if (empty($params['attachments'])) { |
be2fb01f | 419 | $params['attachments'] = []; |
6a488035 | 420 | } |
14bf6806 | 421 | $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']); |
9849720e RK |
422 | if (isset($params['tplParams']['email_comment'])) { |
423 | $params['html'] = $params['tplParams']['email_comment']; | |
d9e4ebe7 | 424 | $params['text'] = strip_tags($params['tplParams']['email_comment']); |
9849720e | 425 | } |
6a488035 TO |
426 | } |
427 | ||
428 | $sent = CRM_Utils_Mail::send($params); | |
429 | ||
430 | if ($pdf_filename) { | |
431 | unlink($pdf_filename); | |
432 | } | |
433 | } | |
434 | ||
bd010d53 | 435 | return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']]; |
6a488035 | 436 | } |
96025800 | 437 | |
0c5781ae TO |
438 | /** |
439 | * Create a map between workflow_name and workflow_id. | |
440 | * | |
441 | * @return array | |
442 | * Array(string $workflowName => int $workflowId) | |
443 | */ | |
444 | protected static function getWorkflowNameIdMap() { | |
445 | // There's probably some more clever way to do this, but this seems simple. | |
446 | 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', [ | |
447 | 1 => ['msg_tpl_workflow_%', 'String'], | |
448 | ])->fetchMap('name', 'id'); | |
449 | } | |
450 | ||
a4965e0c | 451 | /** |
452 | * Load the specified template. | |
453 | * | |
454 | * @param string $workflowName | |
455 | * @param bool $isTest | |
456 | * @param int|null $messageTemplateID | |
457 | * @param string $groupName | |
e2615a28 TO |
458 | * @param array|null $messageTemplateOverride |
459 | * Optionally, record with msg_subject, msg_text, msg_html. | |
460 | * If omitted, the record will be loaded from workflowName/messageTemplateID. | |
461 | * @param string|null $subjectOverride | |
462 | * This option is the older, wonkier version of $messageTemplate['msg_subject']... | |
a4965e0c | 463 | * |
464 | * @return array | |
465 | * @throws \API_Exception | |
466 | * @throws \CRM_Core_Exception | |
467 | */ | |
e2615a28 TO |
468 | protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL, ?array $messageTemplateOverride = NULL, ?string $subjectOverride = NULL): array { |
469 | $base = ['msg_subject' => NULL, 'msg_text' => NULL, 'msg_html' => NULL, 'pdf_format_id' => NULL]; | |
a4965e0c | 470 | if (!$workflowName && !$messageTemplateID) { |
471 | throw new CRM_Core_Exception(ts("Message template's option value or ID missing.")); | |
472 | } | |
473 | ||
474 | $apiCall = MessageTemplate::get(FALSE) | |
475 | ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id') | |
476 | ->addWhere('is_default', '=', 1); | |
477 | ||
478 | if ($messageTemplateID) { | |
479 | $apiCall->addWhere('id', '=', (int) $messageTemplateID); | |
480 | } | |
481 | else { | |
482 | $apiCall->addWhere('workflow_name', '=', $workflowName); | |
483 | } | |
e2615a28 TO |
484 | $messageTemplate = array_merge($base, $apiCall->execute()->first() ?: [], $messageTemplateOverride ?: []); |
485 | if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) { | |
a4965e0c | 486 | if ($messageTemplateID) { |
487 | throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID])); | |
488 | } | |
e2615a28 | 489 | throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName])); |
a4965e0c | 490 | } |
491 | ||
492 | $mailContent = [ | |
493 | 'subject' => $messageTemplate['msg_subject'], | |
494 | 'text' => $messageTemplate['msg_text'], | |
495 | 'html' => $messageTemplate['msg_html'], | |
496 | 'format' => $messageTemplate['pdf_format_id'], | |
87c4c149 | 497 | // Workflow name is the field in the message templates table that denotes the |
498 | // workflow the template is used for. This is intended to eventually | |
499 | // replace the non-standard option value/group implementation - see | |
500 | // https://github.com/civicrm/civicrm-core/pull/17227 and the longer | |
501 | // discussion on https://github.com/civicrm/civicrm-core/pull/17180 | |
a4965e0c | 502 | 'workflow_name' => $workflowName, |
503 | // Note messageTemplateID is the id but when present we also know it was specifically requested. | |
504 | 'messageTemplateID' => $messageTemplateID, | |
505 | // Group name & valueName are deprecated parameters. At some point it will not be passed out. | |
506 | // https://github.com/civicrm/civicrm-core/pull/17180 | |
507 | 'groupName' => $groupName, | |
508 | 'valueName' => $workflowName, | |
509 | ]; | |
510 | ||
511 | CRM_Utils_Hook::alterMailContent($mailContent); | |
512 | ||
513 | // add the test banner (if requested) | |
514 | if ($isTest) { | |
515 | $testText = MessageTemplate::get(FALSE) | |
516 | ->setSelect(['msg_subject', 'msg_text', 'msg_html']) | |
517 | ->addWhere('workflow_name', '=', 'test_preview') | |
518 | ->addWhere('is_default', '=', TRUE) | |
519 | ->execute()->first(); | |
520 | ||
521 | $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject']; | |
522 | $mailContent['text'] = $testText['msg_text'] . $mailContent['text']; | |
523 | $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']); | |
524 | } | |
525 | ||
e2615a28 TO |
526 | if (!empty($subjectOverride)) { |
527 | CRM_Core_Error::deprecatedWarning('CRM_Core_BAO_MessageTemplate: $params[subject] is deprecated. Use $params[messageTemplate][msg_subject] instead.'); | |
528 | $mailContent['subject'] = $subjectOverride; | |
529 | } | |
530 | ||
a4965e0c | 531 | return $mailContent; |
532 | } | |
533 | ||
6a488035 | 534 | } |