Set version to 5.51.alpha1
[civicrm-core.git] / CRM / Admin / Form / ScheduleReminders.php
CommitLineData
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
18/**
ce064e4f 19 * This class generates form components for Scheduling Reminders.
6a488035
TO
20 */
21class CRM_Admin_Form_ScheduleReminders extends CRM_Admin_Form {
22
23 /**
eceb18cc 24 * Scheduled Reminder ID.
62d3ee27 25 * @var int
6a488035 26 */
d53caabc 27 public $_id;
6a488035
TO
28
29 public $_freqUnits;
30
9351dc7e 31 protected $_compId;
32
2d69ef96 33 /**
9351dc7e 34 * @return mixed
35 */
36 public function getComponentID() {
37 return $this->_compId;
38 }
39
40 /**
41 * @param mixed $compId
2d69ef96 42 */
d53caabc 43 public function setComponentID($compId): void {
9351dc7e 44 $this->_compId = $compId;
45 }
2d69ef96 46
6a488035 47 /**
eceb18cc 48 * Build the form object.
d53caabc 49 *
50 * @throws \CRM_Core_Exception
51 * @throws \CiviCRM_API3_Exception
6a488035 52 */
d53caabc 53 public function buildQuickForm(): void {
6a488035
TO
54 parent::buildQuickForm();
55 $this->_mappingID = $mappingID = NULL;
a3e3eea1 56 $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
9351dc7e 57 $this->setContext();
d53caabc 58 $isEvent = $this->getContext() === 'event';
6a488035 59
9351dc7e 60 if ($isEvent) {
61 $this->setComponentID(CRM_Utils_Request::retrieve('compId', 'Integer', $this));
f6807038 62 if (!CRM_Event_BAO_Event::checkPermission((int) $this->getComponentID(), CRM_Core_Permission::EDIT)) {
9351dc7e 63 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
121eba46
WA
64 }
65 }
9351dc7e 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 }
9c74fabc 69
6a488035 70 if ($this->_action & (CRM_Core_Action::DELETE)) {
4d3e4dbe 71 $reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
6a488035
TO
72 $this->assign('reminderName', $reminderName);
73 return;
74 }
75 elseif ($this->_action & (CRM_Core_Action::UPDATE)) {
c301f76e 76 $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
6a488035 77 }
9351dc7e 78 if ($isEvent) {
79 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->getComponentID(), 'is_template');
be2fb01f 80 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
2d69ef96 81 'id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
be2fb01f 82 ]));
2d69ef96 83 if ($mapping) {
84 $this->_mappingID = $mapping->getId();
85 }
86 else {
9351dc7e 87 throw new CRM_Core_Exception('Could not find mapping for event scheduled reminders.');
4d3e4dbe 88 }
264ebe5d 89 }
90
9351dc7e 91 if (!empty($_POST) && !empty($_POST['entity']) && empty($this->getContext())) {
02fc859b
TO
92 $mappingID = $_POST['entity'][0];
93 }
94 elseif ($this->_mappingID) {
95 $mappingID = $this->_mappingID;
9351dc7e 96 if ($isEvent) {
93fdcf55 97 $this->add('hidden', 'mappingID', $mappingID);
98 }
02fc859b 99 }
4d3e4dbe 100
6a488035
TO
101 $this->add(
102 'text',
103 'title',
104 ts('Title'),
0c843583 105 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'title'),
6a488035
TO
106 TRUE
107 );
108
0905ee5d
TO
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 ));
6a488035 118
9351dc7e 119 if (!$this->getContext()) {
353ffa53 120 $sel = &$this->add(
4d3e4dbe 121 'hierselect',
353ffa53
TO
122 'entity',
123 ts('Entity'),
be2fb01f 124 [
353ffa53
TO
125 'name' => 'entity[0]',
126 'style' => 'vertical-align: top;',
be2fb01f 127 ]
4d3e4dbe 128 );
be2fb01f 129 $sel->setOptions([
0905ee5d
TO
130 CRM_Utils_Array::collectMethod('getLabel', $mappings),
131 CRM_Core_BAO_ActionSchedule::getAllEntityValueLabels(),
132 CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels(),
be2fb01f 133 ]);
6a488035 134
4d3e4dbe 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 {
0905ee5d
TO
148 // Dig deeper - this code is sublimely stupid.
149 $allEntityStatusLabels = CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels();
150 $options = $allEntityStatusLabels[$this->_mappingID][0];
be2fb01f 151 $attributes = ['multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]];
4d3e4dbe 152 unset($options[0]);
153 $this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes);
9351dc7e 154 $this->assign('context', $this->getContext());
6a488035
TO
155 }
156
157 //get the frequency units.
8fe4b69f 158 $this->_freqUnits = CRM_Core_SelectValues::getRecurringFrequencyUnits();
6a488035 159
6a488035 160 //reminder_interval
be2fb01f 161 $this->add('number', 'start_action_offset', ts('When'), ['class' => 'six', 'min' => 0]);
4054a23f
DRJ
162 $this->addRule('start_action_offset', ts('Value should be a positive number'), 'positiveInteger');
163
b30461e4 164 $isActive = ts('Scheduled Reminder Active');
a3e3eea1 165 $recordActivity = ts('Record activity for automated email');
166 if ($providersCount) {
7b007e61 167 $this->assign('sms', $providersCount);
a3e3eea1 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
be2fb01f 174 $providerSelect = [];
a3e3eea1 175 foreach ($providers as $provider) {
176 $providerSelect[$provider['id']] = $provider['title'];
177 }
1e035d58 178 $this->add('select', 'sms_provider_id', ts('SMS Provider'), $providerSelect, TRUE);
a3e3eea1 179 }
6a488035
TO
180
181 foreach ($this->_freqUnits as $val => $label) {
be2fb01f 182 $freqUnitsDisplay[$val] = ts('%1(s)', [1 => $label]);
6a488035
TO
183 }
184
be2fb01f 185 $this->add('datepicker', 'absolute_date', ts('Start Date'), [], FALSE, ['time' => FALSE]);
6a488035
TO
186
187 //reminder_frequency
188 $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
189
be2fb01f 190 $condition = [
353ffa53 191 'before' => ts('before'),
6a488035 192 'after' => ts('after'),
be2fb01f 193 ];
6a488035
TO
194 //reminder_action
195 $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
196
0905ee5d 197 $this->add('select', 'start_action_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
6a488035 198
a3e3eea1 199 $this->addElement('checkbox', 'record_activity', $recordActivity);
6a488035
TO
200
201 $this->addElement('checkbox', 'is_repeat', ts('Repeat'),
be2fb01f 202 NULL, ['onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);"]
6a488035
TO
203 );
204
205 $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
be2fb01f 206 $this->add('number', 'repetition_frequency_interval', ts('every'), ['class' => 'six', 'min' => 0]);
4054a23f
DRJ
207 $this->addRule('repetition_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
208
6a488035 209 $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
be2fb01f 210 $this->add('number', 'end_frequency_interval', ts('until'), ['class' => 'six', 'min' => 0]);
4054a23f
DRJ
211 $this->addRule('end_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
212
6a488035 213 $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
0905ee5d 214 $this->add('select', 'end_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
6a488035 215
1991bba1 216 $this->add('text', 'from_name', ts('From Name'));
1e035d58 217 $this->add('text', 'from_email', ts('From Email'));
1991bba1 218
4e57130f
MD
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
be2fb01f 222 $recipientListingOptions = [];
6a488035
TO
223
224 if ($mappingID) {
be2fb01f 225 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
50a23755 226 'id' => $mappingID,
be2fb01f 227 ]));
6a488035
TO
228 }
229
be2fb01f 230 $limitOptions = ['' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include')];
8ef12e64 231
be2fb01f 232 $recipientLabels = ['activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients')];
84a3e359 233 $this->assign('recipientLabels', $recipientLabels);
234
be2fb01f 235 $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, ['onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"]);
84a3e359 236
0905ee5d 237 $this->add('select', 'recipient', $recipientLabels['other'], $entityRecipientLabels,
be2fb01f 238 FALSE, ['onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);"]
6a488035
TO
239 );
240
49d61c3a 241 if (!empty($this->_submitValues['recipient_listing'])) {
9351dc7e 242 if ($this->getContext()) {
4d3e4dbe 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 }
6a488035 248 }
a7488080 249 elseif (!empty($this->_values['recipient_listing'])) {
6a488035
TO
250 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
251 }
4d3e4dbe 252
581c7be2 253 $this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE,
be2fb01f 254 ['multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE]);
6a488035 255
be2fb01f 256 $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), ['multiple' => TRUE, 'create' => TRUE]);
6a488035 257
581c7be2 258 $this->add('select', 'group_id', ts('Group'),
c6fe32d7 259 CRM_Core_PseudoConstant::nestedGroup(), FALSE, ['class' => 'crm-select2 huge']
6a488035
TO
260 );
261
776a4216 262 // multilingual only options
273f9849 263 $multilingual = CRM_Core_I18n::isMultilingual();
776a4216
SV
264 if ($multilingual) {
265 $smarty = CRM_Core_Smarty::singleton();
266 $smarty->assign('multilingual', $multilingual);
267
273f9849 268 $languages = CRM_Core_I18n::languages(TRUE);
be2fb01f 269 $languageFilter = $languages + [CRM_Core_I18n::NONE => ts('Contacts with no preferred language')];
776a4216 270 $element = $this->add('select', 'filter_contact_language', ts('Recipients language'), $languageFilter, FALSE,
be2fb01f 271 ['multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE]);
776a4216 272
be2fb01f 273 $communicationLanguage = [
273f9849 274 '' => ts('System default language'),
aeb3ba30 275 CRM_Core_I18n::AUTO => ts('Follow recipient preferred language'),
be2fb01f 276 ];
b3518210 277 $communicationLanguage = $communicationLanguage + $languages;
776a4216
SV
278 $this->add('select', 'communication_language', ts('Communication language'), $communicationLanguage);
279 }
280
6a488035
TO
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
a3e3eea1 287 $this->add('checkbox', 'is_active', $isActive);
6a488035 288
be2fb01f 289 $this->addFormRule(['CRM_Admin_Form_ScheduleReminders', 'formRule'], $this);
581c7be2
CW
290
291 $this->setPageTitle(ts('Scheduled Reminder'));
6a488035 292 }
353ffa53 293
6a488035 294 /**
eceb18cc 295 * Global form rule.
6a488035 296 *
5173bd95
TO
297 * @param array $fields
298 * The input form values.
ea3ddccf 299 * @param array $files
7f0141d8 300 * @param CRM_Admin_Form_ScheduleReminders $self
6a488035 301 *
ea3ddccf 302 * @return array|bool
303 * True if no errors, else array of errors
d53caabc 304 * @throws \CRM_Core_Exception
305 * @throws \CiviCRM_API3_Exception
306 * @throws \Civi\API\Exception\UnauthorizedException
6a488035 307 */
d53caabc 308 public static function formRule(array $fields, $files, $self) {
be2fb01f 309 $errors = [];
8d657dde 310 if ((array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0) ||
6a488035
TO
311 (array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0)
312 ) {
313 $errors['entity'] = ts('Please select appropriate value');
314 }
315
1c4d4fb7 316 $mode = CRM_Utils_Array::value('mode', $fields, FALSE);
fb90d6bb 317 if (!empty($fields['is_active']) &&
d53caabc 318 CRM_Utils_System::isNull($fields['subject']) && (!$mode || $mode !== 'SMS')
6a488035
TO
319 ) {
320 $errors['subject'] = ts('Subject is a required field.');
321 }
02fdbd86 322 if (!empty($fields['is_active']) &&
d53caabc 323 CRM_Utils_System::isNull(trim(strip_tags($fields['html_message']))) && (!$mode || $mode !== 'SMS')
02fdbd86 324 ) {
325 $errors['html_message'] = ts('The HTML message is a required field.');
326 }
6a488035 327
d53caabc 328 if (!empty($mode) && ($mode === 'SMS' || $mode === 'User_Preference') && !empty($fields['is_active']) &&
1c4d4fb7
SL
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
9351dc7e 334 if (empty($self->getContext()) && CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
6a488035
TO
335 $errors['entity'] = ts('Please select entity value');
336 }
337
338 if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
b219e49f 339 if ($fields['absolute_date'] < date('Y-m-d')) {
6a488035
TO
340 $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
341 }
342 }
b219e49f
SL
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 }
1c4d4fb7 348 if (!CRM_Utils_Rule::email($fields['from_email']) && (!$mode || $mode != 'SMS')) {
e09225f7
DV
349 $errors['from_email'] = ts('Please enter a valid email address.');
350 }
be2fb01f
CW
351 $recipientKind = [
352 'participant_role' => [
84a3e359 353 'name' => 'participant role',
21dfd5f5 354 'target_id' => 'recipient_listing',
be2fb01f
CW
355 ],
356 'manual' => [
84a3e359 357 'name' => 'recipient',
21dfd5f5 358 'target_id' => 'recipient_manual_id',
be2fb01f
CW
359 ],
360 ];
fb90d6bb 361 if ($fields['limit_to'] != '' && array_key_exists($fields['recipient'], $recipientKind) && empty($fields[$recipientKind[$fields['recipient']]['target_id']])) {
be2fb01f 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']]);
84a3e359 363 }
364
d1095f4a
BS
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
6f23e48a
JP
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));
7f0141d8
TO
376 }
377
6a488035
TO
378 if (!empty($errors)) {
379 return $errors;
380 }
381
382 return empty($errors) ? TRUE : $errors;
383 }
384
e0ef6999
EM
385 /**
386 * @return int
387 */
00be9182 388 public function setDefaultValues() {
6a488035
TO
389 if ($this->_action & CRM_Core_Action::ADD) {
390 $defaults['is_active'] = 1;
a3e3eea1 391 $defaults['mode'] = 'Email';
6a488035 392 $defaults['record_activity'] = 1;
33ad8852 393 $defaults['start_action_unit'] = 'hour';
6a488035
TO
394 }
395 else {
396 $defaults = $this->_values;
4d3e4dbe 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));
9351dc7e 399 if (empty($this->getContext())) {
9c1bc317 400 $defaults['entity'][0] = $defaults['mapping_id'] ?? NULL;
4d3e4dbe 401 $defaults['entity'][1] = $entityValue;
402 $defaults['entity'][2] = $entityStatus;
403 }
404 else {
405 $defaults['entity'] = $entityStatus;
406 }
6a488035
TO
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 }
9c1bc317
CW
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;
a7488080 418 if (!empty($defaults['group_id'])) {
6a488035
TO
419 $defaults['recipient'] = 'group';
420 }
a7488080 421 elseif (!empty($defaults['recipient_manual'])) {
6a488035 422 $defaults['recipient'] = 'manual';
92f4a0b1 423 $defaults['recipient_manual_id'] = $defaults['recipient_manual'];
6a488035 424 }
776a4216 425 if ($contactLanguage = CRM_Utils_Array::value('filter_contact_language', $defaults)) {
fadd4d37 426 $defaults['filter_contact_language'] = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contactLanguage);
776a4216 427 }
6a488035
TO
428 }
429
430 return $defaults;
431 }
432
433 /**
eceb18cc 434 * Process the form submission.
6a488035
TO
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');
d53caabc 441 if ($this->getContext() === 'event' && $this->getComponentID()) {
6a488035 442 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
9351dc7e 443 "reset=1&action=browse&id=" . $this->getComponentID() . "&component=" . $this->getContext() . "&setTab=1"
6a488035
TO
444 );
445 $session = CRM_Core_Session::singleton();
446 $session->pushUserContext($url);
447 }
448 return;
449 }
450 $values = $this->controller->exportValues($this->getName());
6f23e48a
JP
451 if (empty($this->_actionSchedule)) {
452 $bao = $this->parseActionSchedule($values)->save();
453 }
454 else {
455 $bao = $this->_actionSchedule->save();
456 }
7f0141d8
TO
457
458 // we need to set this on the form so that hooks can identify the created entity
459 $this->set('id', $bao->id);
7f0141d8
TO
460
461 $status = ts("Your new Reminder titled %1 has been saved.",
be2fb01f 462 [1 => "<strong>{$values['title']}</strong>"]
7f0141d8
TO
463 );
464
465 if ($this->_action) {
466 if ($this->_action & CRM_Core_Action::UPDATE) {
467 $status = ts("Your Reminder titled %1 has been updated.",
be2fb01f 468 [1 => "<strong>{$values['title']}</strong>"]
7f0141d8
TO
469 );
470 }
471
d53caabc 472 if ($this->getContext() === 'event' && $this->getComponentID()) {
9351dc7e 473 $url = CRM_Utils_System::url('civicrm/event/manage/reminder', "reset=1&action=browse&id=" . $this->getComponentID() . "&component=" . $this->getContext() . "&setTab=1");
7f0141d8
TO
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.
d53caabc 484 *
7f0141d8 485 * @return CRM_Core_DAO_ActionSchedule
d53caabc 486 * @throws \CiviCRM_API3_Exception
487 * @throws \Civi\API\Exception\UnauthorizedException
7f0141d8
TO
488 */
489 public function parseActionSchedule($values) {
be2fb01f 490 $params = [];
6a488035 491
be2fb01f 492 $keys = [
6a488035
TO
493 'title',
494 'subject',
495 'absolute_date',
496 'group_id',
a3e3eea1 497 'limit_to',
498 'mode',
1991bba1
DG
499 'sms_provider_id',
500 'from_name',
501 'from_email',
be2fb01f 502 ];
6a488035 503 foreach ($keys as $key) {
9c1bc317 504 $params[$key] = $values[$key] ?? NULL;
6a488035
TO
505 }
506
6c8ae5bf
PN
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 }
2ef60934 511
be2fb01f 512 $moreKeys = [
3e315abc 513 'start_action_offset',
514 'start_action_unit',
515 'start_action_condition',
516 'start_action_date',
6a488035
TO
517 'repetition_frequency_unit',
518 'repetition_frequency_interval',
519 'end_frequency_unit',
520 'end_frequency_interval',
3e315abc 521 'end_action',
522 'end_date',
9b329ebc
EM
523 'effective_end_date',
524 'effective_start_date',
be2fb01f 525 ];
6a488035 526
de6c59ca 527 if (empty($params['absolute_date'])) {
6a488035 528 $params['absolute_date'] = 'null';
dc6c330d 529 }
530 foreach ($moreKeys as $mkey) {
d53caabc 531 if ($params['absolute_date'] !== 'null' && CRM_Utils_String::startsWith($mkey, 'start_action')) {
39bf7f1e
JP
532 $params[$mkey] = 'null';
533 continue;
6a488035 534 }
9c1bc317 535 $params[$mkey] = $values[$mkey] ?? NULL;
6a488035
TO
536 }
537
9c1bc317
CW
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;
6a488035 541
d53caabc 542 if (CRM_Utils_Array::value('recipient', $values) === 'manual') {
9c1bc317 543 $params['recipient_manual'] = $values['recipient_manual_id'] ?? NULL;
6a488035
TO
544 $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null';
545 }
d53caabc 546 elseif (CRM_Utils_Array::value('recipient', $values) === 'group') {
6a488035
TO
547 $params['group_id'] = $values['group_id'];
548 $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null';
549 }
7f0141d8 550 elseif (isset($values['recipient_listing']) && isset($values['limit_to']) && !CRM_Utils_System::isNull($values['recipient_listing']) && !CRM_Utils_System::isNull($values['limit_to'])) {
9c1bc317 551 $params['recipient'] = $values['recipient'] ?? NULL;
6a488035
TO
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 {
9c1bc317 558 $params['recipient'] = $values['recipient'] ?? NULL;
6a488035
TO
559 $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
560 }
561
9351dc7e 562 if (!empty($this->_mappingID) && !empty($this->getComponentID())) {
353ffa53 563 $params['mapping_id'] = $this->_mappingID;
9351dc7e 564 $params['entity_value'] = $this->getComponentID();
4d3e4dbe 565 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']);
84a3e359 566 }
4d3e4dbe 567 else {
568 $params['mapping_id'] = $values['entity'][0];
673cdfb4 569 if ($params['mapping_id'] == 1) {
4d3e4dbe 570 $params['limit_to'] = 1;
571 }
84a3e359 572
be2fb01f
CW
573 $entity_value = CRM_Utils_Array::value(1, $values['entity'], []);
574 $entity_status = CRM_Utils_Array::value(2, $values['entity'], []);
7f0141d8
TO
575 $params['entity_value'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_value);
576 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_status);
6a488035
TO
577 }
578
de6c59ca 579 if (empty($values['is_repeat'])) {
6a488035
TO
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
776a4216 588 // multilingual options
be2fb01f 589 $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, []);
776a4216 590 $params['filter_contact_language'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['filter_contact_language']);
9c1bc317 591 $params['communication_language'] = $values['communication_language'] ?? NULL;
776a4216 592
6a488035
TO
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
be2fb01f 601 $modePrefixes = ['Mail' => NULL, 'SMS' => 'SMS'];
1e035d58 602
d53caabc 603 if ($params['mode'] === 'Email' || empty($params['sms_provider_id'])) {
1e035d58 604 unset($modePrefixes['SMS']);
605 }
d53caabc 606 elseif ($params['mode'] === 'SMS') {
1e035d58 607 unset($modePrefixes['Mail']);
608 }
609
610 //TODO: handle postprocessing of SMS and/or Email info based on $modePrefixes
611
be2fb01f 612 $composeFields = [
353ffa53
TO
613 'template',
614 'saveTemplate',
615 'updateTemplate',
616 'saveTemplateName',
be2fb01f 617 ];
6a488035
TO
618 $msgTemplate = NULL;
619 //mail template is composed
620
1e035d58 621 foreach ($modePrefixes as $prefix) {
be2fb01f 622 $composeParams = [];
1e035d58 623 foreach ($composeFields as $key) {
624 $key = $prefix . $key;
625 if (!empty($values[$key])) {
626 $composeParams[$key] = $values[$key];
627 }
6a488035 628 }
6a488035 629
1e035d58 630 if (!empty($composeParams[$prefix . 'updateTemplate'])) {
be2fb01f 631 $templateParams = ['is_active' => TRUE];
d53caabc 632 if ($prefix === 'SMS') {
be2fb01f 633 $templateParams += [
1e035d58 634 'msg_text' => $params['sms_body_text'],
635 'is_sms' => TRUE,
be2fb01f 636 ];
1e035d58 637 }
638 else {
be2fb01f 639 $templateParams += [
1e035d58 640 'msg_text' => $params['body_text'],
641 'msg_html' => $params['body_html'],
642 'msg_subject' => $params['subject'],
be2fb01f 643 ];
1e035d58 644 }
645 $templateParams['id'] = $values[$prefix . 'template'];
646
647 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
648 }
6a488035 649
1e035d58 650 if (!empty($composeParams[$prefix . 'saveTemplate'])) {
be2fb01f 651 $templateParams = ['is_active' => TRUE];
d53caabc 652 if ($prefix === 'SMS') {
be2fb01f 653 $templateParams += [
1e035d58 654 'msg_text' => $params['sms_body_text'],
655 'is_sms' => TRUE,
be2fb01f 656 ];
1e035d58 657 }
658 else {
be2fb01f 659 $templateParams += [
1e035d58 660 'msg_text' => $params['body_text'],
661 'msg_html' => $params['body_html'],
662 'msg_subject' => $params['subject'],
be2fb01f 663 ];
1e035d58 664 }
665 $templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName'];
666
667 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
668 }
6a488035 669
d53caabc 670 if ($prefix === 'SMS') {
1e035d58 671 if (isset($msgTemplate->id)) {
672 $params['sms_template_id'] = $msgTemplate->id;
673 }
674 else {
9c1bc317 675 $params['sms_template_id'] = $values['SMStemplate'] ?? NULL;
1e035d58 676 }
677 }
678 else {
679 if (isset($msgTemplate->id)) {
680 $params['msg_template_id'] = $msgTemplate->id;
681 }
682 else {
9c1bc317 683 $params['msg_template_id'] = $values['template'] ?? NULL;
1e035d58 684 }
685 }
6a488035
TO
686 }
687
7f0141d8
TO
688 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
689 $actionSchedule->copyValues($params);
690 return $actionSchedule;
6a488035 691 }
96025800 692
5ec6b0ad
TM
693 /**
694 * List available tokens for this form.
695 *
696 * @return array
697 */
698 public function listTokens() {
f9b991fa
MW
699 $tokenProcessor = new \Civi\Token\TokenProcessor(\Civi::dispatcher(), [
700 'controller' => get_class(),
701 'smarty' => FALSE,
e80f2261 702 'schema' => ['activityId', 'participantId'],
f9b991fa
MW
703 ]);
704 $tokens = $tokenProcessor->listTokens();
705
706 $tokens = array_merge(CRM_Core_SelectValues::contactTokens(), $tokens);
5ec6b0ad
TM
707 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
708 $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens);
c3ab1f3d 709 $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
5ec6b0ad
TM
710 return $tokens;
711 }
712
6a488035 713}