event recreation from child - delete record for entity going to be a new parent
[civicrm-core.git] / CRM / Core / Form / RecurringEntity.php
CommitLineData
62933949 1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
33 * $Id$
34 *
35 */
36/**
78fe87e6 37 * This class generates form components for processing Entity
62933949 38 *
39 */
40class CRM_Core_Form_RecurringEntity {
41 /**
42 * Current entity id
43 */
44 protected static $_entityId = NULL;
45
78fe87e6 46 /**
47 * Schedule Reminder ID
48 */
49 protected static $_scheduleReminderID = NULL;
50
51 /**
52 * Schedule Reminder data
53 */
54 protected static $_scheduleReminderDetails = array();
55
56 /**
57 * Parent Entity ID
58 */
59 protected static $_parentEntityId = NULL;
60
61 /**
62 * Exclude date information
63 */
64 public static $_excludeDateInfo = array();
65
a7ea18bf 66 /**
8cec51b0 67 * Entity Table
68 */
69 public static $_entityTable;
b09e7ce7 70
6266861e 71 /**
72 * Checks current entityID has parent
73 */
74 public static $_hasParent = FALSE;
75
8cec51b0 76 static function preProcess($entityTable) {
77 self::$_entityId = (int) CRM_Utils_Request::retrieve('id', 'Positive');
78 self::$_entityTable = $entityTable;
b09e7ce7 79
8cec51b0 80 if (self::$_entityId && $entityTable) {
81 $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor(self::$_entityId, $entityTable);
8cec51b0 82 if ($checkParentExistsForThisId) {
83 self::$_hasParent = TRUE;
84 self::$_parentEntityId = $checkParentExistsForThisId;
b09e7ce7 85 self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $entityTable);
8cec51b0 86 }
87 else {
88 self::$_parentEntityId = self::$_entityId;
b09e7ce7 89 self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId(self::$_entityId, $entityTable);
8cec51b0 90 }
91 self::$_scheduleReminderID = self::$_scheduleReminderDetails->id;
92 }
b09e7ce7 93 if ($entityTable) {
94 CRM_Core_OptionValue::getValues(array('name' => $entityTable.'_repeat_exclude_dates_'.self::$_parentEntityId), $optionValue);
8cec51b0 95 $excludeOptionValues = array();
96 if (!empty($optionValue)) {
97 foreach($optionValue as $key => $val) {
98 $excludeOptionValues[$val['value']] = date('m/d/Y', strtotime($val['value']));
99 }
100 self::$_excludeDateInfo = $excludeOptionValues;
78fe87e6 101 }
6266861e 102 }
78fe87e6 103 }
104
105 /**
106 * This function sets the default values for the form. For edit/view mode
107 * the default values are retrieved from the database
108 *
109 * @access public
110 *
111 * @return None
112 */
113 static function setDefaultValues() {
114 $defaults = array();
115 if (self::$_scheduleReminderID) {
116 $defaults['repetition_frequency_unit'] = self::$_scheduleReminderDetails->repetition_frequency_unit;
117 $defaults['repetition_frequency_interval'] = self::$_scheduleReminderDetails->repetition_frequency_interval;
118 $defaults['start_action_condition'] = array_flip(explode(",",self::$_scheduleReminderDetails->start_action_condition));
119 foreach($defaults['start_action_condition'] as $key => $val) {
120 $val = 1;
121 $defaults['start_action_condition'][$key] = $val;
122 }
123 $defaults['start_action_offset'] = self::$_scheduleReminderDetails->start_action_offset;
124 if (self::$_scheduleReminderDetails->start_action_offset) {
125 $defaults['ends'] = 1;
126 }
127 list($defaults['repeat_absolute_date']) = CRM_Utils_Date::setDateDefaults(self::$_scheduleReminderDetails->absolute_date);
128 if (self::$_scheduleReminderDetails->absolute_date) {
129 $defaults['ends'] = 2;
130 }
131 $defaults['limit_to'] = self::$_scheduleReminderDetails->limit_to;
132 if (self::$_scheduleReminderDetails->limit_to) {
133 $defaults['repeats_by'] = 1;
134 }
135 $explodeStartActionCondition = array();
136 if (self::$_scheduleReminderDetails->entity_status) {
137 $explodeStartActionCondition = explode(" ", self::$_scheduleReminderDetails->entity_status);
138 $defaults['entity_status_1'] = $explodeStartActionCondition[0];
139 $defaults['entity_status_2'] = $explodeStartActionCondition[1];
140 }
141 if (self::$_scheduleReminderDetails->entity_status) {
142 $defaults['repeats_by'] = 2;
143 }
144 }
145 return $defaults;
146 }
147
62933949 148 static function buildQuickForm(&$form) {
62933949 149 $form->assign('currentEntityId', self::$_entityId);
8cec51b0 150 $form->assign('entityTable', self::$_entityTable);
a83e7558 151 $form->assign('scheduleReminderId', self::$_scheduleReminderID);
6266861e 152 $form->assign('hasParent', self::$_hasParent);
62933949 153
154 $form->_freqUnits = array('hour' => 'hour') + CRM_Core_OptionGroup::values('recur_frequency_units');
155 foreach ($form->_freqUnits as $val => $label) {
a50a97b8 156 if ($label == "day") {
62933949 157 $label = "dai";
158 }
159 $freqUnitsDisplay[$val] = ts('%1ly', array(1 => $label));
160 }
161 // echo "<pre>";print_r($freqUnitsDisplay);
162 $dayOfTheWeek = array('monday' => 'Monday',
163 'tuesday' => 'Tuesday',
164 'wednesday' => 'Wednesday',
165 'thursday' => 'Thursday',
166 'friday' => 'Friday',
167 'saturday' => 'Saturday',
168 'sunday' => 'Sunday'
169 );
ba4e7023 170 $form->add('select', 'repetition_frequency_unit', ts('Repeats:'), $freqUnitsDisplay);
62933949 171 $numericOptions = CRM_Core_SelectValues::getNumericOptions(1, 30);
ba4e7023 172 $form->add('select', 'repetition_frequency_interval', ts('Repeats every:'), $numericOptions, '', array('style' => 'width:55px;'));
66f66040 173 $form->addDateTime('repetition_start_date', ts('Repetition Start Date'), FALSE, array('formatType' => 'activityDateTime'));
a50a97b8 174 foreach($dayOfTheWeek as $key => $val) {
62933949 175 $startActionCondition[] = $form->createElement('checkbox', $key, NULL, substr($val."&nbsp;", 0, 3));
176 }
177 $form->addGroup($startActionCondition, 'start_action_condition', ts('Repeats on'));
178 $roptionTypes = array('1' => ts('day of the month'),
179 '2' => ts('day of the week'),
180 );
181 $form->addRadio('repeats_by', ts("Repeats By:"), $roptionTypes, array(), NULL);
182 $getMonths = CRM_Core_SelectValues::getNumericOptions(1, 31);
b1d1479a 183 $form->add('select', 'limit_to', '', $getMonths, FALSE, array('style' => 'width:55px;'));
62933949 184 $dayOfTheWeekNo = array('first' => 'First',
185 'second'=> 'Second',
186 'third' => 'Third',
187 'fourth'=> 'Fourth',
188 'last' => 'Last'
189 );
a1a821bc 190 $form->add('select', 'entity_status_1', ts(''), $dayOfTheWeekNo);
191 $form->add('select', 'entity_status_2', ts(''), $dayOfTheWeek);
62933949 192 $eoptionTypes = array('1' => ts('After'),
193 '2' => ts('On'),
194 );
ba4e7023 195 $form->addRadio('ends', ts("Ends:"), $eoptionTypes, array(), NULL);
431b0ca8 196 $form->add('text', 'start_action_offset', ts(''), array('size' => 3, 'maxlength' => 2));
62933949 197 $form->addFormRule(array('CRM_Core_Form_RecurringEntity', 'formRule'));
198 $form->addDate('repeat_absolute_date', ts('On'), FALSE, array('formatType' => 'mailing'));
199 $form->addDate('exclude_date', ts('Exclude Date(s)'), FALSE);
7af8fab4 200 $select = $form->add('select', 'exclude_date_list', ts(''), self::$_excludeDateInfo, FALSE, array('style' => 'width:150px;', 'size' => 4));
62933949 201 $select->setMultiple(TRUE);
202 $form->addElement('button','add_to_exclude_list','>>','onClick="addToExcludeList(document.getElementById(\'exclude_date\').value);"');
203 $form->addElement('button','remove_from_exclude_list', '<<', 'onClick="removeFromExcludeList(\'exclude_date_list\')"');
62933949 204 $form->addElement('hidden', 'copyExcludeDates', '', array('id' => 'copyExcludeDates'));
ba4e7023 205 $form->addElement('hidden', 'allowRepeatConfigToSubmit', '', array('id' => 'allowRepeatConfigToSubmit'));
62933949 206 $form->addButtons(array(
207 array(
208 'type' => 'submit',
209 'name' => ts('Save'),
210 'isDefault' => TRUE,
211 ),
212 array(
213 'type' => 'cancel',
214 'name' => ts('Cancel')
215 ),
216 )
217 );
218 }
219
220 /**
221 * global validation rules for the form
222 *
223 * @param array $fields posted values of the form
224 *
225 * @return array list of errors to be posted back to the form
226 * @static
227 * @access public
228 */
229 static function formRule($values) {
230 $errors = array();
ba4e7023 231 //Process this function only when you get this variable
232 if ($values['allowRepeatConfigToSubmit'] == 1) {
233 $dayOfTheWeek = array(monday,tuesday,wednesday,thursday,friday,saturday,sunday);
234 //Repeats
235 if (!CRM_Utils_Array::value('repetition_frequency_unit', $values)) {
236 $errors['repetition_frequency_unit'] = ts('This is a required field');
237 }
238 //Repeats every
239 if (!CRM_Utils_Array::value('repetition_frequency_interval', $values)) {
240 $errors['repetition_frequency_interval'] = ts('This is a required field');
62933949 241 }
ba4e7023 242 //Ends
243 if (CRM_Utils_Array::value('ends', $values)) {
244 if ($values['ends'] == 1) {
245 if ($values['start_action_offset'] == "") {
246 $errors['start_action_offset'] = ts('This is a required field');
247 }
248 else if ($values['start_action_offset'] > 30) {
249 $errors['start_action_offset'] = ts('Occurrences should be less than or equal to 30');
62933949 250 }
a50a97b8 251 }
ba4e7023 252 if ($values['ends'] == 2) {
253 if ($values['repeat_absolute_date'] != "") {
254 $entityStartDate = CRM_Utils_Date::processDate($values['repetition_start_date']);
255 $end = CRM_Utils_Date::processDate($values['repeat_absolute_date']);
256 if (($end < $entityStartDate) && ($end != 0)) {
257 $errors['repeat_absolute_date'] = ts('End date should be after current entity\'s start date');
258 }
259 }
260 else {
261 $errors['repeat_absolute_date'] = ts('This is a required field');
262 }
62933949 263 }
264 }
ba4e7023 265 else {
266 $errors['ends'] = ts('This is a required field');
267 }
268
269 //Repeats BY
270 if (CRM_Utils_Array::value('repeats_by', $values)) {
271 if ($values['repeats_by'] == 1) {
272 if ($values['limit_to'] != "") {
273 if ($values['limit_to'] < 1 && $values['limit_to'] > 31) {
274 $errors['limit_to'] = ts('Invalid day of the month');
275 }
276 }
277 else {
62933949 278 $errors['limit_to'] = ts('Invalid day of the month');
279 }
a50a97b8 280 }
ba4e7023 281 if ($values['repeats_by'] == 2) {
282 if ($values['entity_status_1'] != "" ) {
283 $dayOfTheWeekNo = array(first, second, third, fourth, last);
284 if (!in_array($values['entity_status_1'], $dayOfTheWeekNo)) {
285 $errors['entity_status_1'] = ts('Invalid option');
286 }
62933949 287 }
ba4e7023 288 else {
289 $errors['entity_status_1'] = ts('Invalid option');
290 }
291 if ($values['entity_status_2'] != "" ) {
292 if (!in_array($values['entity_status_2'], $dayOfTheWeek)) {
293 $errors['entity_status_2'] = ts('Invalid day name');
294 }
295 }
296 else {
297 $errors['entity_status_2'] = ts('Invalid day name');
62933949 298 }
62933949 299 }
300 }
301 }
302 return $errors;
303 }
304
305 /**
306 * Function to process the form
307 *
308 * @access public
309 *
310 * @return None
311 */
78fe87e6 312 static function postProcess($params = array(), $type, $linkedEntities = array()) {
313 $params['entity_id'] = self::$_entityId;
ba4e7023 314 //Process this function only when you get this variable
315 if ($params['allowRepeatConfigToSubmit'] == 1) {
316 if (CRM_Utils_Array::value('entity_table', $params) && CRM_Utils_Array::value('entity_id', $params) && $type) {
317 $params['used_for'] = $type;
318 $params['parent_entity_id'] = self::$_parentEntityId;
319 $params['id'] = self::$_scheduleReminderID;
1b1bde74 320
ba4e7023 321 //Save post params to the schedule reminder table
322 $dbParams = CRM_Core_BAO_RecurringEntity::mapFormValuesToDB($params);
62933949 323
ba4e7023 324 //Delete repeat configuration and rebuild
325 if (CRM_Utils_Array::value('id', $params)) {
326 CRM_Core_BAO_ActionSchedule::del($params['id']);
327 unset($params['id']);
328 }
329 $actionScheduleObj = CRM_Core_BAO_ActionSchedule::add($dbParams);
78fe87e6 330
ba4e7023 331 //exclude dates
332 $excludeDateList = array();
333 if (CRM_Utils_Array::value('copyExcludeDates', $params) && CRM_Utils_Array::value('parent_entity_id', $params)) {
334 //Since we get comma separated values lets get them in array
335 $exclude_date_list = array();
336 $exclude_date_list = explode(",", $params['copyExcludeDates']);
78fe87e6 337
ba4e7023 338 //Check if there exists any values for this option group
339 $optionGroupIdExists = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
340 $type.'_repeat_exclude_dates_'.$params['parent_entity_id'],
341 'id',
342 'name'
78fe87e6 343 );
ba4e7023 344 if ($optionGroupIdExists) {
345 CRM_Core_BAO_OptionGroup::del($optionGroupIdExists);
346 }
347 $optionGroupParams =
348 array(
349 'name' => $type.'_repeat_exclude_dates_'.$params['parent_entity_id'],
350 'title' => $type.' recursion',
351 'is_reserved' => 0,
352 'is_active' => 1
353 );
354 $opGroup = CRM_Core_BAO_OptionGroup::add($optionGroupParams);
355 if ($opGroup->id) {
356 $oldWeight= 0;
357 $fieldValues = array('option_group_id' => $opGroup->id);
358 foreach($exclude_date_list as $val) {
359 $optionGroupValue =
360 array(
361 'option_group_id' => $opGroup->id,
362 'label' => CRM_Utils_Date::processDate($val),
363 'value' => CRM_Utils_Date::processDate($val),
364 'name' => $opGroup->name,
365 'description' => 'Used for recurring '.$type,
366 'weight' => CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues),
367 'is_active' => 1
368 );
369 $excludeDateList[] = $optionGroupValue['value'];
370 CRM_Core_BAO_OptionValue::add($optionGroupValue);
371 }
78fe87e6 372 }
62933949 373 }
dfbe9b91 374
ba4e7023 375 //Set type for API
376 $apiEntityType = array();
377 $apiEntityType = explode("_", $type);
378 if (!empty($apiEntityType[1])) {
379 $apiType = $apiEntityType[1];
5165b19c 380 }
ba4e7023 381 //Delete relations if any from recurring entity tables before inserting new relations for this entity id
382 if ($params['entity_id']) {
383 //If entity has any pre delete function, consider that first
384 if (CRM_Utils_Array::value('pre_delete_func', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]) &&
385 CRM_Utils_Array::value('helper_class', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']])) {
386 call_user_func(array(
387 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['helper_class'],
388 call_user_func_array(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['pre_delete_func'], array($params['entity_id'])))
389 );
390 }
391 //Ready to execute delete on entities if it has delete function set
392 if (CRM_Utils_Array::value('delete_func', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]) &&
20cede00 393 CRM_Utils_Array::value('helper_class', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']])) {
394 //Check if pre delete function has some ids to be deleted
395 if (!empty(CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted)) {
396 foreach (CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted as $eid) {
397 $result = civicrm_api3(
398 ucfirst(strtolower($apiType)),
399 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
400 array(
401 'sequential' => 1,
402 'id' => $eid,
403 )
404 );
405 if ($result['error']) {
406 CRM_Core_Error::statusBounce('Error creating recurring list');
defe2873 407 }
5165b19c 408 }
20cede00 409 }
410 else {
411 $getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($params['entity_id'], $params['entity_table'], FALSE);
412 foreach ($getRelatedEntities as $key => $value) {
413 $result = civicrm_api3(
414 ucfirst(strtolower($apiType)),
415 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
416 array(
417 'sequential' => 1,
418 'id' => $value['id'],
419 )
420 );
421 if ($result['error']) {
422 CRM_Core_Error::statusBounce('Error creating recurring list');
defe2873 423 }
5165b19c 424 }
20cede00 425 }
ba4e7023 426 }
20cede00 427 // lets delete current entity from recurring-entity table, which is going to be a new parent
428 CRM_Core_BAO_RecurringEntity::delEntity($params['entity_id'], $params['entity_table']);
5d4bf2ff 429 }
d10273dc 430
ba4e7023 431 $recursion = new CRM_Core_BAO_RecurringEntity();
432 $recursion->dateColumns = $params['dateColumns'];
433 $recursion->scheduleId = $actionScheduleObj->id;
dfbe9b91 434
ba4e7023 435 if (!empty($excludeDateList)) {
436 $recursion->excludeDates = $excludeDateList;
437 $recursion->excludeDateRangeColumns = $params['excludeDateRangeColumns'];
438 }
439 $recursion->intervalDateColumns = $params['intervalDateColumns'];
440 $recursion->entity_id = $params['entity_id'];
441 $recursion->entity_table = $params['entity_table'];
442 if (!empty($linkedEntities)) {
443 $recursion->linkedEntities = $linkedEntities;
444 }
dc07e5a7 445
ba4e7023 446 $recurResult = $recursion->generate();
dfbe9b91 447
ba4e7023 448 $status = ts('Repeat Configuration has been saved');
449 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
450 }
78fe87e6 451 }
62933949 452 }
453 //end of function
454
455 /**
456 * Return a descriptive name for the page, used in wizard header
457 *
458 * @return string
459 * @access public
460 */
461 public function getTitle() {
fbdee7b7 462 return ts('Repeat Entity');
62933949 463 }
2eeee284 464
62933949 465}