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