Merge pull request #22555 from eileenmcnaughton/stricter
[civicrm-core.git] / CRM / Core / Form / RecurringEntity.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 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18
19 /**
20 * This class generates form components for processing Entity.
21 */
22 class CRM_Core_Form_RecurringEntity {
23 /**
24 * Current entity id
25 * @var int
26 */
27 protected static $_entityId = NULL;
28
29 /**
30 * Schedule Reminder ID
31 * @var int
32 */
33 protected static $_scheduleReminderID = NULL;
34
35 /**
36 * Schedule Reminder data
37 * @var array
38 */
39 protected static $_scheduleReminderDetails = [];
40
41 /**
42 * Parent Entity ID
43 * @var int
44 */
45 protected static $_parentEntityId = NULL;
46
47 /**
48 * Exclude date information
49 * @var array
50 */
51 public static $_excludeDateInfo = [];
52
53 /**
54 * Entity Table
55 * @var string
56 */
57 public static $_entityTable;
58
59 /**
60 * Checks current entityID has parent
61 * @var string
62 */
63 public static $_hasParent = FALSE;
64
65 /**
66 * @param $entityTable
67 */
68 public static function preProcess($entityTable) {
69 self::$_entityId = (int) CRM_Utils_Request::retrieve('id', 'Positive');
70 self::$_entityTable = $entityTable;
71
72 if (self::$_entityId && $entityTable) {
73 $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor(self::$_entityId, $entityTable);
74 if ($checkParentExistsForThisId) {
75 self::$_hasParent = TRUE;
76 self::$_parentEntityId = $checkParentExistsForThisId;
77 self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $entityTable);
78 }
79 else {
80 self::$_parentEntityId = self::$_entityId;
81 self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId(self::$_entityId, $entityTable);
82 }
83 if (property_exists(self::$_scheduleReminderDetails, 'id')) {
84 self::$_scheduleReminderID = self::$_scheduleReminderDetails->id;
85 }
86 }
87 CRM_Core_OptionValue::getValues(['name' => $entityTable . '_repeat_exclude_dates_' . self::$_parentEntityId], $optionValue);
88 $excludeOptionValues = [];
89 if (!empty($optionValue)) {
90 foreach ($optionValue as $key => $val) {
91 $excludeOptionValues[$val['value']] = substr(CRM_Utils_Date::mysqlToIso($val['value']), 0, 10);
92 }
93 self::$_excludeDateInfo = $excludeOptionValues;
94 }
95
96 // Assign variables
97 $entityType = CRM_Core_DAO_AllCoreTables::getEntityNameForTable($entityTable);
98 $tpl = CRM_Core_Smarty::singleton();
99 $tpl->assign('recurringEntityType', ts($entityType));
100 $tpl->assign('currentEntityId', self::$_entityId);
101 $tpl->assign('entityTable', self::$_entityTable);
102 $tpl->assign('scheduleReminderId', self::$_scheduleReminderID);
103 $tpl->assign('hasParent', self::$_hasParent);
104 }
105
106 /**
107 * Set default values for the form. For edit/view mode
108 * the default values are retrieved from the database
109 *
110 *
111 * @return array
112 */
113 public static function setDefaultValues() {
114 // Defaults for new entity
115 $defaults = [
116 'repetition_frequency_unit' => 'week',
117 ];
118
119 // Default for existing entity
120 if (self::$_scheduleReminderID) {
121 $defaults['repetition_frequency_unit'] = self::$_scheduleReminderDetails->repetition_frequency_unit;
122 $defaults['repetition_frequency_interval'] = self::$_scheduleReminderDetails->repetition_frequency_interval;
123 $defaults['start_action_condition'] = array_flip(explode(",", self::$_scheduleReminderDetails->start_action_condition));
124 foreach ($defaults['start_action_condition'] as $key => $val) {
125 $val = 1;
126 $defaults['start_action_condition'][$key] = $val;
127 }
128 $defaults['start_action_offset'] = self::$_scheduleReminderDetails->start_action_offset;
129 if (self::$_scheduleReminderDetails->start_action_offset) {
130 $defaults['ends'] = 1;
131 }
132 $defaults['repeat_absolute_date'] = self::$_scheduleReminderDetails->absolute_date;
133 if (self::$_scheduleReminderDetails->absolute_date) {
134 $defaults['ends'] = 2;
135 }
136 $defaults['limit_to'] = self::$_scheduleReminderDetails->limit_to;
137 if (self::$_scheduleReminderDetails->limit_to) {
138 $defaults['repeats_by'] = 1;
139 }
140 if (self::$_scheduleReminderDetails->entity_status) {
141 $explodeStartActionCondition = explode(" ", self::$_scheduleReminderDetails->entity_status);
142 $defaults['entity_status_1'] = $explodeStartActionCondition[0];
143 $defaults['entity_status_2'] = $explodeStartActionCondition[1];
144 }
145 if (self::$_scheduleReminderDetails->entity_status) {
146 $defaults['repeats_by'] = 2;
147 }
148 if (self::$_excludeDateInfo) {
149 $defaults['exclude_date_list'] = implode(',', self::$_excludeDateInfo);
150 }
151 }
152 return $defaults;
153 }
154
155 /**
156 * Build form.
157 *
158 * @param CRM_Core_Form $form
159 */
160 public static function buildQuickForm(&$form) {
161 // FIXME: this is using the following as keys rather than the standard numeric keys returned by CRM_Utils_Date
162 $dayOfTheWeek = [];
163 $dayKeys = [
164 'sunday',
165 'monday',
166 'tuesday',
167 'wednesday',
168 'thursday',
169 'friday',
170 'saturday',
171 ];
172 foreach (CRM_Utils_Date::getAbbrWeekdayNames() as $k => $label) {
173 $dayOfTheWeek[$dayKeys[$k]] = $label;
174 }
175 $form->add('select', 'repetition_frequency_unit', ts('Repeats every'), CRM_Core_SelectValues::getRecurringFrequencyUnits(), FALSE, ['class' => 'required']);
176 $numericOptions = CRM_Core_SelectValues::getNumericOptions(1, 30);
177 $form->add('select', 'repetition_frequency_interval', NULL, $numericOptions, FALSE, ['class' => 'required']);
178 $form->add('datepicker', 'repetition_start_date', ts('Start Date'), [], FALSE, ['time' => TRUE]);
179 foreach ($dayOfTheWeek as $key => $val) {
180 $startActionCondition[] = $form->createElement('checkbox', $key, NULL, $val);
181 }
182 $form->addGroup($startActionCondition, 'start_action_condition', ts('Repeats on'));
183 $roptionTypes = [
184 '1' => ts('day of the month'),
185 '2' => ts('day of the week'),
186 ];
187 $form->addRadio('repeats_by', ts("Repeats on"), $roptionTypes, ['required' => TRUE], NULL);
188 $form->add('select', 'limit_to', '', CRM_Core_SelectValues::getNumericOptions(1, 31));
189 $dayOfTheWeekNo = [
190 'first' => ts('First'),
191 'second' => ts('Second'),
192 'third' => ts('Third'),
193 'fourth' => ts('Fourth'),
194 'last' => ts('Last'),
195 ];
196 $form->add('select', 'entity_status_1', '', $dayOfTheWeekNo);
197 $form->add('select', 'entity_status_2', '', $dayOfTheWeek);
198 $eoptionTypes = [
199 '1' => ts('After'),
200 '2' => ts('On'),
201 ];
202 $form->addRadio('ends', ts("Ends"), $eoptionTypes, ['class' => 'required'], NULL);
203 // Offset options gets key=>val pairs like 1=>2 because the BAO wants to know the number of
204 // children while it makes more sense to the user to see the total number including the parent.
205 $offsetOptions = range(1, 30);
206 unset($offsetOptions[0]);
207 $form->add('select', 'start_action_offset', NULL, $offsetOptions, FALSE);
208 $form->addFormRule(['CRM_Core_Form_RecurringEntity', 'formRule']);
209 $form->add('datepicker', 'repeat_absolute_date', ts('On'), [], FALSE, ['time' => FALSE]);
210 $form->add('text', 'exclude_date_list', ts('Exclude Dates'), ['class' => 'twenty']);
211 $form->addElement('hidden', 'allowRepeatConfigToSubmit', '', ['id' => 'allowRepeatConfigToSubmit']);
212 $form->addButtons([
213 [
214 'type' => 'submit',
215 'name' => ts('Save'),
216 'isDefault' => TRUE,
217 ],
218 [
219 'type' => 'cancel',
220 'name' => ts('Cancel'),
221 ],
222 ]);
223 // For client-side pluralization
224 $form->assign('recurringFrequencyOptions', [
225 'single' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::getRecurringFrequencyUnits()),
226 'plural' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::getRecurringFrequencyUnits(2)),
227 ]);
228 }
229
230 /**
231 * Global validation rules for the form.
232 *
233 * @param array $values
234 * Posted values of the form.
235 *
236 * @return array
237 * list of errors to be posted back to the form
238 */
239 public static function formRule($values) {
240 $errors = [];
241 //Process this function only when you get this variable
242 if ($values['allowRepeatConfigToSubmit'] == 1) {
243 $dayOfTheWeek = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
244 //Repeats
245 if (empty($values['repetition_frequency_unit'])) {
246 $errors['repetition_frequency_unit'] = ts('This is a required field');
247 }
248 //Repeats every
249 if (empty($values['repetition_frequency_interval'])) {
250 $errors['repetition_frequency_interval'] = ts('This is a required field');
251 }
252 //Ends
253 if (!empty($values['ends'])) {
254 if ($values['ends'] == 1) {
255 if (empty($values['start_action_offset'])) {
256 $errors['start_action_offset'] = ts('This is a required field');
257 }
258 elseif ($values['start_action_offset'] > 30) {
259 $errors['start_action_offset'] = ts('Occurrences should be less than or equal to 30');
260 }
261 }
262 if ($values['ends'] == 2) {
263 if (!empty($values['repeat_absolute_date'])) {
264 $entityStartDate = CRM_Utils_Date::processDate($values['repetition_start_date']);
265 $end = CRM_Utils_Date::processDate($values['repeat_absolute_date']);
266 if (($end < $entityStartDate) && ($end != 0)) {
267 $errors['repeat_absolute_date'] = ts('End date should be after current entity\'s start date');
268 }
269 }
270 else {
271 $errors['repeat_absolute_date'] = ts('This is a required field');
272 }
273 }
274 }
275 else {
276 $errors['ends'] = ts('This is a required field');
277 }
278
279 //Repeats BY
280 if (!empty($values['repeats_by'])) {
281 if ($values['repeats_by'] == 1) {
282 if (!empty($values['limit_to'])) {
283 if ($values['limit_to'] < 1 && $values['limit_to'] > 31) {
284 $errors['limit_to'] = ts('Invalid day of the month');
285 }
286 }
287 else {
288 $errors['limit_to'] = ts('Invalid day of the month');
289 }
290 }
291 if ($values['repeats_by'] == 2) {
292 if (!empty($values['entity_status_1'])) {
293 $dayOfTheWeekNo = ['first', 'second', 'third', 'fourth', 'last'];
294 if (!in_array($values['entity_status_1'], $dayOfTheWeekNo)) {
295 $errors['entity_status_1'] = ts('Invalid option');
296 }
297 }
298 else {
299 $errors['entity_status_1'] = ts('Invalid option');
300 }
301 if (!empty($values['entity_status_2'])) {
302 if (!in_array($values['entity_status_2'], $dayOfTheWeek)) {
303 $errors['entity_status_2'] = ts('Invalid day name');
304 }
305 }
306 else {
307 $errors['entity_status_2'] = ts('Invalid day name');
308 }
309 }
310 }
311 }
312 return $errors;
313 }
314
315 /**
316 * Process the form submission.
317 *
318 * @param array $params
319 * @param string $type
320 * @param array $linkedEntities
321 *
322 * @throws \CiviCRM_API3_Exception
323 */
324 public static function postProcess($params, $type, $linkedEntities = []) {
325 // Check entity_id not present in params take it from class variable
326 if (empty($params['entity_id'])) {
327 $params['entity_id'] = self::$_entityId;
328 }
329 //Process this function only when you get this variable
330 if (CRM_Utils_Array::value('allowRepeatConfigToSubmit', $params) == 1) {
331 if (!empty($params['entity_table']) && !empty($params['entity_id']) && $type) {
332 $params['used_for'] = $type;
333 if (empty($params['parent_entity_id'])) {
334 $params['parent_entity_id'] = self::$_parentEntityId;
335 }
336 if (!empty($params['schedule_reminder_id'])) {
337 $params['id'] = $params['schedule_reminder_id'];
338 }
339 else {
340 $params['id'] = self::$_scheduleReminderID;
341 }
342
343 //Save post params to the schedule reminder table
344 $recurobj = new CRM_Core_BAO_RecurringEntity();
345 $dbParams = $recurobj->mapFormValuesToDB($params);
346
347 //Delete repeat configuration and rebuild
348 if (!empty($params['id'])) {
349 CRM_Core_BAO_ActionSchedule::del($params['id']);
350 unset($params['id']);
351 }
352 $actionScheduleObj = CRM_Core_BAO_ActionSchedule::add($dbParams);
353
354 //exclude dates
355 $excludeDateList = [];
356 if (!empty($params['exclude_date_list']) && !empty($params['parent_entity_id']) && $actionScheduleObj->entity_value) {
357 //Since we get comma separated values lets get them in array
358 $excludeDates = explode(",", $params['exclude_date_list']);
359
360 //Check if there exists any values for this option group
361 $optionGroupIdExists = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
362 $type . '_repeat_exclude_dates_' . $params['parent_entity_id'],
363 'id',
364 'name'
365 );
366 if ($optionGroupIdExists) {
367 CRM_Core_BAO_OptionGroup::del($optionGroupIdExists);
368 }
369 $optionGroupParams = [
370 'name' => $type . '_repeat_exclude_dates_' . $actionScheduleObj->entity_value,
371 'title' => $type . ' recursion',
372 'is_reserved' => 0,
373 'is_active' => 1,
374 ];
375 $opGroup = CRM_Core_BAO_OptionGroup::add($optionGroupParams);
376 if ($opGroup->id) {
377 $oldWeight = 0;
378 $fieldValues = ['option_group_id' => $opGroup->id];
379 foreach ($excludeDates as $val) {
380 $optionGroupValue = [
381 'option_group_id' => $opGroup->id,
382 'label' => CRM_Utils_Date::processDate($val),
383 'value' => CRM_Utils_Date::processDate($val),
384 'name' => $opGroup->name,
385 'description' => 'Used for recurring ' . $type,
386 'weight' => CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues),
387 'is_active' => 1,
388 ];
389 $excludeDateList[] = $optionGroupValue['value'];
390 CRM_Core_BAO_OptionValue::create($optionGroupValue);
391 }
392 }
393 }
394
395 //Set type for API
396 $apiEntityType = explode("_", $type);
397 if (!empty($apiEntityType[1])) {
398 $apiType = $apiEntityType[1];
399 }
400 //Delete relations if any from recurring entity tables before inserting new relations for this entity id
401 if ($params['entity_id']) {
402 //If entity has any pre delete function, consider that first
403 if (!empty(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['pre_delete_func']) &&
404 !empty(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['helper_class'])
405 ) {
406 $preDeleteResult = call_user_func_array(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['pre_delete_func'], [$params['entity_id']]);
407 if (!empty($preDeleteResult)) {
408 call_user_func([CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['helper_class'], $preDeleteResult]);
409 }
410 }
411 //Ready to execute delete on entities if it has delete function set
412 if (!empty(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func']) &&
413 !empty(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['helper_class'])
414 ) {
415 //Check if pre delete function has some ids to be deleted
416 if (!empty(CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted)) {
417 foreach (CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted as $eid) {
418 $result = civicrm_api3(
419 ucfirst(strtolower($apiType)),
420 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
421 [
422 'sequential' => 1,
423 'id' => $eid,
424 ]
425 );
426 if ($result['error']) {
427 CRM_Core_Error::statusBounce(ts('Error creating recurring list'));
428 }
429 }
430 }
431 else {
432 $getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($params['entity_id'], $params['entity_table'], FALSE);
433 foreach ($getRelatedEntities as $key => $value) {
434 $result = civicrm_api3(
435 ucfirst(strtolower($apiType)),
436 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
437 [
438 'sequential' => 1,
439 'id' => $value['id'],
440 ]
441 );
442 if ($result['error']) {
443 CRM_Core_Error::statusBounce(ts('Error creating recurring list'));
444 }
445 }
446 }
447 }
448
449 // find all entities from the recurring set. At this point we 'll get entities which were not deleted
450 // for e.g due to participants being present. We need to delete them from recurring tables anyway.
451 $pRepeatingEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($params['entity_id'], $params['entity_table']);
452 foreach ($pRepeatingEntities as $val) {
453 CRM_Core_BAO_RecurringEntity::delEntity($val['id'], $val['table'], TRUE);
454 }
455 }
456
457 $recursion = new CRM_Core_BAO_RecurringEntity();
458 $recursion->dateColumns = $params['dateColumns'];
459 $recursion->scheduleId = $actionScheduleObj->id;
460
461 if (!empty($excludeDateList)) {
462 $recursion->excludeDates = $excludeDateList;
463 $recursion->excludeDateRangeColumns = $params['excludeDateRangeColumns'];
464 }
465 if (!empty($params['intervalDateColumns'])) {
466 $recursion->intervalDateColumns = $params['intervalDateColumns'];
467 }
468 $recursion->entity_id = $params['entity_id'];
469 $recursion->entity_table = $params['entity_table'];
470 if (!empty($linkedEntities)) {
471 $recursion->linkedEntities = $linkedEntities;
472 }
473
474 $recursion->generate();
475
476 $status = ts('Repeat Configuration has been saved');
477 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
478 }
479 }
480 }
481
482 /**
483 * Return a descriptive name for the page, used in wizard header
484 *
485 * @return string
486 */
487 public function getTitle() {
488 return ts('Repeat Entity');
489 }
490
491 }