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