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