commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-new / civicrm / CRM / Core / Form / RecurringEntity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 CRM_Core_OptionValue::getValues(array('name' => $entityTable . '_repeat_exclude_dates_' . self::$_parentEntityId), $optionValue);
100 $excludeOptionValues = array();
101 if (!empty($optionValue)) {
102 foreach ($optionValue as $key => $val) {
103 $excludeOptionValues[$val['value']] = substr(CRM_Utils_Date::mysqlToIso($val['value']), 0, 10);
104 }
105 self::$_excludeDateInfo = $excludeOptionValues;
106 }
107
108 // Assign variables
109 $entityType = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable));
110 $tpl = CRM_Core_Smarty::singleton();
111 $tpl->assign('recurringEntityType', ts($entityType));
112 $tpl->assign('currentEntityId', self::$_entityId);
113 $tpl->assign('entityTable', self::$_entityTable);
114 $tpl->assign('scheduleReminderId', self::$_scheduleReminderID);
115 $tpl->assign('hasParent', self::$_hasParent);
116 }
117
118 /**
119 * Set default values for the form. For edit/view mode
120 * the default values are retrieved from the database
121 *
122 *
123 * @return array
124 */
125 public static function setDefaultValues() {
126 // Defaults for new entity
127 $defaults = array(
128 'repetition_frequency_unit' => 'week',
129 );
130
131 // Default for existing entity
132 if (self::$_scheduleReminderID) {
133 $defaults['repetition_frequency_unit'] = self::$_scheduleReminderDetails->repetition_frequency_unit;
134 $defaults['repetition_frequency_interval'] = self::$_scheduleReminderDetails->repetition_frequency_interval;
135 $defaults['start_action_condition'] = array_flip(explode(",", self::$_scheduleReminderDetails->start_action_condition));
136 foreach ($defaults['start_action_condition'] as $key => $val) {
137 $val = 1;
138 $defaults['start_action_condition'][$key] = $val;
139 }
140 $defaults['start_action_offset'] = self::$_scheduleReminderDetails->start_action_offset;
141 if (self::$_scheduleReminderDetails->start_action_offset) {
142 $defaults['ends'] = 1;
143 }
144 list($defaults['repeat_absolute_date']) = CRM_Utils_Date::setDateDefaults(self::$_scheduleReminderDetails->absolute_date);
145 if (self::$_scheduleReminderDetails->absolute_date) {
146 $defaults['ends'] = 2;
147 }
148 $defaults['limit_to'] = self::$_scheduleReminderDetails->limit_to;
149 if (self::$_scheduleReminderDetails->limit_to) {
150 $defaults['repeats_by'] = 1;
151 }
152 if (self::$_scheduleReminderDetails->entity_status) {
153 $explodeStartActionCondition = explode(" ", self::$_scheduleReminderDetails->entity_status);
154 $defaults['entity_status_1'] = $explodeStartActionCondition[0];
155 $defaults['entity_status_2'] = $explodeStartActionCondition[1];
156 }
157 if (self::$_scheduleReminderDetails->entity_status) {
158 $defaults['repeats_by'] = 2;
159 }
160 if (self::$_excludeDateInfo) {
161 $defaults['exclude_date_list'] = implode(',', self::$_excludeDateInfo);
162 }
163 }
164 return $defaults;
165 }
166
167 /**
168 * Build form.
169 *
170 * @param CRM_Core_Form $form
171 */
172 public static function buildQuickForm(&$form) {
173 // For some reason this is using the following as keys rather than the standard numeric keys returned by CRM_Utils_Date
174 $dayOfTheWeek = array(
175 'sunday',
176 'monday',
177 'tuesday',
178 'wednesday',
179 'thursday',
180 'friday',
181 'saturday',
182 );
183 $dayOfTheWeek = array_combine($dayOfTheWeek, CRM_Utils_Date::getAbbrWeekdayNames());
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->addDateTime('repetition_start_date', ts('Repetition Start Date'), FALSE, array('formatType' => 'activityDateTime'));
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 by"), $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->addDate('repeat_absolute_date', ts('On'), FALSE, array('formatType' => 'mailing'));
219 $form->add('text', 'exclude_date_list', ts('Exclude Dates'), array(
220 'class' => 'twenty',
221 ));
222 $form->addElement('hidden', 'allowRepeatConfigToSubmit', '', array('id' => 'allowRepeatConfigToSubmit'));
223 $form->addButtons(array(
224 array(
225 'type' => 'submit',
226 'name' => ts('Save'),
227 'isDefault' => TRUE,
228 ),
229 array(
230 'type' => 'cancel',
231 'name' => ts('Cancel'),
232 ),
233 )
234 );
235 // For client-side pluralization
236 $form->assign('recurringFrequencyOptions', array(
237 'single' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::getRecurringFrequencyUnits()),
238 'plural' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::getRecurringFrequencyUnits(2)),
239 ));
240 }
241
242 /**
243 * Global validation rules for the form.
244 *
245 * @param array $values
246 * Posted values of the form.
247 *
248 * @return array
249 * list of errors to be posted back to the form
250 */
251 public static function formRule($values) {
252 $errors = array();
253 //Process this function only when you get this variable
254 if ($values['allowRepeatConfigToSubmit'] == 1) {
255 $dayOfTheWeek = array('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday');
256 //Repeats
257 if (empty($values['repetition_frequency_unit'])) {
258 $errors['repetition_frequency_unit'] = ts('This is a required field');
259 }
260 //Repeats every
261 if (empty($values['repetition_frequency_interval'])) {
262 $errors['repetition_frequency_interval'] = ts('This is a required field');
263 }
264 //Ends
265 if (!empty($values['ends'])) {
266 if ($values['ends'] == 1) {
267 if (empty($values['start_action_offset'])) {
268 $errors['start_action_offset'] = ts('This is a required field');
269 }
270 elseif ($values['start_action_offset'] > 30) {
271 $errors['start_action_offset'] = ts('Occurrences should be less than or equal to 30');
272 }
273 }
274 if ($values['ends'] == 2) {
275 if (!empty($values['repeat_absolute_date'])) {
276 $entityStartDate = CRM_Utils_Date::processDate($values['repetition_start_date']);
277 $end = CRM_Utils_Date::processDate($values['repeat_absolute_date']);
278 if (($end < $entityStartDate) && ($end != 0)) {
279 $errors['repeat_absolute_date'] = ts('End date should be after current entity\'s start date');
280 }
281 }
282 else {
283 $errors['repeat_absolute_date'] = ts('This is a required field');
284 }
285 }
286 }
287 else {
288 $errors['ends'] = ts('This is a required field');
289 }
290
291 //Repeats BY
292 if (!empty($values['repeats_by'])) {
293 if ($values['repeats_by'] == 1) {
294 if (!empty($values['limit_to'])) {
295 if ($values['limit_to'] < 1 && $values['limit_to'] > 31) {
296 $errors['limit_to'] = ts('Invalid day of the month');
297 }
298 }
299 else {
300 $errors['limit_to'] = ts('Invalid day of the month');
301 }
302 }
303 if ($values['repeats_by'] == 2) {
304 if (!empty($values['entity_status_1'])) {
305 $dayOfTheWeekNo = array('first', 'second', 'third', 'fourth', 'last');
306 if (!in_array($values['entity_status_1'], $dayOfTheWeekNo)) {
307 $errors['entity_status_1'] = ts('Invalid option');
308 }
309 }
310 else {
311 $errors['entity_status_1'] = ts('Invalid option');
312 }
313 if (!empty($values['entity_status_2'])) {
314 if (!in_array($values['entity_status_2'], $dayOfTheWeek)) {
315 $errors['entity_status_2'] = ts('Invalid day name');
316 }
317 }
318 else {
319 $errors['entity_status_2'] = ts('Invalid day name');
320 }
321 }
322 }
323 }
324 return $errors;
325 }
326
327 /**
328 * Process the form submission.
329 *
330 *
331 * @return void
332 */
333 public static function postProcess($params = array(), $type, $linkedEntities = array()) {
334 //Check entity_id not present in params take it from class variable
335 if (empty($params['entity_id'])) {
336 $params['entity_id'] = self::$_entityId;
337 }
338 //Process this function only when you get this variable
339 if ($params['allowRepeatConfigToSubmit'] == 1) {
340 if (!empty($params['entity_table']) && !empty($params['entity_id']) && $type) {
341 $params['used_for'] = $type;
342 if (empty($params['parent_entity_id'])) {
343 $params['parent_entity_id'] = self::$_parentEntityId;
344 }
345 if (!empty($params['schedule_reminder_id'])) {
346 $params['id'] = $params['schedule_reminder_id'];
347 }
348 else {
349 $params['id'] = self::$_scheduleReminderID;
350 }
351
352 //Save post params to the schedule reminder table
353 $recurobj = new CRM_Core_BAO_RecurringEntity();
354 $dbParams = $recurobj->mapFormValuesToDB($params);
355
356 //Delete repeat configuration and rebuild
357 if (!empty($params['id'])) {
358 CRM_Core_BAO_ActionSchedule::del($params['id']);
359 unset($params['id']);
360 }
361 $actionScheduleObj = CRM_Core_BAO_ActionSchedule::add($dbParams);
362
363 //exclude dates
364 $excludeDateList = array();
365 if (CRM_Utils_Array::value('exclude_date_list', $params) && CRM_Utils_Array::value('parent_entity_id', $params) && $actionScheduleObj->entity_value) {
366 //Since we get comma separated values lets get them in array
367 $excludeDates = explode(",", $params['exclude_date_list']);
368
369 //Check if there exists any values for this option group
370 $optionGroupIdExists = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
371 $type . '_repeat_exclude_dates_' . $params['parent_entity_id'],
372 'id',
373 'name'
374 );
375 if ($optionGroupIdExists) {
376 CRM_Core_BAO_OptionGroup::del($optionGroupIdExists);
377 }
378 $optionGroupParams = array(
379 'name' => $type . '_repeat_exclude_dates_' . $actionScheduleObj->entity_value,
380 'title' => $type . ' recursion',
381 'is_reserved' => 0,
382 'is_active' => 1,
383 );
384 $opGroup = CRM_Core_BAO_OptionGroup::add($optionGroupParams);
385 if ($opGroup->id) {
386 $oldWeight = 0;
387 $fieldValues = array('option_group_id' => $opGroup->id);
388 foreach ($excludeDates as $val) {
389 $optionGroupValue = array(
390 'option_group_id' => $opGroup->id,
391 'label' => CRM_Utils_Date::processDate($val),
392 'value' => CRM_Utils_Date::processDate($val),
393 'name' => $opGroup->name,
394 'description' => 'Used for recurring ' . $type,
395 'weight' => CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues),
396 'is_active' => 1,
397 );
398 $excludeDateList[] = $optionGroupValue['value'];
399 CRM_Core_BAO_OptionValue::create($optionGroupValue);
400 }
401 }
402 }
403
404 //Set type for API
405 $apiEntityType = explode("_", $type);
406 if (!empty($apiEntityType[1])) {
407 $apiType = $apiEntityType[1];
408 }
409 //Delete relations if any from recurring entity tables before inserting new relations for this entity id
410 if ($params['entity_id']) {
411 //If entity has any pre delete function, consider that first
412 if (CRM_Utils_Array::value('pre_delete_func', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]) &&
413 CRM_Utils_Array::value('helper_class', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']])
414 ) {
415 $preDeleteResult = call_user_func_array(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['pre_delete_func'], array($params['entity_id']));
416 if (!empty($preDeleteResult)) {
417 call_user_func(array(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['helper_class'], $preDeleteResult));
418 }
419 }
420 //Ready to execute delete on entities if it has delete function set
421 if (CRM_Utils_Array::value('delete_func', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]) &&
422 CRM_Utils_Array::value('helper_class', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']])
423 ) {
424 //Check if pre delete function has some ids to be deleted
425 if (!empty(CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted)) {
426 foreach (CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted as $eid) {
427 $result = civicrm_api3(
428 ucfirst(strtolower($apiType)),
429 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
430 array(
431 'sequential' => 1,
432 'id' => $eid,
433 )
434 );
435 if ($result['error']) {
436 CRM_Core_Error::statusBounce('Error creating recurring list');
437 }
438 }
439 }
440 else {
441 $getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($params['entity_id'], $params['entity_table'], FALSE);
442 foreach ($getRelatedEntities as $key => $value) {
443 $result = civicrm_api3(
444 ucfirst(strtolower($apiType)),
445 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
446 array(
447 'sequential' => 1,
448 'id' => $value['id'],
449 )
450 );
451 if ($result['error']) {
452 CRM_Core_Error::statusBounce('Error creating recurring list');
453 }
454 }
455 }
456 }
457
458 // find all entities from the recurring set. At this point we 'll get entities which were not deleted
459 // for e.g due to participants being present. We need to delete them from recurring tables anyway.
460 $pRepeatingEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($params['entity_id'], $params['entity_table']);
461 foreach ($pRepeatingEntities as $val) {
462 CRM_Core_BAO_RecurringEntity::delEntity($val['id'], $val['table'], TRUE);
463 }
464 }
465
466 $recursion = new CRM_Core_BAO_RecurringEntity();
467 $recursion->dateColumns = $params['dateColumns'];
468 $recursion->scheduleId = $actionScheduleObj->id;
469
470 if (!empty($excludeDateList)) {
471 $recursion->excludeDates = $excludeDateList;
472 $recursion->excludeDateRangeColumns = $params['excludeDateRangeColumns'];
473 }
474 if (!empty($params['intervalDateColumns'])) {
475 $recursion->intervalDateColumns = $params['intervalDateColumns'];
476 }
477 $recursion->entity_id = $params['entity_id'];
478 $recursion->entity_table = $params['entity_table'];
479 if (!empty($linkedEntities)) {
480 $recursion->linkedEntities = $linkedEntities;
481 }
482
483 $recursion->generate();
484
485 $status = ts('Repeat Configuration has been saved');
486 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
487 }
488 }
489 }
490
491 /**
492 * Return a descriptive name for the page, used in wizard header
493 *
494 * @return string
495 */
496 public function getTitle() {
497 return ts('Repeat Entity');
498 }
499
500 }