Merge pull request #16671 from eileenmcnaughton/acl
[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 = NULL;
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) {
44 $this->_compId = $compId;
45 }
46
47 /**
48 * Build the form object.
49 */
50 public function buildQuickForm() {
51 parent::buildQuickForm();
52 $this->_mappingID = $mappingID = NULL;
53 $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
54 $this->setContext();
55 $isEvent = $this->getContext() == 'event';
56
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.'));
61 }
62 }
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 }
66
67 if ($this->_action & (CRM_Core_Action::DELETE)) {
68 $reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
69 $this->assign('reminderName', $reminderName);
70 return;
71 }
72 elseif ($this->_action & (CRM_Core_Action::UPDATE)) {
73 $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
74 }
75 if ($isEvent) {
76 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->getComponentID(), 'is_template');
77 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
78 'id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
79 ]));
80 if ($mapping) {
81 $this->_mappingID = $mapping->getId();
82 }
83 else {
84 throw new CRM_Core_Exception('Could not find mapping for event scheduled reminders.');
85 }
86 }
87
88 if (!empty($_POST) && !empty($_POST['entity']) && empty($this->getContext())) {
89 $mappingID = $_POST['entity'][0];
90 }
91 elseif ($this->_mappingID) {
92 $mappingID = $this->_mappingID;
93 if ($isEvent) {
94 $this->add('hidden', 'mappingID', $mappingID);
95 }
96 }
97
98 $this->add(
99 'text',
100 'title',
101 ts('Title'),
102 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'title'),
103 TRUE
104 );
105
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 ));
115
116 if (!$this->getContext()) {
117 $sel = &$this->add(
118 'hierselect',
119 'entity',
120 ts('Entity'),
121 [
122 'name' => 'entity[0]',
123 'style' => 'vertical-align: top;',
124 ]
125 );
126 $sel->setOptions([
127 CRM_Utils_Array::collectMethod('getLabel', $mappings),
128 CRM_Core_BAO_ActionSchedule::getAllEntityValueLabels(),
129 CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels(),
130 ]);
131
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 {
145 // Dig deeper - this code is sublimely stupid.
146 $allEntityStatusLabels = CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels();
147 $options = $allEntityStatusLabels[$this->_mappingID][0];
148 $attributes = ['multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]];
149 unset($options[0]);
150 $this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes);
151 $this->assign('context', $this->getContext());
152 }
153
154 //get the frequency units.
155 $this->_freqUnits = CRM_Core_SelectValues::getRecurringFrequencyUnits();
156
157 //reminder_interval
158 $this->add('number', 'start_action_offset', ts('When'), ['class' => 'six', 'min' => 0]);
159 $this->addRule('start_action_offset', ts('Value should be a positive number'), 'positiveInteger');
160
161 $isActive = ts('Scheduled Reminder Active');
162 $recordActivity = ts('Record activity for automated email');
163 if ($providersCount) {
164 $this->assign('sms', $providersCount);
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
171 $providerSelect = [];
172 foreach ($providers as $provider) {
173 $providerSelect[$provider['id']] = $provider['title'];
174 }
175 $this->add('select', 'sms_provider_id', ts('SMS Provider'), $providerSelect, TRUE);
176 }
177
178 foreach ($this->_freqUnits as $val => $label) {
179 $freqUnitsDisplay[$val] = ts('%1(s)', [1 => $label]);
180 }
181
182 $this->add('datepicker', 'absolute_date', ts('Start Date'), [], FALSE, ['time' => FALSE]);
183
184 //reminder_frequency
185 $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
186
187 $condition = [
188 'before' => ts('before'),
189 'after' => ts('after'),
190 ];
191 //reminder_action
192 $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
193
194 $this->add('select', 'start_action_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
195
196 $this->addElement('checkbox', 'record_activity', $recordActivity);
197
198 $this->addElement('checkbox', 'is_repeat', ts('Repeat'),
199 NULL, ['onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);"]
200 );
201
202 $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
203 $this->add('number', 'repetition_frequency_interval', ts('every'), ['class' => 'six', 'min' => 0]);
204 $this->addRule('repetition_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
205
206 $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
207 $this->add('number', 'end_frequency_interval', ts('until'), ['class' => 'six', 'min' => 0]);
208 $this->addRule('end_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
209
210 $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
211 $this->add('select', 'end_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
212
213 $this->add('text', 'from_name', ts('From Name'));
214 $this->add('text', 'from_email', ts('From Email'));
215
216 $recipientListingOptions = [];
217
218 if ($mappingID) {
219 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
220 'id' => $mappingID,
221 ]));
222 }
223
224 $limitOptions = ['' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include')];
225
226 $recipientLabels = ['activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients')];
227 $this->assign('recipientLabels', $recipientLabels);
228
229 $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, ['onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"]);
230
231 $this->add('select', 'recipient', $recipientLabels['other'], $entityRecipientLabels,
232 FALSE, ['onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);"]
233 );
234
235 if (!empty($this->_submitValues['recipient_listing'])) {
236 if ($this->getContext()) {
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 }
242 }
243 elseif (!empty($this->_values['recipient_listing'])) {
244 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
245 }
246
247 $this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE,
248 ['multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE]);
249
250 $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), ['multiple' => TRUE, 'create' => TRUE]);
251
252 $this->add('select', 'group_id', ts('Group'),
253 CRM_Core_PseudoConstant::nestedGroup('Mailing'), FALSE, ['class' => 'crm-select2 huge']
254 );
255
256 // multilingual only options
257 $multilingual = CRM_Core_I18n::isMultilingual();
258 if ($multilingual) {
259 $smarty = CRM_Core_Smarty::singleton();
260 $smarty->assign('multilingual', $multilingual);
261
262 $languages = CRM_Core_I18n::languages(TRUE);
263 $languageFilter = $languages + [CRM_Core_I18n::NONE => ts('Contacts with no preferred language')];
264 $element = $this->add('select', 'filter_contact_language', ts('Recipients language'), $languageFilter, FALSE,
265 ['multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE]);
266
267 $communicationLanguage = [
268 '' => ts('System default language'),
269 CRM_Core_I18n::AUTO => ts('Follow recipient preferred language'),
270 ];
271 $communicationLanguage = $communicationLanguage + $languages;
272 $this->add('select', 'communication_language', ts('Communication language'), $communicationLanguage);
273 }
274
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
281 $this->add('checkbox', 'is_active', $isActive);
282
283 $this->addFormRule(['CRM_Admin_Form_ScheduleReminders', 'formRule'], $this);
284
285 $this->setPageTitle(ts('Scheduled Reminder'));
286 }
287
288 /**
289 * Global form rule.
290 *
291 * @param array $fields
292 * The input form values.
293 * @param array $files
294 * @param CRM_Admin_Form_ScheduleReminders $self
295 *
296 * @return array|bool
297 * True if no errors, else array of errors
298 */
299 public static function formRule($fields, $files, $self) {
300 $errors = [];
301 if ((array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0) ||
302 (array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0)
303 ) {
304 $errors['entity'] = ts('Please select appropriate value');
305 }
306
307 $mode = CRM_Utils_Array::value('mode', $fields, FALSE);
308 if (!empty($fields['is_active']) &&
309 CRM_Utils_System::isNull($fields['subject']) && (!$mode || $mode != 'SMS')
310 ) {
311 $errors['subject'] = ts('Subject is a required field.');
312 }
313 if (!empty($fields['is_active']) &&
314 CRM_Utils_System::isNull(trim(strip_tags($fields['html_message']))) && (!$mode || $mode != 'SMS')
315 ) {
316 $errors['html_message'] = ts('The HTML message is a required field.');
317 }
318
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
325 if (empty($self->getContext()) && CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
326 $errors['entity'] = ts('Please select entity value');
327 }
328
329 if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
330 if ($fields['absolute_date'] < date('Y-m-d')) {
331 $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
332 }
333 }
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 }
339 if (!CRM_Utils_Rule::email($fields['from_email']) && (!$mode || $mode != 'SMS')) {
340 $errors['from_email'] = ts('Please enter a valid email address.');
341 }
342 $recipientKind = [
343 'participant_role' => [
344 'name' => 'participant role',
345 'target_id' => 'recipient_listing',
346 ],
347 'manual' => [
348 'name' => 'recipient',
349 'target_id' => 'recipient_manual_id',
350 ],
351 ];
352 if ($fields['limit_to'] != '' && array_key_exists($fields['recipient'], $recipientKind) && empty($fields[$recipientKind[$fields['recipient']]['target_id']])) {
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']]);
354 }
355
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
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));
367 }
368
369 if (!empty($errors)) {
370 return $errors;
371 }
372
373 return empty($errors) ? TRUE : $errors;
374 }
375
376 /**
377 * @return int
378 */
379 public function setDefaultValues() {
380 if ($this->_action & CRM_Core_Action::ADD) {
381 $defaults['is_active'] = 1;
382 $defaults['mode'] = 'Email';
383 $defaults['record_activity'] = 1;
384 }
385 else {
386 $defaults = $this->_values;
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));
389 if (empty($this->getContext())) {
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 }
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);
405 $defaults['sms_text_message'] = CRM_Utils_Array::value('sms_body_text', $defaults);
406 $defaults['template'] = CRM_Utils_Array::value('msg_template_id', $defaults);
407 $defaults['SMStemplate'] = CRM_Utils_Array::value('sms_template_id', $defaults);
408 if (!empty($defaults['group_id'])) {
409 $defaults['recipient'] = 'group';
410 }
411 elseif (!empty($defaults['recipient_manual'])) {
412 $defaults['recipient'] = 'manual';
413 $defaults['recipient_manual_id'] = $defaults['recipient_manual'];
414 }
415 if ($contactLanguage = CRM_Utils_Array::value('filter_contact_language', $defaults)) {
416 $defaults['filter_contact_language'] = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contactLanguage);
417 }
418 }
419
420 return $defaults;
421 }
422
423 /**
424 * Process the form submission.
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');
431 if ($this->getContext() == 'event' && $this->getComponentID()) {
432 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
433 "reset=1&action=browse&id=" . $this->getComponentID() . "&component=" . $this->getContext() . "&setTab=1"
434 );
435 $session = CRM_Core_Session::singleton();
436 $session->pushUserContext($url);
437 }
438 return;
439 }
440 $values = $this->controller->exportValues($this->getName());
441 if (empty($this->_actionSchedule)) {
442 $bao = $this->parseActionSchedule($values)->save();
443 }
444 else {
445 $bao = $this->_actionSchedule->save();
446 }
447
448 // we need to set this on the form so that hooks can identify the created entity
449 $this->set('id', $bao->id);
450
451 $status = ts("Your new Reminder titled %1 has been saved.",
452 [1 => "<strong>{$values['title']}</strong>"]
453 );
454
455 if ($this->_action) {
456 if ($this->_action & CRM_Core_Action::UPDATE) {
457 $status = ts("Your Reminder titled %1 has been updated.",
458 [1 => "<strong>{$values['title']}</strong>"]
459 );
460 }
461
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");
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) {
477 $params = [];
478
479 $keys = [
480 'title',
481 'subject',
482 'absolute_date',
483 'group_id',
484 'record_activity',
485 'limit_to',
486 'mode',
487 'sms_provider_id',
488 'from_name',
489 'from_email',
490 ];
491 foreach ($keys as $key) {
492 $params[$key] = CRM_Utils_Array::value($key, $values);
493 }
494
495 $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0);
496
497 $moreKeys = [
498 'start_action_offset',
499 'start_action_unit',
500 'start_action_condition',
501 'start_action_date',
502 'repetition_frequency_unit',
503 'repetition_frequency_interval',
504 'end_frequency_unit',
505 'end_frequency_interval',
506 'end_action',
507 'end_date',
508 ];
509
510 if (empty($params['absolute_date'])) {
511 $params['absolute_date'] = 'null';
512 }
513 foreach ($moreKeys as $mkey) {
514 if ($params['absolute_date'] != 'null' && CRM_Utils_String::startsWith($mkey, 'start_action')) {
515 $params[$mkey] = 'null';
516 continue;
517 }
518 $params[$mkey] = CRM_Utils_Array::value($mkey, $values);
519 }
520
521 $params['body_text'] = CRM_Utils_Array::value('text_message', $values);
522 $params['sms_body_text'] = CRM_Utils_Array::value('sms_text_message', $values);
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 }
533 elseif (isset($values['recipient_listing']) && isset($values['limit_to']) && !CRM_Utils_System::isNull($values['recipient_listing']) && !CRM_Utils_System::isNull($values['limit_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
545 if (!empty($this->_mappingID) && !empty($this->getComponentID())) {
546 $params['mapping_id'] = $this->_mappingID;
547 $params['entity_value'] = $this->getComponentID();
548 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']);
549 }
550 else {
551 $params['mapping_id'] = $values['entity'][0];
552 if ($params['mapping_id'] == 1) {
553 $params['limit_to'] = 1;
554 }
555
556 $entity_value = CRM_Utils_Array::value(1, $values['entity'], []);
557 $entity_status = CRM_Utils_Array::value(2, $values['entity'], []);
558 $params['entity_value'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_value);
559 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_status);
560 }
561
562 $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0);
563
564 if (empty($values['is_repeat'])) {
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
573 // multilingual options
574 $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, []);
575 $params['filter_contact_language'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['filter_contact_language']);
576 $params['communication_language'] = CRM_Utils_Array::value('communication_language', $values, NULL);
577
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
586 $modePrefixes = ['Mail' => NULL, 'SMS' => 'SMS'];
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
597 $composeFields = [
598 'template',
599 'saveTemplate',
600 'updateTemplate',
601 'saveTemplateName',
602 ];
603 $msgTemplate = NULL;
604 //mail template is composed
605
606 foreach ($modePrefixes as $prefix) {
607 $composeParams = [];
608 foreach ($composeFields as $key) {
609 $key = $prefix . $key;
610 if (!empty($values[$key])) {
611 $composeParams[$key] = $values[$key];
612 }
613 }
614
615 if (!empty($composeParams[$prefix . 'updateTemplate'])) {
616 $templateParams = ['is_active' => TRUE];
617 if ($prefix == 'SMS') {
618 $templateParams += [
619 'msg_text' => $params['sms_body_text'],
620 'is_sms' => TRUE,
621 ];
622 }
623 else {
624 $templateParams += [
625 'msg_text' => $params['body_text'],
626 'msg_html' => $params['body_html'],
627 'msg_subject' => $params['subject'],
628 ];
629 }
630 $templateParams['id'] = $values[$prefix . 'template'];
631
632 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
633 }
634
635 if (!empty($composeParams[$prefix . 'saveTemplate'])) {
636 $templateParams = ['is_active' => TRUE];
637 if ($prefix == 'SMS') {
638 $templateParams += [
639 'msg_text' => $params['sms_body_text'],
640 'is_sms' => TRUE,
641 ];
642 }
643 else {
644 $templateParams += [
645 'msg_text' => $params['body_text'],
646 'msg_html' => $params['body_html'],
647 'msg_subject' => $params['subject'],
648 ];
649 }
650 $templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName'];
651
652 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
653 }
654
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 }
671 }
672
673 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
674 $actionSchedule->copyValues($params);
675 return $actionSchedule;
676 }
677
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);
688 $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
689 return $tokens;
690 }
691
692 }