towards linked entities and generation
[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 Event
38 *
39 */
40 class CRM_Core_Form_RecurringEntity {
41 /**
42 * Current entity id
43 */
44 protected static $_entityId = NULL;
45
46 static function buildQuickForm(&$form) {
47 //$attributes_schedule = CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionMapping');
48 self::$_entityId = CRM_Utils_Array::value('id', $_GET);
49 $form->assign('currentEntityId', self::$_entityId);
50
51 $form->_freqUnits = array('hour' => 'hour') + CRM_Core_OptionGroup::values('recur_frequency_units');
52 foreach ($form->_freqUnits as $val => $label) {
53 if($label == "day"){
54 $label = "dai";
55 }
56 $freqUnitsDisplay[$val] = ts('%1ly', array(1 => $label));
57 }
58 // echo "<pre>";print_r($freqUnitsDisplay);
59 $dayOfTheWeek = array('monday' => 'Monday',
60 'tuesday' => 'Tuesday',
61 'wednesday' => 'Wednesday',
62 'thursday' => 'Thursday',
63 'friday' => 'Friday',
64 'saturday' => 'Saturday',
65 'sunday' => 'Sunday'
66 );
67 $form->add('select', 'repetition_frequency_unit', ts('Repeats:'), $freqUnitsDisplay, TRUE);
68 $numericOptions = CRM_Core_SelectValues::getNumericOptions(1, 30);
69 $form->add('select', 'repetition_frequency_interval', ts('Repeats every:'), $numericOptions, TRUE, array('style' => 'width:55px;'));
70 $form->addDateTime('repetition_start_date', ts('Repetition Start Date'), FALSE, array('formatType' => 'activityDateTime'));
71 foreach($dayOfTheWeek as $key => $val){
72 $startActionCondition[] = $form->createElement('checkbox', $key, NULL, substr($val."&nbsp;", 0, 3));
73 }
74 $form->addGroup($startActionCondition, 'start_action_condition', ts('Repeats on'));
75 $roptionTypes = array('1' => ts('day of the month'),
76 '2' => ts('day of the week'),
77 );
78 $form->addRadio('repeats_by', ts("Repeats By:"), $roptionTypes, array(), NULL);
79 $getMonths = CRM_Core_SelectValues::getNumericOptions(1, 31);
80 $form->add('select', 'limit_to', '', $getMonths, FALSE, array('style' => 'width:55px;'));
81 $dayOfTheWeekNo = array('first' => 'First',
82 'second'=> 'Second',
83 'third' => 'Third',
84 'fourth'=> 'Fourth',
85 'last' => 'Last'
86 );
87 $form->add('select', 'entity_status_1', ts(''), $dayOfTheWeekNo);
88 $form->add('select', 'entity_status_2', ts(''), $dayOfTheWeek);
89 $eoptionTypes = array('1' => ts('After'),
90 '2' => ts('On'),
91 );
92 $form->addRadio('ends', ts("Ends:"), $eoptionTypes, array(), NULL, TRUE);
93 $form->add('text', 'start_action_offset', ts(''), array('maxlength' => 2));
94 $form->addFormRule(array('CRM_Core_Form_RecurringEntity', 'formRule'));
95 $form->addDate('repeat_absolute_date', ts('On'), FALSE, array('formatType' => 'mailing'));
96 $form->addDate('exclude_date', ts('Exclude Date(s)'), FALSE);
97 $select = $form->add('select', 'exclude_date_list', ts(''), $form->_excludeDateInfo, FALSE, array('style' => 'width:150px;', 'size' => 4));
98 $select->setMultiple(TRUE);
99 $form->addElement('button','add_to_exclude_list','>>','onClick="addToExcludeList(document.getElementById(\'exclude_date\').value);"');
100 $form->addElement('button','remove_from_exclude_list', '<<', 'onClick="removeFromExcludeList(\'exclude_date_list\')"');
101 $form->addElement('hidden', 'isChangeInRepeatConfiguration', '', array('id' => 'isChangeInRepeatConfiguration'));
102 $form->addElement('hidden', 'copyExcludeDates', '', array('id' => 'copyExcludeDates'));
103 $form->addButtons(array(
104 array(
105 'type' => 'submit',
106 'name' => ts('Save'),
107 'isDefault' => TRUE,
108 ),
109 array(
110 'type' => 'cancel',
111 'name' => ts('Cancel')
112 ),
113 )
114 );
115 }
116
117 /**
118 * global validation rules for the form
119 *
120 * @param array $fields posted values of the form
121 *
122 * @return array list of errors to be posted back to the form
123 * @static
124 * @access public
125 */
126 static function formRule($values) {
127 $errors = array();
128 $dayOfTheWeek = array(monday,tuesday,wednesday,thursday,friday,saturday,sunday);
129
130 //Repeats
131 if(!CRM_Utils_Array::value('repetition_frequency_unit', $values)){
132 $errors['repetition_frequency_unit'] = ts('This is a required field');
133 }
134 //Repeats every
135 if(!CRM_Utils_Array::value('repetition_frequency_interval', $values)){
136 $errors['repetition_frequency_interval'] = ts('This is a required field');
137 }
138 //Ends
139 if(CRM_Utils_Array::value('ends', $values)){
140 if($values['ends'] == 1){
141 if ($values['start_action_offset'] == "") {
142 $errors['start_action_offset'] = ts('This is a required field');
143 }else if($values['start_action_offset'] > 30){
144 $errors['start_action_offset'] = ts('Occurrences should be less than or equal to 30');
145 }
146 }
147 if($values['ends'] == 2){
148 if ($values['repeat_absolute_date'] != "") {
149 $today = date("Y-m-d H:i:s");
150 $today = CRM_Utils_Date::processDate($today);
151 $end = CRM_Utils_Date::processDate($values['repeat_absolute_date']);
152 if (($end <= $today) && ($end != 0)) {
153 $errors['repeat_absolute_date'] = ts('End date should be after today\'s date');
154 }
155 }else{
156 $errors['repeat_absolute_date'] = ts('This is a required field');
157 }
158 }
159 }else{
160 $errors['ends'] = ts('This is a required field');
161 }
162
163 //Repeats BY
164 if(CRM_Utils_Array::value('repeats_by', $values)){
165 if($values['repeats_by'] == 1){
166 if($values['limit_to'] != ""){
167 if($values['limit_to'] < 1 && $values['limit_to'] > 31){
168 $errors['limit_to'] = ts('Invalid day of the month');
169 }
170 }else{
171 $errors['limit_to'] = ts('Invalid day of the month');
172 }
173 }
174 if($values['repeats_by'] == 2){
175 if($values['entity_status_1'] != "" ) {
176 $dayOfTheWeekNo = array(first, second, third, fourth, last);
177 if(!in_array($values['entity_status_1'], $dayOfTheWeekNo)){
178 $errors['entity_status_1'] = ts('Invalid option');
179 }
180 }else{
181 $errors['entity_status_1'] = ts('Invalid option');
182 }
183 if($values['entity_status_2'] != "" ) {
184 if(!in_array($values['entity_status_2'], $dayOfTheWeek)){
185 $errors['entity_status_2'] = ts('Invalid day name');
186 }
187 }else{
188 $errors['entity_status_2'] = ts('Invalid day name');
189 }
190 }
191 }
192 return $errors;
193 }
194
195 /**
196 * Function to process the form
197 *
198 * @access public
199 *
200 * @return None
201 */
202 static function postProcess($params=array(), $type) {
203 if(!empty($type)){
204 $params['used_for'] = $type;
205 }
206
207 if(CRM_Utils_Array::value('id', $params)){
208 CRM_Core_BAO_ActionSchedule::del($params['id']);
209 unset($params['id']);
210 }
211 //Save post params to the schedule reminder table
212 $dbParams = CRM_Core_BAO_RecurringEntity::mapFormValuesToDB($params);
213 $actionScheduleObj = CRM_Core_BAO_ActionSchedule::add($dbParams);
214
215 //exclude dates
216 $excludeDateList = array();
217 if(CRM_Utils_Array::value('copyExcludeDates', $params) && CRM_Utils_Array::value('parent_event_id', $params)){
218 //Since we get comma separated values lets get them in array
219 $exclude_date_list = array();
220 $exclude_date_list = explode(",", $params['copyExcludeDates']);
221
222 //Check if there exists any values for this option group
223 $optionGroupIdExists = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
224 'event_repeat_exclude_dates_'.$params['parent_event_id'],
225 'id',
226 'name'
227 );
228 if($optionGroupIdExists){
229 CRM_Core_BAO_OptionGroup::del($optionGroupIdExists);
230 }
231 $optionGroupParams =
232 array(
233 'name' => 'event_repeat_exclude_dates_'.$params['parent_event_id'],
234 'title' => 'Event Recursion',
235 'is_reserved' => 0,
236 'is_active' => 1
237 );
238 $opGroup = CRM_Core_BAO_OptionGroup::add($optionGroupParams);
239 if($opGroup->id){
240 $oldWeight= 0;
241 $fieldValues = array('option_group_id' => $opGroup->id);
242 foreach($exclude_date_list as $val){
243 $optionGroupValue =
244 array(
245 'option_group_id' => $opGroup->id,
246 'label' => CRM_Utils_Date::processDate($val),
247 'value' => CRM_Utils_Date::processDate($val),
248 'name' => $opGroup->name,
249 'description' => 'Used for event recursion',
250 'weight' => CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues),
251 'is_active' => 1
252 );
253 $excludeDateList[] = $optionGroupValue['value'];
254 CRM_Core_BAO_OptionValue::add($optionGroupValue);
255 }
256 }
257 }
258
259 //Delete relations if any from recurring entity tables before inserting new relations for this entity id
260 if($params['parent_event_id']){
261 $getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($params['parent_event_id'], 'civicrm_event', FALSE);
262 $implodeRelatedEntities = implode(',', array_map(function($entity){
263 return $entity['id'];
264 }, $getRelatedEntities));
265 //Check if participants exists for events
266 if($implodeRelatedEntities){
267 $query = "SELECT event_id, COUNT(*) as count
268 FROM civicrm_participant
269 WHERE event_id IN ({$implodeRelatedEntities})
270 GROUP BY event_id";
271 $dao = CRM_Core_DAO::executeQuery($query);
272 $participantDetails = array();
273 while($dao->fetch()) {
274 $participantDetails[$dao->event_id] = $dao->count;
275 }
276 }
277 foreach ($getRelatedEntities as $key => $value) {
278 if(!CRM_Utils_Array::value($value['id'], $participantDetails)){
279 CRM_Event_BAO_Event::del($value['id']);
280 }
281 }
282 CRM_Core_BAO_RecurringEntity::delEntityRelations($params['parent_event_id'], 'civicrm_event');
283 }
284
285 $recursion = new CRM_Core_BAO_RecurringEntity();
286 $recursion->dateColumns = array('start_date');
287 $recursion->scheduleId = $actionScheduleObj->id;
288
289 if (!empty($excludeDateList)) {
290 $recursion->excludeDates = $excludeDateList;
291 $recursion->excludeDateRangeColumns = array('start_date', 'end_date');
292 }
293
294 if ($params['parent_event_end_date']) {
295 $interval = $recursion->getInterval($params['parent_event_start_date'], $params['parent_event_end_date']);
296 $recursion->intervalDateColumns = array('end_date' => $interval);
297 }
298
299 $recursion->entity_id = $params['current_event_id'];
300 $recursion->entity_table = 'civicrm_event';
301 $recursion->linkedEntities = array(
302 array(
303 'table' => 'civicrm_price_set_entity',
304 'findCriteria' => array(
305 'entity_id' => $recursion->entity_id,
306 'entity_table' => 'civicrm_event'
307 ),
308 'linkedColumns' => array('entity_id'),
309 'isRecurringEntityRecord' => FALSE,
310 ),
311 array(
312 'table' => 'civicrm_uf_join',
313 'findCriteria' => array(
314 'entity_id' => $recursion->entity_id,
315 'entity_table' => 'civicrm_event'
316 ),
317 'linkedColumns' => array('entity_id'),
318 'isRecurringEntityRecord' => FALSE,
319 ),
320 array(
321 'table' => 'civicrm_tell_friend',
322 'findCriteria' => array(
323 'entity_id' => $recursion->entity_id,
324 'entity_table' => 'civicrm_event'
325 ),
326 'linkedColumns' => array('entity_id'),
327 'isRecurringEntityRecord' => TRUE,
328 ),
329 array(
330 'table' => 'civicrm_pcp_block',
331 'findCriteria' => array(
332 'entity_id' => $recursion->entity_id,
333 'entity_table' => 'civicrm_event'
334 ),
335 'linkedColumns' => array('entity_id'),
336 'isRecurringEntityRecord' => TRUE,
337 ),
338 );
339
340 $recurResult = $recursion->generate();
341
342 $status = ts('Repeat Configuration has been saved');
343 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
344 }
345 //end of function
346
347 /**
348 * Return a descriptive name for the page, used in wizard header
349 *
350 * @return string
351 * @access public
352 */
353 public function getTitle() {
354 return ts('Repeat Event');
355 }
356
357 }