3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 * This class generates form components for processing Entity.
22 class CRM_Core_Form_RecurringEntity
{
27 protected static $_entityId = NULL;
30 * Schedule Reminder ID
33 protected static $_scheduleReminderID = NULL;
36 * Schedule Reminder data
39 protected static $_scheduleReminderDetails = [];
45 protected static $_parentEntityId = NULL;
48 * Exclude date information
51 public static $_excludeDateInfo = [];
57 public static $_entityTable;
60 * Checks current entityID has parent
63 public static $_hasParent = FALSE;
68 public static function preProcess($entityTable) {
69 self
::$_entityId = (int) CRM_Utils_Request
::retrieve('id', 'Positive');
70 self
::$_entityTable = $entityTable;
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);
80 self
::$_parentEntityId = self
::$_entityId;
81 self
::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity
::getReminderDetailsByEntityId(self
::$_entityId, $entityTable);
83 if (property_exists(self
::$_scheduleReminderDetails, 'id')) {
84 self
::$_scheduleReminderID = self
::$_scheduleReminderDetails->id
;
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);
93 self
::$_excludeDateInfo = $excludeOptionValues;
97 $entityType = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($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);
107 * Set default values for the form. For edit/view mode
108 * the default values are retrieved from the database
113 public static function setDefaultValues() {
114 // Defaults for new entity
116 'repetition_frequency_unit' => 'week',
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) {
126 $defaults['start_action_condition'][$key] = $val;
128 $defaults['start_action_offset'] = self
::$_scheduleReminderDetails->start_action_offset
;
129 if (self
::$_scheduleReminderDetails->start_action_offset
) {
130 $defaults['ends'] = 1;
132 $defaults['repeat_absolute_date'] = self
::$_scheduleReminderDetails->absolute_date
;
133 if (self
::$_scheduleReminderDetails->absolute_date
) {
134 $defaults['ends'] = 2;
136 $defaults['limit_to'] = self
::$_scheduleReminderDetails->limit_to
;
137 if (self
::$_scheduleReminderDetails->limit_to
) {
138 $defaults['repeats_by'] = 1;
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];
145 if (self
::$_scheduleReminderDetails->entity_status
) {
146 $defaults['repeats_by'] = 2;
148 if (self
::$_excludeDateInfo) {
149 $defaults['exclude_date_list'] = implode(',', self
::$_excludeDateInfo);
158 * @param CRM_Core_Form $form
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
172 foreach (CRM_Utils_Date
::getAbbrWeekdayNames() as $k => $label) {
173 $dayOfTheWeek[$dayKeys[$k]] = $label;
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);
182 $form->addGroup($startActionCondition, 'start_action_condition', ts('Repeats on'));
184 '1' => ts('day of the month'),
185 '2' => ts('day of the week'),
187 $form->addRadio('repeats_by', ts("Repeats on"), $roptionTypes, ['required' => TRUE], NULL);
188 $form->add('select', 'limit_to', '', CRM_Core_SelectValues
::getNumericOptions(1, 31));
190 'first' => ts('First'),
191 'second' => ts('Second'),
192 'third' => ts('Third'),
193 'fourth' => ts('Fourth'),
194 'last' => ts('Last'),
196 $form->add('select', 'entity_status_1', '', $dayOfTheWeekNo);
197 $form->add('select', 'entity_status_2', '', $dayOfTheWeek);
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']);
215 'name' => ts('Save'),
220 'name' => ts('Cancel'),
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)),
231 * Global validation rules for the form.
233 * @param array $values
234 * Posted values of the form.
237 * list of errors to be posted back to the form
239 public static function formRule($values) {
241 //Process this function only when you get this variable
242 if ($values['allowRepeatConfigToSubmit'] == 1) {
243 $dayOfTheWeek = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
245 if (empty($values['repetition_frequency_unit'])) {
246 $errors['repetition_frequency_unit'] = ts('This is a required field');
249 if (empty($values['repetition_frequency_interval'])) {
250 $errors['repetition_frequency_interval'] = ts('This is a required field');
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');
258 elseif ($values['start_action_offset'] > 30) {
259 $errors['start_action_offset'] = ts('Occurrences should be less than or equal to 30');
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');
271 $errors['repeat_absolute_date'] = ts('This is a required field');
276 $errors['ends'] = ts('This is a required field');
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');
288 $errors['limit_to'] = ts('Invalid day of the month');
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');
299 $errors['entity_status_1'] = ts('Invalid option');
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');
307 $errors['entity_status_2'] = ts('Invalid day name');
316 * Process the form submission.
318 * @param array $params
319 * @param string $type
320 * @param array $linkedEntities
322 * @throws \CiviCRM_API3_Exception
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;
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;
336 if (!empty($params['schedule_reminder_id'])) {
337 $params['id'] = $params['schedule_reminder_id'];
340 $params['id'] = self
::$_scheduleReminderID;
343 //Save post params to the schedule reminder table
344 $recurobj = new CRM_Core_BAO_RecurringEntity();
345 $dbParams = $recurobj->mapFormValuesToDB($params);
347 //Delete repeat configuration and rebuild
348 if (!empty($params['id'])) {
349 CRM_Core_BAO_ActionSchedule
::del($params['id']);
350 unset($params['id']);
352 $actionScheduleObj = CRM_Core_BAO_ActionSchedule
::add($dbParams);
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']);
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'],
366 if ($optionGroupIdExists) {
367 CRM_Core_BAO_OptionGroup
::del($optionGroupIdExists);
369 $optionGroupParams = [
370 'name' => $type . '_repeat_exclude_dates_' . $actionScheduleObj->entity_value
,
371 'title' => $type . ' recursion',
375 $opGroup = CRM_Core_BAO_OptionGroup
::add($optionGroupParams);
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),
389 $excludeDateList[] = $optionGroupValue['value'];
390 CRM_Core_BAO_OptionValue
::create($optionGroupValue);
396 $apiEntityType = explode("_", $type);
397 if (!empty($apiEntityType[1])) {
398 $apiType = $apiEntityType[1];
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 (CRM_Utils_Array
::value('pre_delete_func', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]) &&
404 CRM_Utils_Array
::value('helper_class', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']])
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]);
411 //Ready to execute delete on entities if it has delete function set
412 if (CRM_Utils_Array
::value('delete_func', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]) &&
413 CRM_Utils_Array
::value('helper_class', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']])
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'],
426 if ($result['error']) {
427 CRM_Core_Error
::statusBounce('Error creating recurring list');
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'],
439 'id' => $value['id'],
442 if ($result['error']) {
443 CRM_Core_Error
::statusBounce('Error creating recurring list');
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);
457 $recursion = new CRM_Core_BAO_RecurringEntity();
458 $recursion->dateColumns
= $params['dateColumns'];
459 $recursion->scheduleId
= $actionScheduleObj->id
;
461 if (!empty($excludeDateList)) {
462 $recursion->excludeDates
= $excludeDateList;
463 $recursion->excludeDateRangeColumns
= $params['excludeDateRangeColumns'];
465 if (!empty($params['intervalDateColumns'])) {
466 $recursion->intervalDateColumns
= $params['intervalDateColumns'];
468 $recursion->entity_id
= $params['entity_id'];
469 $recursion->entity_table
= $params['entity_table'];
470 if (!empty($linkedEntities)) {
471 $recursion->linkedEntities
= $linkedEntities;
474 $recursion->generate();
476 $status = ts('Repeat Configuration has been saved');
477 CRM_Core_Session
::setStatus($status, ts('Saved'), 'success');
483 * Return a descriptive name for the page, used in wizard header
487 public function getTitle() {
488 return ts('Repeat Entity');