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 | ||
965ff8f1 | 18 | use Civi\Api4\Email; |
c4d7103b | 19 | use Civi\Api4\MessageTemplate; |
3dccbd4b | 20 | use Civi\WorkflowMessage\WorkflowMessage; |
c4d7103b | 21 | |
6a488035 | 22 | require_once 'Mail/mime.php'; |
b5c2afd0 EM |
23 | |
24 | /** | |
8eedd10a | 25 | * Class CRM_Core_BAO_MessageTemplate. |
b5c2afd0 | 26 | */ |
c6327d7d | 27 | class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate { |
6a488035 TO |
28 | |
29 | /** | |
fe482240 | 30 | * Fetch object based on array of properties. |
6a488035 | 31 | * |
6a0b768e TO |
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. | |
6a488035 | 36 | * |
8f86a9e5 | 37 | * @return CRM_Core_DAO_MessageTemplate |
6a488035 | 38 | */ |
00be9182 | 39 | public static function retrieve(&$params, &$defaults) { |
c6327d7d | 40 | $messageTemplates = new CRM_Core_DAO_MessageTemplate(); |
6a488035 TO |
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 | /** | |
fe482240 | 50 | * Update the is_active flag in the db. |
6a488035 | 51 | * |
6a0b768e TO |
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. | |
6a488035 | 56 | * |
8a4fede3 | 57 | * @return bool |
58 | * true if we found and updated the object, else false | |
6a488035 | 59 | */ |
00be9182 | 60 | public static function setIsActive($id, $is_active) { |
c6327d7d | 61 | return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active); |
6a488035 TO |
62 | } |
63 | ||
64 | /** | |
fe482240 | 65 | * Add the Message Templates. |
6a488035 | 66 | * |
6a0b768e TO |
67 | * @param array $params |
68 | * Reference array contains the values submitted by the form. | |
6a488035 | 69 | * |
6a488035 TO |
70 | * |
71 | * @return object | |
8f86a9e5 | 72 | * @throws \CiviCRM_API3_Exception |
73 | * @throws \Civi\API\Exception\UnauthorizedException | |
6a488035 | 74 | */ |
00be9182 | 75 | public static function add(&$params) { |
781ed314 SL |
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']]); | |
0c5781ae | 84 | if (!empty($details['workflow_id']) || !empty($details['workflow_name'])) { |
781ed314 SL |
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 { | |
0c5781ae | 94 | if (!empty($params['workflow_id']) || !empty($params['workflow_name'])) { |
36111e9f SL |
95 | if (!CRM_Core_Permission::check('edit system workflow message templates')) { |
96 | throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage])); | |
97 | } | |
781ed314 | 98 | } |
36111e9f | 99 | elseif (!CRM_Core_Permission::check('edit user-driven message templates')) { |
781ed314 SL |
100 | throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage])); |
101 | } | |
102 | } | |
103 | } | |
104 | } | |
3c8059c8 KM |
105 | $hook = empty($params['id']) ? 'create' : 'edit'; |
106 | CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params); | |
c39c0aa1 | 107 | |
90a73810 | 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 | ||
0c5781ae TO |
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 | ||
c6327d7d | 138 | $messageTemplates = new CRM_Core_DAO_MessageTemplate(); |
6a488035 | 139 | $messageTemplates->copyValues($params); |
6a488035 | 140 | $messageTemplates->save(); |
c39c0aa1 | 141 | |
90a73810 | 142 | if (!empty($fileParams)) { |
143 | $params['file_id'] = $fileParams; | |
04a76231 | 144 | CRM_Core_BAO_File::filePostProcess( |
90a73810 | 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 | ); | |
90a73810 | 155 | } |
156 | ||
c9606a53 | 157 | CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates); |
6a488035 TO |
158 | return $messageTemplates; |
159 | } | |
160 | ||
161 | /** | |
fe482240 | 162 | * Delete the Message Templates. |
6a488035 | 163 | * |
100fef9d | 164 | * @param int $messageTemplatesID |
8f86a9e5 | 165 | * |
166 | * @throws \CRM_Core_Exception | |
6a488035 | 167 | */ |
00be9182 | 168 | public static function del($messageTemplatesID) { |
6a488035 TO |
169 | // make sure messageTemplatesID is an integer |
170 | if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) { | |
8f86a9e5 | 171 | throw new CRM_Core_Exception(ts('Invalid Message template')); |
6a488035 TO |
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"; | |
5f351616 | 178 | |
be2fb01f | 179 | $params = [1 => [$messageTemplatesID, 'Integer']]; |
6a488035 TO |
180 | CRM_Core_DAO::executeQuery($query, $params); |
181 | ||
c6327d7d | 182 | $messageTemplates = new CRM_Core_DAO_MessageTemplate(); |
6a488035 TO |
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 | /** | |
fe482240 | 189 | * Get the Message Templates. |
6a488035 | 190 | * |
6a488035 | 191 | * |
dd244018 EM |
192 | * @param bool $all |
193 | * | |
ad37ac8e | 194 | * @param bool $isSMS |
195 | * | |
8f86a9e5 | 196 | * @return array |
6a488035 | 197 | */ |
00be9182 | 198 | public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) { |
be2fb01f | 199 | $msgTpls = []; |
6a488035 | 200 | |
c6327d7d | 201 | $messageTemplates = new CRM_Core_DAO_MessageTemplate(); |
6a488035 | 202 | $messageTemplates->is_active = 1; |
1e035d58 | 203 | $messageTemplates->is_sms = $isSMS; |
6a488035 TO |
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 | ||
6a488035 | 216 | /** |
8eedd10a | 217 | * Revert a message template to its default subject+text+HTML state. |
6a488035 | 218 | * |
608e6658 | 219 | * @param int $id id of the template |
8f86a9e5 | 220 | * |
221 | * @throws \CRM_Core_Exception | |
6a488035 | 222 | */ |
00be9182 | 223 | public static function revert($id) { |
608e6658 | 224 | $diverted = new CRM_Core_BAO_MessageTemplate(); |
6a488035 TO |
225 | $diverted->id = (int) $id; |
226 | $diverted->find(1); | |
227 | ||
228 | if ($diverted->N != 1) { | |
8f86a9e5 | 229 | throw new CRM_Core_Exception(ts('Did not find a message template with id of %1.', [1 => $id])); |
6a488035 TO |
230 | } |
231 | ||
608e6658 | 232 | $orig = new CRM_Core_BAO_MessageTemplate(); |
6a488035 TO |
233 | $orig->workflow_id = $diverted->workflow_id; |
234 | $orig->is_reserved = 1; | |
235 | $orig->find(1); | |
236 | ||
237 | if ($orig->N != 1) { | |
8f86a9e5 | 238 | throw new CRM_Core_Exception(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id])); |
6a488035 TO |
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 | ||
fa78ca24 TO |
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) { | |
bd010d53 TO |
265 | [$mailContent, $params] = self::renderTemplateRaw($params); |
266 | return CRM_Utils_Array::subset($mailContent, ['subject', 'text', 'html']); | |
267 | } | |
268 | ||
269 | /** | |
270 | * Render a message template. | |
271 | * | |
272 | * @param array $params | |
273 | * Mixed render parameters. See sendTemplate() for more details. | |
274 | * @return array | |
275 | * Tuple of [$mailContent, $updatedParams]. | |
276 | * @throws \API_Exception | |
277 | * @throws \CRM_Core_Exception | |
278 | * @see sendTemplate() | |
279 | */ | |
280 | protected static function renderTemplateRaw($params) { | |
3ace1ae5 | 281 | $modelDefaults = [ |
3dccbd4b TO |
282 | // instance of WorkflowMessageInterface, containing a list of data to provide to the message-template |
283 | 'model' => NULL, | |
3ace1ae5 | 284 | // Symbolic name of the workflow step. Matches the option-value-name of the template. |
6a488035 | 285 | 'valueName' => NULL, |
6a488035 | 286 | // additional template params (other than the ones already set in the template singleton) |
be2fb01f | 287 | 'tplParams' => [], |
0238a01e | 288 | // additional token params (passed to the TokenProcessor) |
7a46f8e3 | 289 | // INTERNAL: 'tokenContext' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs. |
0238a01e | 290 | 'tokenContext' => [], |
3ace1ae5 TO |
291 | // properties to import directly to the model object |
292 | 'modelProps' => NULL, | |
293 | // contact id if contact tokens are to be replaced; alias for tokenContext.contactId | |
294 | 'contactId' => NULL, | |
295 | ]; | |
296 | $viewDefaults = [ | |
297 | // ID of the specific template to load | |
298 | 'messageTemplateID' => NULL, | |
299 | // content of the message template | |
300 | // Ex: ['msg_subject' => 'Hello {contact.display_name}', 'msg_html' => '...', 'msg_text' => '...'] | |
301 | // INTERNAL: 'messageTemplate' is currently only intended for use within civicrm-core only. For downstream usage, future updates will provide comparable public APIs. | |
302 | 'messageTemplate' => NULL, | |
303 | // whether this is a test email (and hence should include the test banner) | |
304 | 'isTest' => FALSE, | |
305 | // Disable Smarty? | |
306 | 'disableSmarty' => FALSE, | |
307 | ]; | |
308 | $envelopeDefaults = [ | |
6a488035 TO |
309 | // the From: header |
310 | 'from' => NULL, | |
311 | // the recipient’s name | |
312 | 'toName' => NULL, | |
313 | // the recipient’s email - mail is sent only if set | |
314 | 'toEmail' => NULL, | |
315 | // the Cc: header | |
316 | 'cc' => NULL, | |
317 | // the Bcc: header | |
318 | 'bcc' => NULL, | |
319 | // the Reply-To: header | |
320 | 'replyTo' => NULL, | |
321 | // email attachments | |
322 | 'attachments' => NULL, | |
6a488035 TO |
323 | // filename of optional PDF version to add as attachment (do not include path) |
324 | 'PDFFilename' => NULL, | |
be2fb01f | 325 | ]; |
6a488035 | 326 | |
b7ade3e0 TO |
327 | // Some params have been deprecated/renamed. Synchronize old<=>new params. We periodically resync after exchanging data with other parties. |
328 | $sync = function () use (&$params, $modelDefaults, $viewDefaults) { | |
329 | CRM_Utils_Array::pathSync($params, ['workflow'], ['valueName']); | |
330 | CRM_Utils_Array::pathSync($params, ['tokenContext', 'contactId'], ['contactId']); | |
331 | CRM_Utils_Array::pathSync($params, ['tokenContext', 'smarty'], ['disableSmarty'], function ($v, bool $isCanon) { | |
332 | return !$v; | |
333 | }); | |
334 | ||
335 | // Core#644 - handle Email ID passed as "From". | |
336 | if (isset($params['from'])) { | |
337 | $params['from'] = \CRM_Utils_Mail::formatFromAddress($params['from']); | |
338 | } | |
339 | }; | |
340 | $sync(); | |
341 | ||
3dccbd4b | 342 | // Allow WorkflowMessage to run any filters/mappings/cleanups. |
b7ade3e0 | 343 | $model = $params['model'] ?? WorkflowMessage::create($params['workflow'] ?? 'UNKNOWN'); |
3dccbd4b TO |
344 | $params = WorkflowMessage::exportAll(WorkflowMessage::importAll($model, $params)); |
345 | unset($params['model']); | |
346 | // 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']). | |
347 | // If you want to expose the model via hook, consider interjecting a new Hook::alterWorkflowMessage($model) between `importAll()` and `exportAll()`. | |
348 | ||
b7ade3e0 | 349 | $sync(); |
3ace1ae5 | 350 | $params = array_merge($modelDefaults, $viewDefaults, $envelopeDefaults, $params); |
4335f229 | 351 | |
ededcdab | 352 | CRM_Utils_Hook::alterMailParams($params, 'messageTemplate'); |
e2615a28 | 353 | $mailContent = self::loadTemplate((string) $params['valueName'], $params['isTest'], $params['messageTemplateID'] ?? NULL, $params['groupName'] ?? '', $params['messageTemplate'], $params['subject'] ?? NULL); |
c8025280 | 354 | |
b7ade3e0 | 355 | $sync(); |
3151fc5d TO |
356 | $rendered = CRM_Core_TokenSmarty::render(CRM_Utils_Array::subset($mailContent, ['text', 'html', 'subject']), $params['tokenContext'], $params['tplParams']); |
357 | if (isset($rendered['subject'])) { | |
358 | $rendered['subject'] = trim(preg_replace('/[\r\n]+/', ' ', $rendered['subject'])); | |
359 | } | |
360 | $nullSet = ['subject' => NULL, 'text' => NULL, 'html' => NULL]; | |
bd010d53 TO |
361 | $mailContent = array_merge($nullSet, $mailContent, $rendered); |
362 | return [$mailContent, $params]; | |
fd0e4bde | 363 | } |
4ee279f4 | 364 | |
fd0e4bde EM |
365 | /** |
366 | * Send an email from the specified template based on an array of params. | |
367 | * | |
368 | * @param array $params | |
369 | * A string-keyed array of function params, see function body for details. | |
370 | * | |
371 | * @return array | |
372 | * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates | |
373 | * @throws \CRM_Core_Exception | |
374 | * @throws \API_Exception | |
375 | */ | |
376 | public static function sendTemplate($params) { | |
bd010d53 TO |
377 | [$mailContent, $params] = self::renderTemplateRaw($params); |
378 | ||
379 | // create the params array | |
380 | $params['subject'] = $mailContent['subject']; | |
381 | $params['text'] = $mailContent['text']; | |
382 | $params['html'] = $mailContent['html']; | |
383 | ||
6a488035 TO |
384 | // send the template, honouring the target user’s preferences (if any) |
385 | $sent = FALSE; | |
fd0e4bde | 386 | if (!empty($params['toEmail'])) { |
965ff8f1 EM |
387 | // @todo - consider whether we really should be loading |
388 | // this based on 'the first email in the db that matches'. | |
389 | // when we likely have the contact id. OTOH people probably barely | |
390 | // use preferredMailFormat these days - the good fight against html | |
391 | // emails was lost a decade ago... | |
97b745fe | 392 | $preferredMailFormatArray = Email::get(FALSE)->addWhere('email', '=', $params['toEmail'])->addSelect('contact_id.preferred_mail_format')->execute()->first(); |
393 | $preferredMailFormat = $preferredMailFormatArray['contact_id.preferred_mail_format'] ?? 'Both'; | |
965ff8f1 EM |
394 | |
395 | if ($preferredMailFormat === 'HTML') { | |
6a488035 TO |
396 | $params['text'] = NULL; |
397 | } | |
965ff8f1 | 398 | if ($preferredMailFormat === 'Text') { |
6a488035 TO |
399 | $params['html'] = NULL; |
400 | } | |
401 | ||
402 | $config = CRM_Core_Config::singleton(); | |
9161952c | 403 | if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) { |
3ace1ae5 | 404 | // FIXME: $params['contributionId'] is not modeled in the parameter list. When is it supplied? Should probably move to tokenContext.contributionId. |
d141946b | 405 | $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']); |
9161952c | 406 | if (empty($params['attachments'])) { |
be2fb01f | 407 | $params['attachments'] = []; |
9161952c | 408 | } |
bd010d53 | 409 | $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']); |
9161952c | 410 | } |
6a488035 TO |
411 | $pdf_filename = ''; |
412 | if ($config->doNotAttachPDFReceipt && | |
413 | $params['PDFFilename'] && | |
414 | $params['html'] | |
415 | ) { | |
6a488035 | 416 | if (empty($params['attachments'])) { |
be2fb01f | 417 | $params['attachments'] = []; |
6a488035 | 418 | } |
14bf6806 | 419 | $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']); |
9849720e RK |
420 | if (isset($params['tplParams']['email_comment'])) { |
421 | $params['html'] = $params['tplParams']['email_comment']; | |
d9e4ebe7 | 422 | $params['text'] = strip_tags($params['tplParams']['email_comment']); |
9849720e | 423 | } |
6a488035 TO |
424 | } |
425 | ||
426 | $sent = CRM_Utils_Mail::send($params); | |
427 | ||
428 | if ($pdf_filename) { | |
429 | unlink($pdf_filename); | |
430 | } | |
431 | } | |
432 | ||
bd010d53 | 433 | return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']]; |
6a488035 | 434 | } |
96025800 | 435 | |
0c5781ae TO |
436 | /** |
437 | * Create a map between workflow_name and workflow_id. | |
438 | * | |
439 | * @return array | |
440 | * Array(string $workflowName => int $workflowId) | |
441 | */ | |
442 | protected static function getWorkflowNameIdMap() { | |
443 | // There's probably some more clever way to do this, but this seems simple. | |
444 | 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', [ | |
445 | 1 => ['msg_tpl_workflow_%', 'String'], | |
446 | ])->fetchMap('name', 'id'); | |
447 | } | |
448 | ||
a4965e0c | 449 | /** |
450 | * Load the specified template. | |
451 | * | |
452 | * @param string $workflowName | |
453 | * @param bool $isTest | |
454 | * @param int|null $messageTemplateID | |
455 | * @param string $groupName | |
e2615a28 TO |
456 | * @param array|null $messageTemplateOverride |
457 | * Optionally, record with msg_subject, msg_text, msg_html. | |
458 | * If omitted, the record will be loaded from workflowName/messageTemplateID. | |
459 | * @param string|null $subjectOverride | |
460 | * This option is the older, wonkier version of $messageTemplate['msg_subject']... | |
a4965e0c | 461 | * |
462 | * @return array | |
463 | * @throws \API_Exception | |
464 | * @throws \CRM_Core_Exception | |
465 | */ | |
e2615a28 TO |
466 | protected static function loadTemplate(string $workflowName, bool $isTest, int $messageTemplateID = NULL, $groupName = NULL, ?array $messageTemplateOverride = NULL, ?string $subjectOverride = NULL): array { |
467 | $base = ['msg_subject' => NULL, 'msg_text' => NULL, 'msg_html' => NULL, 'pdf_format_id' => NULL]; | |
a4965e0c | 468 | if (!$workflowName && !$messageTemplateID) { |
469 | throw new CRM_Core_Exception(ts("Message template's option value or ID missing.")); | |
470 | } | |
471 | ||
472 | $apiCall = MessageTemplate::get(FALSE) | |
473 | ->addSelect('msg_subject', 'msg_text', 'msg_html', 'pdf_format_id', 'id') | |
474 | ->addWhere('is_default', '=', 1); | |
475 | ||
476 | if ($messageTemplateID) { | |
477 | $apiCall->addWhere('id', '=', (int) $messageTemplateID); | |
478 | } | |
479 | else { | |
480 | $apiCall->addWhere('workflow_name', '=', $workflowName); | |
481 | } | |
e2615a28 TO |
482 | $messageTemplate = array_merge($base, $apiCall->execute()->first() ?: [], $messageTemplateOverride ?: []); |
483 | if (empty($messageTemplate['id']) && empty($messageTemplateOverride)) { | |
a4965e0c | 484 | if ($messageTemplateID) { |
485 | throw new CRM_Core_Exception(ts('No such message template: id=%1.', [1 => $messageTemplateID])); | |
486 | } | |
e2615a28 | 487 | throw new CRM_Core_Exception(ts('No message template with workflow name %1.', [1 => $workflowName])); |
a4965e0c | 488 | } |
489 | ||
490 | $mailContent = [ | |
491 | 'subject' => $messageTemplate['msg_subject'], | |
492 | 'text' => $messageTemplate['msg_text'], | |
493 | 'html' => $messageTemplate['msg_html'], | |
494 | 'format' => $messageTemplate['pdf_format_id'], | |
87c4c149 | 495 | // Workflow name is the field in the message templates table that denotes the |
496 | // workflow the template is used for. This is intended to eventually | |
497 | // replace the non-standard option value/group implementation - see | |
498 | // https://github.com/civicrm/civicrm-core/pull/17227 and the longer | |
499 | // discussion on https://github.com/civicrm/civicrm-core/pull/17180 | |
a4965e0c | 500 | 'workflow_name' => $workflowName, |
501 | // Note messageTemplateID is the id but when present we also know it was specifically requested. | |
502 | 'messageTemplateID' => $messageTemplateID, | |
503 | // Group name & valueName are deprecated parameters. At some point it will not be passed out. | |
504 | // https://github.com/civicrm/civicrm-core/pull/17180 | |
505 | 'groupName' => $groupName, | |
506 | 'valueName' => $workflowName, | |
507 | ]; | |
508 | ||
509 | CRM_Utils_Hook::alterMailContent($mailContent); | |
510 | ||
511 | // add the test banner (if requested) | |
512 | if ($isTest) { | |
513 | $testText = MessageTemplate::get(FALSE) | |
514 | ->setSelect(['msg_subject', 'msg_text', 'msg_html']) | |
515 | ->addWhere('workflow_name', '=', 'test_preview') | |
516 | ->addWhere('is_default', '=', TRUE) | |
517 | ->execute()->first(); | |
518 | ||
519 | $mailContent['subject'] = $testText['msg_subject'] . $mailContent['subject']; | |
520 | $mailContent['text'] = $testText['msg_text'] . $mailContent['text']; | |
521 | $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testText['msg_html']}", $mailContent['html']); | |
522 | } | |
523 | ||
e2615a28 TO |
524 | if (!empty($subjectOverride)) { |
525 | CRM_Core_Error::deprecatedWarning('CRM_Core_BAO_MessageTemplate: $params[subject] is deprecated. Use $params[messageTemplate][msg_subject] instead.'); | |
526 | $mailContent['subject'] = $subjectOverride; | |
527 | } | |
528 | ||
a4965e0c | 529 | return $mailContent; |
530 | } | |
531 | ||
6a488035 | 532 | } |