3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
32 * @copyright CiviCRM LLC (c) 2004-2019
36 * This class generates form components for processing Entity.
38 class CRM_Core_Form_RecurringEntity
{
43 protected static $_entityId = NULL;
46 * Schedule Reminder ID
49 protected static $_scheduleReminderID = NULL;
52 * Schedule Reminder data
55 protected static $_scheduleReminderDetails = [];
61 protected static $_parentEntityId = NULL;
64 * Exclude date information
67 public static $_excludeDateInfo = [];
73 public static $_entityTable;
76 * Checks current entityID has parent
79 public static $_hasParent = FALSE;
84 public static function preProcess($entityTable) {
85 self
::$_entityId = (int) CRM_Utils_Request
::retrieve('id', 'Positive');
86 self
::$_entityTable = $entityTable;
88 if (self
::$_entityId && $entityTable) {
89 $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity
::getParentFor(self
::$_entityId, $entityTable);
90 if ($checkParentExistsForThisId) {
91 self
::$_hasParent = TRUE;
92 self
::$_parentEntityId = $checkParentExistsForThisId;
93 self
::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity
::getReminderDetailsByEntityId($checkParentExistsForThisId, $entityTable);
96 self
::$_parentEntityId = self
::$_entityId;
97 self
::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity
::getReminderDetailsByEntityId(self
::$_entityId, $entityTable);
99 if (property_exists(self
::$_scheduleReminderDetails, 'id')) {
100 self
::$_scheduleReminderID = self
::$_scheduleReminderDetails->id
;
103 CRM_Core_OptionValue
::getValues(['name' => $entityTable . '_repeat_exclude_dates_' . self
::$_parentEntityId], $optionValue);
104 $excludeOptionValues = [];
105 if (!empty($optionValue)) {
106 foreach ($optionValue as $key => $val) {
107 $excludeOptionValues[$val['value']] = substr(CRM_Utils_Date
::mysqlToIso($val['value']), 0, 10);
109 self
::$_excludeDateInfo = $excludeOptionValues;
113 $entityType = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($entityTable));
114 $tpl = CRM_Core_Smarty
::singleton();
115 $tpl->assign('recurringEntityType', ts($entityType));
116 $tpl->assign('currentEntityId', self
::$_entityId);
117 $tpl->assign('entityTable', self
::$_entityTable);
118 $tpl->assign('scheduleReminderId', self
::$_scheduleReminderID);
119 $tpl->assign('hasParent', self
::$_hasParent);
123 * Set default values for the form. For edit/view mode
124 * the default values are retrieved from the database
129 public static function setDefaultValues() {
130 // Defaults for new entity
132 'repetition_frequency_unit' => 'week',
135 // Default for existing entity
136 if (self
::$_scheduleReminderID) {
137 $defaults['repetition_frequency_unit'] = self
::$_scheduleReminderDetails->repetition_frequency_unit
;
138 $defaults['repetition_frequency_interval'] = self
::$_scheduleReminderDetails->repetition_frequency_interval
;
139 $defaults['start_action_condition'] = array_flip(explode(",", self
::$_scheduleReminderDetails->start_action_condition
));
140 foreach ($defaults['start_action_condition'] as $key => $val) {
142 $defaults['start_action_condition'][$key] = $val;
144 $defaults['start_action_offset'] = self
::$_scheduleReminderDetails->start_action_offset
;
145 if (self
::$_scheduleReminderDetails->start_action_offset
) {
146 $defaults['ends'] = 1;
148 $defaults['repeat_absolute_date'] = self
::$_scheduleReminderDetails->absolute_date
;
149 if (self
::$_scheduleReminderDetails->absolute_date
) {
150 $defaults['ends'] = 2;
152 $defaults['limit_to'] = self
::$_scheduleReminderDetails->limit_to
;
153 if (self
::$_scheduleReminderDetails->limit_to
) {
154 $defaults['repeats_by'] = 1;
156 if (self
::$_scheduleReminderDetails->entity_status
) {
157 $explodeStartActionCondition = explode(" ", self
::$_scheduleReminderDetails->entity_status
);
158 $defaults['entity_status_1'] = $explodeStartActionCondition[0];
159 $defaults['entity_status_2'] = $explodeStartActionCondition[1];
161 if (self
::$_scheduleReminderDetails->entity_status
) {
162 $defaults['repeats_by'] = 2;
164 if (self
::$_excludeDateInfo) {
165 $defaults['exclude_date_list'] = implode(',', self
::$_excludeDateInfo);
174 * @param CRM_Core_Form $form
176 public static function buildQuickForm(&$form) {
177 // FIXME: this is using the following as keys rather than the standard numeric keys returned by CRM_Utils_Date
188 foreach (CRM_Utils_Date
::getAbbrWeekdayNames() as $k => $label) {
189 $dayOfTheWeek[$dayKeys[$k]] = $label;
191 $form->add('select', 'repetition_frequency_unit', ts('Repeats every'), CRM_Core_SelectValues
::getRecurringFrequencyUnits(), FALSE, ['class' => 'required']);
192 $numericOptions = CRM_Core_SelectValues
::getNumericOptions(1, 30);
193 $form->add('select', 'repetition_frequency_interval', NULL, $numericOptions, FALSE, ['class' => 'required']);
194 $form->add('datepicker', 'repetition_start_date', ts('Start Date'), [], FALSE, ['time' => TRUE]);
195 foreach ($dayOfTheWeek as $key => $val) {
196 $startActionCondition[] = $form->createElement('checkbox', $key, NULL, $val);
198 $form->addGroup($startActionCondition, 'start_action_condition', ts('Repeats on'));
200 '1' => ts('day of the month'),
201 '2' => ts('day of the week'),
203 $form->addRadio('repeats_by', ts("Repeats on"), $roptionTypes, ['required' => TRUE], NULL);
204 $form->add('select', 'limit_to', '', CRM_Core_SelectValues
::getNumericOptions(1, 31));
206 'first' => ts('First'),
207 'second' => ts('Second'),
208 'third' => ts('Third'),
209 'fourth' => ts('Fourth'),
210 'last' => ts('Last'),
212 $form->add('select', 'entity_status_1', '', $dayOfTheWeekNo);
213 $form->add('select', 'entity_status_2', '', $dayOfTheWeek);
218 $form->addRadio('ends', ts("Ends"), $eoptionTypes, ['class' => 'required'], NULL);
219 // Offset options gets key=>val pairs like 1=>2 because the BAO wants to know the number of
220 // children while it makes more sense to the user to see the total number including the parent.
221 $offsetOptions = range(1, 30);
222 unset($offsetOptions[0]);
223 $form->add('select', 'start_action_offset', NULL, $offsetOptions, FALSE);
224 $form->addFormRule(['CRM_Core_Form_RecurringEntity', 'formRule']);
225 $form->add('datepicker', 'repeat_absolute_date', ts('On'), [], FALSE, ['time' => FALSE]);
226 $form->add('text', 'exclude_date_list', ts('Exclude Dates'), ['class' => 'twenty']);
227 $form->addElement('hidden', 'allowRepeatConfigToSubmit', '', ['id' => 'allowRepeatConfigToSubmit']);
231 'name' => ts('Save'),
236 'name' => ts('Cancel'),
239 // For client-side pluralization
240 $form->assign('recurringFrequencyOptions', [
241 'single' => CRM_Utils_Array
::makeNonAssociative(CRM_Core_SelectValues
::getRecurringFrequencyUnits()),
242 'plural' => CRM_Utils_Array
::makeNonAssociative(CRM_Core_SelectValues
::getRecurringFrequencyUnits(2)),
247 * Global validation rules for the form.
249 * @param array $values
250 * Posted values of the form.
253 * list of errors to be posted back to the form
255 public static function formRule($values) {
257 //Process this function only when you get this variable
258 if ($values['allowRepeatConfigToSubmit'] == 1) {
259 $dayOfTheWeek = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
261 if (empty($values['repetition_frequency_unit'])) {
262 $errors['repetition_frequency_unit'] = ts('This is a required field');
265 if (empty($values['repetition_frequency_interval'])) {
266 $errors['repetition_frequency_interval'] = ts('This is a required field');
269 if (!empty($values['ends'])) {
270 if ($values['ends'] == 1) {
271 if (empty($values['start_action_offset'])) {
272 $errors['start_action_offset'] = ts('This is a required field');
274 elseif ($values['start_action_offset'] > 30) {
275 $errors['start_action_offset'] = ts('Occurrences should be less than or equal to 30');
278 if ($values['ends'] == 2) {
279 if (!empty($values['repeat_absolute_date'])) {
280 $entityStartDate = CRM_Utils_Date
::processDate($values['repetition_start_date']);
281 $end = CRM_Utils_Date
::processDate($values['repeat_absolute_date']);
282 if (($end < $entityStartDate) && ($end != 0)) {
283 $errors['repeat_absolute_date'] = ts('End date should be after current entity\'s start date');
287 $errors['repeat_absolute_date'] = ts('This is a required field');
292 $errors['ends'] = ts('This is a required field');
296 if (!empty($values['repeats_by'])) {
297 if ($values['repeats_by'] == 1) {
298 if (!empty($values['limit_to'])) {
299 if ($values['limit_to'] < 1 && $values['limit_to'] > 31) {
300 $errors['limit_to'] = ts('Invalid day of the month');
304 $errors['limit_to'] = ts('Invalid day of the month');
307 if ($values['repeats_by'] == 2) {
308 if (!empty($values['entity_status_1'])) {
309 $dayOfTheWeekNo = ['first', 'second', 'third', 'fourth', 'last'];
310 if (!in_array($values['entity_status_1'], $dayOfTheWeekNo)) {
311 $errors['entity_status_1'] = ts('Invalid option');
315 $errors['entity_status_1'] = ts('Invalid option');
317 if (!empty($values['entity_status_2'])) {
318 if (!in_array($values['entity_status_2'], $dayOfTheWeek)) {
319 $errors['entity_status_2'] = ts('Invalid day name');
323 $errors['entity_status_2'] = ts('Invalid day name');
332 * Process the form submission.
334 * @param array $params
335 * @param string $type
336 * @param array $linkedEntities
338 * @throws \CiviCRM_API3_Exception
340 public static function postProcess($params = [], $type, $linkedEntities = []) {
341 // Check entity_id not present in params take it from class variable
342 if (empty($params['entity_id'])) {
343 $params['entity_id'] = self
::$_entityId;
345 //Process this function only when you get this variable
346 if ($params['allowRepeatConfigToSubmit'] == 1) {
347 if (!empty($params['entity_table']) && !empty($params['entity_id']) && $type) {
348 $params['used_for'] = $type;
349 if (empty($params['parent_entity_id'])) {
350 $params['parent_entity_id'] = self
::$_parentEntityId;
352 if (!empty($params['schedule_reminder_id'])) {
353 $params['id'] = $params['schedule_reminder_id'];
356 $params['id'] = self
::$_scheduleReminderID;
359 //Save post params to the schedule reminder table
360 $recurobj = new CRM_Core_BAO_RecurringEntity();
361 $dbParams = $recurobj->mapFormValuesToDB($params);
363 //Delete repeat configuration and rebuild
364 if (!empty($params['id'])) {
365 CRM_Core_BAO_ActionSchedule
::del($params['id']);
366 unset($params['id']);
368 $actionScheduleObj = CRM_Core_BAO_ActionSchedule
::add($dbParams);
371 $excludeDateList = [];
372 if (!empty($params['exclude_date_list']) && !empty($params['parent_entity_id']) && $actionScheduleObj->entity_value
) {
373 //Since we get comma separated values lets get them in array
374 $excludeDates = explode(",", $params['exclude_date_list']);
376 //Check if there exists any values for this option group
377 $optionGroupIdExists = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup',
378 $type . '_repeat_exclude_dates_' . $params['parent_entity_id'],
382 if ($optionGroupIdExists) {
383 CRM_Core_BAO_OptionGroup
::del($optionGroupIdExists);
385 $optionGroupParams = [
386 'name' => $type . '_repeat_exclude_dates_' . $actionScheduleObj->entity_value
,
387 'title' => $type . ' recursion',
391 $opGroup = CRM_Core_BAO_OptionGroup
::add($optionGroupParams);
394 $fieldValues = ['option_group_id' => $opGroup->id
];
395 foreach ($excludeDates as $val) {
396 $optionGroupValue = [
397 'option_group_id' => $opGroup->id
,
398 'label' => CRM_Utils_Date
::processDate($val),
399 'value' => CRM_Utils_Date
::processDate($val),
400 'name' => $opGroup->name
,
401 'description' => 'Used for recurring ' . $type,
402 'weight' => CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array
::value('weight', $params), $fieldValues),
405 $excludeDateList[] = $optionGroupValue['value'];
406 CRM_Core_BAO_OptionValue
::create($optionGroupValue);
412 $apiEntityType = explode("_", $type);
413 if (!empty($apiEntityType[1])) {
414 $apiType = $apiEntityType[1];
416 //Delete relations if any from recurring entity tables before inserting new relations for this entity id
417 if ($params['entity_id']) {
418 //If entity has any pre delete function, consider that first
419 if (CRM_Utils_Array
::value('pre_delete_func', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]) &&
420 CRM_Utils_Array
::value('helper_class', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']])
422 $preDeleteResult = call_user_func_array(CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]['pre_delete_func'], [$params['entity_id']]);
423 if (!empty($preDeleteResult)) {
424 call_user_func([CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]['helper_class'], $preDeleteResult]);
427 //Ready to execute delete on entities if it has delete function set
428 if (CRM_Utils_Array
::value('delete_func', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]) &&
429 CRM_Utils_Array
::value('helper_class', CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']])
431 //Check if pre delete function has some ids to be deleted
432 if (!empty(CRM_Core_BAO_RecurringEntity
::$_entitiesToBeDeleted)) {
433 foreach (CRM_Core_BAO_RecurringEntity
::$_entitiesToBeDeleted as $eid) {
434 $result = civicrm_api3(
435 ucfirst(strtolower($apiType)),
436 CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
442 if ($result['error']) {
443 CRM_Core_Error
::statusBounce('Error creating recurring list');
448 $getRelatedEntities = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($params['entity_id'], $params['entity_table'], FALSE);
449 foreach ($getRelatedEntities as $key => $value) {
450 $result = civicrm_api3(
451 ucfirst(strtolower($apiType)),
452 CRM_Core_BAO_RecurringEntity
::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
455 'id' => $value['id'],
458 if ($result['error']) {
459 CRM_Core_Error
::statusBounce('Error creating recurring list');
465 // find all entities from the recurring set. At this point we 'll get entities which were not deleted
466 // for e.g due to participants being present. We need to delete them from recurring tables anyway.
467 $pRepeatingEntities = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($params['entity_id'], $params['entity_table']);
468 foreach ($pRepeatingEntities as $val) {
469 CRM_Core_BAO_RecurringEntity
::delEntity($val['id'], $val['table'], TRUE);
473 $recursion = new CRM_Core_BAO_RecurringEntity();
474 $recursion->dateColumns
= $params['dateColumns'];
475 $recursion->scheduleId
= $actionScheduleObj->id
;
477 if (!empty($excludeDateList)) {
478 $recursion->excludeDates
= $excludeDateList;
479 $recursion->excludeDateRangeColumns
= $params['excludeDateRangeColumns'];
481 if (!empty($params['intervalDateColumns'])) {
482 $recursion->intervalDateColumns
= $params['intervalDateColumns'];
484 $recursion->entity_id
= $params['entity_id'];
485 $recursion->entity_table
= $params['entity_table'];
486 if (!empty($linkedEntities)) {
487 $recursion->linkedEntities
= $linkedEntities;
490 $recursion->generate();
492 $status = ts('Repeat Configuration has been saved');
493 CRM_Core_Session
::setStatus($status, ts('Saved'), 'success');
499 * Return a descriptive name for the page, used in wizard header
503 public function getTitle() {
504 return ts('Repeat Entity');