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