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