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