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