Merge pull request #24148 from civicrm/5.52
[civicrm-core.git] / CRM / Admin / Form / ScheduleReminders.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for Scheduling Reminders.
20 */
21 class CRM_Admin_Form_ScheduleReminders extends CRM_Admin_Form {
22
23 /**
24 * Scheduled Reminder ID.
25 * @var int
26 */
27 public $_id;
28
29 public $_freqUnits;
30
31 protected $_compId;
32
33 /**
34 * @return mixed
35 */
36 public function getComponentID() {
37 return $this->_compId;
38 }
39
40 /**
41 * @param mixed $compId
42 */
43 public function setComponentID($compId): void {
44 $this->_compId = $compId;
45 }
46
47 /**
48 * Build the form object.
49 *
50 * @throws \CRM_Core_Exception
51 * @throws \CiviCRM_API3_Exception
52 */
53 public function buildQuickForm(): void {
54 parent::buildQuickForm();
55 $this->_mappingID = $mappingID = NULL;
56 $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
57 $this->setContext();
58 $isEvent = $this->getContext() === 'event';
59
60 if ($isEvent) {
61 $this->setComponentID(CRM_Utils_Request::retrieve('compId', 'Integer', $this));
62 if (!CRM_Event_BAO_Event::checkPermission((int) $this->getComponentID(), CRM_Core_Permission::EDIT)) {
63 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
64 }
65 }
66 elseif (!CRM_Core_Permission::check('administer CiviCRM')) {
67 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
68 }
69
70 if ($this->_action & (CRM_Core_Action::DELETE)) {
71 $reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
72 $this->assign('reminderName', $reminderName);
73 return;
74 }
75 elseif ($this->_action & (CRM_Core_Action::UPDATE)) {
76 $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
77 }
78 if ($isEvent) {
79 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->getComponentID(), 'is_template');
80 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
81 'id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
82 ]));
83 if ($mapping) {
84 $this->_mappingID = $mapping->getId();
85 }
86 else {
87 throw new CRM_Core_Exception('Could not find mapping for event scheduled reminders.');
88 }
89 }
90
91 if (!empty($_POST) && !empty($_POST['entity']) && empty($this->getContext())) {
92 $mappingID = $_POST['entity'][0];
93 }
94 elseif ($this->_mappingID) {
95 $mappingID = $this->_mappingID;
96 if ($isEvent) {
97 $this->add('hidden', 'mappingID', $mappingID);
98 }
99 }
100
101 $this->add(
102 'text',
103 'title',
104 ts('Title'),
105 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'title'),
106 TRUE
107 );
108
109 $mappings = CRM_Core_BAO_ActionSchedule::getMappings();
110 $selectedMapping = $mappings[$mappingID ? $mappingID : 1];
111 $entityRecipientLabels = $selectedMapping->getRecipientTypes() + CRM_Core_BAO_ActionSchedule::getAdditionalRecipients();
112 $this->assign('entityMapping', json_encode(
113 CRM_Utils_Array::collectMethod('getEntity', $mappings)
114 ));
115 $this->assign('recipientMapping', json_encode(
116 array_combine(array_keys($entityRecipientLabels), array_keys($entityRecipientLabels))
117 ));
118
119 if (!$this->getContext()) {
120 $sel = &$this->add(
121 'hierselect',
122 'entity',
123 ts('Entity'),
124 [
125 'name' => 'entity[0]',
126 'style' => 'vertical-align: top;',
127 ]
128 );
129 $sel->setOptions([
130 CRM_Utils_Array::collectMethod('getLabel', $mappings),
131 CRM_Core_BAO_ActionSchedule::getAllEntityValueLabels(),
132 CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels(),
133 ]);
134
135 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
136 // make second selector a multi-select -
137 $sel->_elements[1]->setMultiple(TRUE);
138 $sel->_elements[1]->setSize(5);
139 }
140
141 if (is_a($sel->_elements[2], 'HTML_QuickForm_select')) {
142 // make third selector a multi-select -
143 $sel->_elements[2]->setMultiple(TRUE);
144 $sel->_elements[2]->setSize(5);
145 }
146 }
147 else {
148 // Dig deeper - this code is sublimely stupid.
149 $allEntityStatusLabels = CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels();
150 $options = $allEntityStatusLabels[$this->_mappingID][0];
151 $attributes = ['multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]];
152 unset($options[0]);
153 $this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes);
154 $this->assign('context', $this->getContext());
155 }
156
157 //get the frequency units.
158 $this->_freqUnits = CRM_Core_SelectValues::getRecurringFrequencyUnits();
159
160 //reminder_interval
161 $this->add('number', 'start_action_offset', ts('When'), ['class' => 'six', 'min' => 0]);
162 $this->addRule('start_action_offset', ts('Value should be a positive number'), 'positiveInteger');
163
164 $isActive = ts('Scheduled Reminder Active');
165 $recordActivity = ts('Record activity for automated email');
166 if ($providersCount) {
167 $this->assign('sms', $providersCount);
168 $recordActivity = ts('Record activity for automated email or SMS');
169 $options = CRM_Core_OptionGroup::values('msg_mode');
170 $this->add('select', 'mode', ts('Send as'), $options);
171
172 $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
173
174 $providerSelect = [];
175 foreach ($providers as $provider) {
176 $providerSelect[$provider['id']] = $provider['title'];
177 }
178 $this->add('select', 'sms_provider_id', ts('SMS Provider'), $providerSelect, TRUE);
179 }
180
181 foreach ($this->_freqUnits as $val => $label) {
182 $freqUnitsDisplay[$val] = ts('%1(s)', [1 => $label]);
183 }
184
185 $this->add('datepicker', 'absolute_date', ts('Start Date'), [], FALSE, ['time' => FALSE]);
186
187 //reminder_frequency
188 $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
189
190 $condition = [
191 'before' => ts('before'),
192 'after' => ts('after'),
193 ];
194 //reminder_action
195 $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
196
197 $this->add('select', 'start_action_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
198
199 $this->addElement('checkbox', 'record_activity', $recordActivity);
200
201 $this->addElement('checkbox', 'is_repeat', ts('Repeat'),
202 NULL, ['onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);"]
203 );
204
205 $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
206 $this->add('number', 'repetition_frequency_interval', ts('every'), ['class' => 'six', 'min' => 0]);
207 $this->addRule('repetition_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
208
209 $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
210 $this->add('number', 'end_frequency_interval', ts('until'), ['class' => 'six', 'min' => 0]);
211 $this->addRule('end_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
212
213 $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
214 $this->add('select', 'end_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
215
216 $this->add('text', 'from_name', ts('From Name'));
217 $this->add('text', 'from_email', ts('From Email'));
218
219 $this->add('datepicker', 'effective_start_date', ts('Effective start date'), [], FALSE);
220 $this->add('datepicker', 'effective_end_date', ts('Effective end date'), [], FALSE);
221
222 $recipientListingOptions = [];
223
224 if ($mappingID) {
225 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
226 'id' => $mappingID,
227 ]));
228 }
229
230 $limitOptions = ['' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include')];
231
232 $recipientLabels = ['activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients')];
233 $this->assign('recipientLabels', $recipientLabels);
234
235 $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, ['onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"]);
236
237 $this->add('select', 'recipient', $recipientLabels['other'], $entityRecipientLabels,
238 FALSE, ['onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);"]
239 );
240
241 if (!empty($this->_submitValues['recipient_listing'])) {
242 if ($this->getContext()) {
243 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_mappingID, $this->_submitValues['recipient']);
244 }
245 else {
246 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($_POST['entity'][0], $_POST['recipient']);
247 }
248 }
249 elseif (!empty($this->_values['recipient_listing'])) {
250 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
251 }
252
253 $this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE,
254 ['multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE]);
255
256 $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), ['multiple' => TRUE, 'create' => TRUE]);
257
258 $this->add('select', 'group_id', ts('Group'),
259 CRM_Core_PseudoConstant::nestedGroup(), FALSE, ['class' => 'crm-select2 huge']
260 );
261
262 // multilingual only options
263 $multilingual = CRM_Core_I18n::isMultilingual();
264 if ($multilingual) {
265 $smarty = CRM_Core_Smarty::singleton();
266 $smarty->assign('multilingual', $multilingual);
267
268 $languages = CRM_Core_I18n::languages(TRUE);
269 $languageFilter = $languages + [CRM_Core_I18n::NONE => ts('Contacts with no preferred language')];
270 $element = $this->add('select', 'filter_contact_language', ts('Recipients language'), $languageFilter, FALSE,
271 ['multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE]);
272
273 $communicationLanguage = [
274 '' => ts('System default language'),
275 CRM_Core_I18n::AUTO => ts('Follow recipient preferred language'),
276 ];
277 $communicationLanguage = $communicationLanguage + $languages;
278 $this->add('select', 'communication_language', ts('Communication language'), $communicationLanguage);
279 }
280
281 CRM_Mailing_BAO_Mailing::commonCompose($this);
282
283 $this->add('text', 'subject', ts('Subject'),
284 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject')
285 );
286
287 $this->add('checkbox', 'is_active', $isActive);
288
289 $this->addFormRule(['CRM_Admin_Form_ScheduleReminders', 'formRule'], $this);
290
291 $this->setPageTitle(ts('Scheduled Reminder'));
292 }
293
294 /**
295 * Global form rule.
296 *
297 * @param array $fields
298 * The input form values.
299 * @param array $files
300 * @param CRM_Admin_Form_ScheduleReminders $self
301 *
302 * @return array|bool
303 * True if no errors, else array of errors
304 * @throws \CRM_Core_Exception
305 * @throws \CiviCRM_API3_Exception
306 * @throws \Civi\API\Exception\UnauthorizedException
307 */
308 public static function formRule(array $fields, $files, $self) {
309 $errors = [];
310 if ((array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0) ||
311 (array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0)
312 ) {
313 $errors['entity'] = ts('Please select appropriate value');
314 }
315
316 $mode = CRM_Utils_Array::value('mode', $fields, FALSE);
317 if (!empty($fields['is_active']) &&
318 CRM_Utils_System::isNull($fields['subject']) && (!$mode || $mode !== 'SMS')
319 ) {
320 $errors['subject'] = ts('Subject is a required field.');
321 }
322 if (!empty($fields['is_active']) &&
323 CRM_Utils_System::isNull(trim(strip_tags($fields['html_message']))) && (!$mode || $mode !== 'SMS')
324 ) {
325 $errors['html_message'] = ts('The HTML message is a required field.');
326 }
327
328 if (!empty($mode) && ($mode === 'SMS' || $mode === 'User_Preference') && !empty($fields['is_active']) &&
329 CRM_Utils_System::isNull(trim(strip_tags($fields['sms_text_message'])))
330 ) {
331 $errors['sms_text_message'] = ts('The SMS message is a required field.');
332 }
333
334 if (empty($self->getContext()) && CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
335 $errors['entity'] = ts('Please select entity value');
336 }
337
338 if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
339 if ($fields['absolute_date'] < date('Y-m-d')) {
340 $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
341 }
342 }
343 else {
344 if (CRM_Utils_System::isNull($fields['start_action_offset'])) {
345 $errors['start_action_offset'] = ts('Start Action Offset must be filled in or Absolute Date set');
346 }
347 }
348 if (!CRM_Utils_Rule::email($fields['from_email']) && (!$mode || $mode != 'SMS')) {
349 $errors['from_email'] = ts('Please enter a valid email address.');
350 }
351 $recipientKind = [
352 'participant_role' => [
353 'name' => 'participant role',
354 'target_id' => 'recipient_listing',
355 ],
356 'manual' => [
357 'name' => 'recipient',
358 'target_id' => 'recipient_manual_id',
359 ],
360 ];
361 if ($fields['limit_to'] != '' && array_key_exists($fields['recipient'], $recipientKind) && empty($fields[$recipientKind[$fields['recipient']]['target_id']])) {
362 $errors[$recipientKind[$fields['recipient']]['target_id']] = ts('If "Also include" or "Limit to" are selected, you must specify at least one %1', [1 => $recipientKind[$fields['recipient']]['name']]);
363 }
364
365 //CRM-21523
366 if (!empty($fields['is_repeat']) &&
367 (empty($fields['repetition_frequency_interval']) || ($fields['end_frequency_interval'] == NULL))
368 ) {
369 $errors['is_repeat'] = ts('If you are enabling repetition you must indicate the frequency and ending term.');
370 }
371
372 $self->_actionSchedule = $self->parseActionSchedule($fields);
373 if ($self->_actionSchedule->mapping_id) {
374 $mapping = CRM_Core_BAO_ActionSchedule::getMapping($self->_actionSchedule->mapping_id);
375 CRM_Utils_Array::extend($errors, $mapping->validateSchedule($self->_actionSchedule));
376 }
377
378 if (!empty($errors)) {
379 return $errors;
380 }
381
382 return empty($errors) ? TRUE : $errors;
383 }
384
385 /**
386 * @return int
387 */
388 public function setDefaultValues() {
389 if ($this->_action & CRM_Core_Action::ADD) {
390 $defaults['is_active'] = 1;
391 $defaults['mode'] = 'Email';
392 $defaults['record_activity'] = 1;
393 $defaults['start_action_unit'] = 'hour';
394 }
395 else {
396 $defaults = $this->_values;
397 $entityValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('entity_value', $defaults));
398 $entityStatus = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('entity_status', $defaults));
399 if (empty($this->getContext())) {
400 $defaults['entity'][0] = $defaults['mapping_id'] ?? NULL;
401 $defaults['entity'][1] = $entityValue;
402 $defaults['entity'][2] = $entityStatus;
403 }
404 else {
405 $defaults['entity'] = $entityStatus;
406 }
407
408 if ($recipientListing = CRM_Utils_Array::value('recipient_listing', $defaults)) {
409 $defaults['recipient_listing'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
410 $recipientListing
411 );
412 }
413 $defaults['text_message'] = $defaults['body_text'] ?? NULL;
414 $defaults['html_message'] = $defaults['body_html'] ?? NULL;
415 $defaults['sms_text_message'] = $defaults['sms_body_text'] ?? NULL;
416 $defaults['template'] = $defaults['msg_template_id'] ?? NULL;
417 $defaults['SMStemplate'] = $defaults['sms_template_id'] ?? NULL;
418 if (!empty($defaults['group_id'])) {
419 $defaults['recipient'] = 'group';
420 }
421 elseif (!empty($defaults['recipient_manual'])) {
422 $defaults['recipient'] = 'manual';
423 $defaults['recipient_manual_id'] = $defaults['recipient_manual'];
424 }
425 if ($contactLanguage = CRM_Utils_Array::value('filter_contact_language', $defaults)) {
426 $defaults['filter_contact_language'] = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contactLanguage);
427 }
428 }
429
430 return $defaults;
431 }
432
433 /**
434 * Process the form submission.
435 */
436 public function postProcess() {
437 if ($this->_action & CRM_Core_Action::DELETE) {
438 // delete reminder
439 CRM_Core_BAO_ActionSchedule::del($this->_id);
440 CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success');
441 if ($this->getContext() === 'event' && $this->getComponentID()) {
442 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
443 "reset=1&action=browse&id=" . $this->getComponentID() . "&component=" . $this->getContext() . "&setTab=1"
444 );
445 $session = CRM_Core_Session::singleton();
446 $session->pushUserContext($url);
447 }
448 return;
449 }
450 $values = $this->controller->exportValues($this->getName());
451 if (empty($this->_actionSchedule)) {
452 $bao = $this->parseActionSchedule($values)->save();
453 }
454 else {
455 $bao = $this->_actionSchedule->save();
456 }
457
458 // we need to set this on the form so that hooks can identify the created entity
459 $this->set('id', $bao->id);
460
461 $status = ts("Your new Reminder titled %1 has been saved.",
462 [1 => "<strong>{$values['title']}</strong>"]
463 );
464
465 if ($this->_action) {
466 if ($this->_action & CRM_Core_Action::UPDATE) {
467 $status = ts("Your Reminder titled %1 has been updated.",
468 [1 => "<strong>{$values['title']}</strong>"]
469 );
470 }
471
472 if ($this->getContext() === 'event' && $this->getComponentID()) {
473 $url = CRM_Utils_System::url('civicrm/event/manage/reminder', "reset=1&action=browse&id=" . $this->getComponentID() . "&component=" . $this->getContext() . "&setTab=1");
474 $session = CRM_Core_Session::singleton();
475 $session->pushUserContext($url);
476 }
477 }
478 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
479 }
480
481 /**
482 * @param array $values
483 * The submitted form values.
484 *
485 * @return CRM_Core_DAO_ActionSchedule
486 * @throws \CiviCRM_API3_Exception
487 * @throws \Civi\API\Exception\UnauthorizedException
488 */
489 public function parseActionSchedule($values) {
490 $params = [];
491
492 $keys = [
493 'title',
494 'subject',
495 'absolute_date',
496 'group_id',
497 'limit_to',
498 'mode',
499 'sms_provider_id',
500 'from_name',
501 'from_email',
502 ];
503 foreach ($keys as $key) {
504 $params[$key] = $values[$key] ?? NULL;
505 }
506
507 // set boolean fields to false if not set.
508 foreach (['record_activity', 'is_repeat', 'is_active'] as $boolFieldName) {
509 $params[$boolFieldName] = $values[$boolFieldName] ?? 0;
510 }
511
512 $moreKeys = [
513 'start_action_offset',
514 'start_action_unit',
515 'start_action_condition',
516 'start_action_date',
517 'repetition_frequency_unit',
518 'repetition_frequency_interval',
519 'end_frequency_unit',
520 'end_frequency_interval',
521 'end_action',
522 'end_date',
523 'effective_end_date',
524 'effective_start_date',
525 ];
526
527 if (empty($params['absolute_date'])) {
528 $params['absolute_date'] = 'null';
529 }
530 foreach ($moreKeys as $mkey) {
531 if ($params['absolute_date'] !== 'null' && CRM_Utils_String::startsWith($mkey, 'start_action')) {
532 $params[$mkey] = 'null';
533 continue;
534 }
535 $params[$mkey] = $values[$mkey] ?? NULL;
536 }
537
538 $params['body_text'] = $values['text_message'] ?? NULL;
539 $params['sms_body_text'] = $values['sms_text_message'] ?? NULL;
540 $params['body_html'] = $values['html_message'] ?? NULL;
541
542 if (CRM_Utils_Array::value('recipient', $values) === 'manual') {
543 $params['recipient_manual'] = $values['recipient_manual_id'] ?? NULL;
544 $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null';
545 }
546 elseif (CRM_Utils_Array::value('recipient', $values) === 'group') {
547 $params['group_id'] = $values['group_id'];
548 $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null';
549 }
550 elseif (isset($values['recipient_listing']) && isset($values['limit_to']) && !CRM_Utils_System::isNull($values['recipient_listing']) && !CRM_Utils_System::isNull($values['limit_to'])) {
551 $params['recipient'] = $values['recipient'] ?? NULL;
552 $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
553 CRM_Utils_Array::value('recipient_listing', $values)
554 );
555 $params['group_id'] = $params['recipient_manual'] = 'null';
556 }
557 else {
558 $params['recipient'] = $values['recipient'] ?? NULL;
559 $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
560 }
561
562 if (!empty($this->_mappingID) && !empty($this->getComponentID())) {
563 $params['mapping_id'] = $this->_mappingID;
564 $params['entity_value'] = $this->getComponentID();
565 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']);
566 }
567 else {
568 $params['mapping_id'] = $values['entity'][0];
569 if ($params['mapping_id'] == 1) {
570 $params['limit_to'] = 1;
571 }
572
573 $entity_value = CRM_Utils_Array::value(1, $values['entity'], []);
574 $entity_status = CRM_Utils_Array::value(2, $values['entity'], []);
575 $params['entity_value'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_value);
576 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_status);
577 }
578
579 if (empty($values['is_repeat'])) {
580 $params['repetition_frequency_unit'] = 'null';
581 $params['repetition_frequency_interval'] = 'null';
582 $params['end_frequency_unit'] = 'null';
583 $params['end_frequency_interval'] = 'null';
584 $params['end_action'] = 'null';
585 $params['end_date'] = 'null';
586 }
587
588 // multilingual options
589 $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, []);
590 $params['filter_contact_language'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['filter_contact_language']);
591 $params['communication_language'] = $values['communication_language'] ?? NULL;
592
593 if ($this->_action & CRM_Core_Action::UPDATE) {
594 $params['id'] = $this->_id;
595 }
596 elseif ($this->_action & CRM_Core_Action::ADD) {
597 // we do this only once, so name never changes
598 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64);
599 }
600
601 $modePrefixes = ['Mail' => NULL, 'SMS' => 'SMS'];
602
603 if ($params['mode'] === 'Email' || empty($params['sms_provider_id'])) {
604 unset($modePrefixes['SMS']);
605 }
606 elseif ($params['mode'] === 'SMS') {
607 unset($modePrefixes['Mail']);
608 }
609
610 //TODO: handle postprocessing of SMS and/or Email info based on $modePrefixes
611
612 $composeFields = [
613 'template',
614 'saveTemplate',
615 'updateTemplate',
616 'saveTemplateName',
617 ];
618 $msgTemplate = NULL;
619 //mail template is composed
620
621 foreach ($modePrefixes as $prefix) {
622 $composeParams = [];
623 foreach ($composeFields as $key) {
624 $key = $prefix . $key;
625 if (!empty($values[$key])) {
626 $composeParams[$key] = $values[$key];
627 }
628 }
629
630 if (!empty($composeParams[$prefix . 'updateTemplate'])) {
631 $templateParams = ['is_active' => TRUE];
632 if ($prefix === 'SMS') {
633 $templateParams += [
634 'msg_text' => $params['sms_body_text'],
635 'is_sms' => TRUE,
636 ];
637 }
638 else {
639 $templateParams += [
640 'msg_text' => $params['body_text'],
641 'msg_html' => $params['body_html'],
642 'msg_subject' => $params['subject'],
643 ];
644 }
645 $templateParams['id'] = $values[$prefix . 'template'];
646
647 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
648 }
649
650 if (!empty($composeParams[$prefix . 'saveTemplate'])) {
651 $templateParams = ['is_active' => TRUE];
652 if ($prefix === 'SMS') {
653 $templateParams += [
654 'msg_text' => $params['sms_body_text'],
655 'is_sms' => TRUE,
656 ];
657 }
658 else {
659 $templateParams += [
660 'msg_text' => $params['body_text'],
661 'msg_html' => $params['body_html'],
662 'msg_subject' => $params['subject'],
663 ];
664 }
665 $templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName'];
666
667 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
668 }
669
670 if ($prefix === 'SMS') {
671 if (isset($msgTemplate->id)) {
672 $params['sms_template_id'] = $msgTemplate->id;
673 }
674 else {
675 $params['sms_template_id'] = $values['SMStemplate'] ?? NULL;
676 }
677 }
678 else {
679 if (isset($msgTemplate->id)) {
680 $params['msg_template_id'] = $msgTemplate->id;
681 }
682 else {
683 $params['msg_template_id'] = $values['template'] ?? NULL;
684 }
685 }
686 }
687
688 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
689 $actionSchedule->copyValues($params);
690 return $actionSchedule;
691 }
692
693 /**
694 * List available tokens for this form.
695 *
696 * @return array
697 */
698 public function listTokens() {
699 $tokenProcessor = new \Civi\Token\TokenProcessor(\Civi::dispatcher(), [
700 'controller' => get_class(),
701 'smarty' => FALSE,
702 'schema' => ['activityId', 'participantId'],
703 ]);
704 $tokens = $tokenProcessor->listTokens();
705
706 $tokens = array_merge(CRM_Core_SelectValues::contactTokens(), $tokens);
707 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
708 $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens);
709 $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
710 return $tokens;
711 }
712
713 }