Replaced function call getallConnected events function with getEntitiesForParent...
[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:49px;'));
70 foreach($dayOfTheWeek as $key => $val){
71 $startActionCondition[] = $form->createElement('checkbox', $key, NULL, substr($val."&nbsp;", 0, 3));
72 }
73 $form->addGroup($startActionCondition, 'start_action_condition', ts('Repeats on'));
74 $roptionTypes = array('1' => ts('day of the month'),
75 '2' => ts('day of the week'),
76 );
77 $form->addRadio('repeats_by', ts("Repeats By:"), $roptionTypes, array(), NULL);
78 $getMonths = CRM_Core_SelectValues::getNumericOptions(1, 31);
79 $form->add('select', 'limit_to', '', $getMonths, FALSE, array('style' => 'width:49px;'));
80 $dayOfTheWeekNo = array('first' => 'First',
81 'second'=> 'Second',
82 'third' => 'Third',
83 'fourth'=> 'Fourth',
84 'last' => 'Last'
85 );
86 $form->add('select', 'start_action_date_1', ts(''), $dayOfTheWeekNo);
87 $form->add('select', 'start_action_date_2', ts(''), $dayOfTheWeek);
88 $eoptionTypes = array('1' => ts('After'),
89 '2' => ts('On'),
90 );
91 $form->addRadio('ends', ts("Ends:"), $eoptionTypes, array(), NULL, TRUE);
92 $form->add('text', 'start_action_offset', ts(''), array('maxlength' => 2));
93 $form->addFormRule(array('CRM_Core_Form_RecurringEntity', 'formRule'));
94 $form->addDate('repeat_absolute_date', ts('On'), FALSE, array('formatType' => 'mailing'));
95 $form->addDate('exclude_date', ts('Exclude Date(s)'), FALSE);
96 $select = $form->add('select', 'exclude_date_list', ts(''), $form->_excludeDateInfo, FALSE, array('style' => 'width:200px;', 'size' => 4));
97 $select->setMultiple(TRUE);
98 $form->addElement('button','add_to_exclude_list','>>','onClick="addToExcludeList(document.getElementById(\'exclude_date\').value);"');
99 $form->addElement('button','remove_from_exclude_list', '<<', 'onClick="removeFromExcludeList(\'exclude_date_list\')"');
100 $form->addElement('hidden', 'isChangeInRepeatConfiguration', '', array('id' => 'isChangeInRepeatConfiguration'));
101 $form->addElement('hidden', 'copyExcludeDates', '', array('id' => 'copyExcludeDates'));
102 $form->addButtons(array(
103 array(
104 'type' => 'submit',
105 'name' => ts('Save'),
106 'isDefault' => TRUE,
107 ),
108 array(
109 'type' => 'cancel',
110 'name' => ts('Cancel')
111 ),
112 )
113 );
114 }
115
116 /**
117 * global validation rules for the form
118 *
119 * @param array $fields posted values of the form
120 *
121 * @return array list of errors to be posted back to the form
122 * @static
123 * @access public
124 */
125 static function formRule($values) {
126 $errors = array();
127 $dayOfTheWeek = array(monday,tuesday,wednesday,thursday,friday,saturday,sunday);
128 // CRM_Core_Error::debug('$values', $values);
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['start_action_date_1'] != "" ) {
176 $dayOfTheWeekNo = array(first, second, third, fourth, last);
177 if(!in_array($values['start_action_date_1'], $dayOfTheWeekNo)){
178 $errors['start_action_date_1'] = ts('Invalid option');
179 }
180 }else{
181 $errors['start_action_date_1'] = ts('Invalid option');
182 }
183 if($values['start_action_date_2'] != "" ) {
184 if(!in_array($values['start_action_date_2'], $dayOfTheWeek)){
185 $errors['start_action_date_2'] = ts('Invalid day name');
186 }
187 }else{
188 $errors['start_action_date_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 //Build Recursion Object
216 if($actionScheduleObj->id){
217 $recursionObject = CRM_Core_BAO_RecurringEntity::getRecursionFromReminder($actionScheduleObj->id);
218 }
219
220
221 //TO DO - Exclude date functionality
222 if(CRM_Utils_Array::value('copyExcludeDates', $params) && CRM_Utils_Array::value('parent_event_id', $params)){
223 //Since we get comma separated values lets get them in array
224 $exclude_date_list = array();
225 $exclude_date_list = explode(",", $params['copyExcludeDates']);
226
227 //Check if there exists any values for this option group
228 $optionGroupIdExists = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
229 'event_repeat_exclude_dates_'.$params['parent_event_id'],
230 'id',
231 'name'
232 );
233 if($optionGroupIdExists){
234 CRM_Core_BAO_OptionGroup::del($optionGroupIdExists);
235 }
236 $optionGroupParams =
237 array(
238 'name' => 'event_repeat_exclude_dates_'.$params['parent_event_id'],
239 'title' => 'Event Recursion',
240 'is_reserved' => 0,
241 'is_active' => 1
242 );
243 $opGroup = CRM_Core_BAO_OptionGroup::add($optionGroupParams);
244 if($opGroup->id){
245 $oldWeight= 0;
246 $fieldValues = array('option_group_id' => $opGroup->id);
247 foreach($exclude_date_list as $val){
248 $optionGroupValue =
249 array(
250 'option_group_id' => $opGroup->id,
251 'label' => CRM_Utils_Date::processDate($val),
252 'value' => CRM_Utils_Date::processDate($val),
253 'name' => $opGroup->name,
254 'description' => 'Used for event recursion',
255 'weight' => CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues),
256 'is_active' => 1
257 );
258 CRM_Core_BAO_OptionValue::add($optionGroupValue);
259 }
260 }
261 }
262
263 //Give call to create recursions
264 $recurResult = self::generateRecursions($recursionObject, $params);
265 if(!empty($recurResult)){
266 self::addEntityThroughRecursion($recurResult, $params['parent_event_id']);
267 }
268 $status = ts('Repeat Configuration has been saved');
269 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
270 }
271 //end of function
272
273 /**
274 * Return a descriptive name for the page, used in wizard header
275 *
276 * @return string
277 * @access public
278 */
279 public function getTitle() {
280 return ts('Repeat Event');
281 }
282
283 static public function generateRecursions($recursionObj, $params=array()){
284 $newParams = $recursionResult = array();
285 if($recursionObj && !empty($params)){
286 //Proceed only if these keys are found in array
287 if(CRM_Utils_Array::value('parent_event_start_date', $params) && CRM_Utils_Array::value('parent_event_id', $params)){
288 $count = 1;
289 while($result = $recursionObj->next()){
290 //$result->format('YmdHis'). '<br />';
291 $newParams['start_date'] = CRM_Utils_Date::processDate($result->format('Y-m-d H:i:s'));
292 $parentStartDate = new DateTime($params['parent_event_start_date']);
293 //If open ended event
294 if(CRM_Utils_Array::value('parent_event_end_date', $params)){
295 $parentEndDate = new DateTime($params['parent_event_end_date']);
296 $interval = $parentStartDate->diff($parentEndDate);
297 $end_date = new DateTime($newParams['start_date']);
298 $end_date->add($interval);
299 $newParams['end_date'] = CRM_Utils_Date::processDate($end_date->format('Y-m-d H:i:s'));
300 $recursionResult[$count]['end_date'] = $newParams['end_date'];
301 }
302 $recursionResult[$count]['start_date'] = $newParams['start_date'];
303 $count++;
304 }
305 }
306 }
307 return $recursionResult;
308 }
309
310 static public function addEntityThroughRecursion($recursionResult = array(), $currEntityID){
311 if(!empty($recursionResult) && $currEntityID){
312 $parent_event_id = CRM_Core_BAO_RecurringEntity::getParentFor($currEntityID, 'civicrm_event');
313 if(!$parent_event_id){
314 $parent_event_id = $currEntityID;
315 }
316
317 // add first entry just for parent
318 CRM_Core_BAO_RecurringEntity::quickAdd($parent_event_id, $parent_event_id, 'civicrm_event');
319
320 foreach ($recursionResult as $key => $value) {
321 $newEventObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity('civicrm_event',
322 array('id' => $parent_event_id),
323 $value);
324
325 CRM_Core_BAO_RecurringEntity::copyCreateEntity('civicrm_price_set_entity',
326 array(
327 'entity_id' => $parent_event_id,
328 'entity_table' => 'civicrm_event'
329 ),
330 array(
331 'entity_id' => $newEventObj->id
332 ),
333 FALSE
334 );
335
336 CRM_Core_BAO_RecurringEntity::copyCreateEntity('civicrm_uf_join',
337 array(
338 'entity_id' => $parent_event_id,
339 'entity_table' => 'civicrm_event'
340 ),
341 array(
342 'entity_id' => $newEventObj->id
343 ),
344 FALSE
345 );
346
347 CRM_Core_BAO_RecurringEntity::copyCreateEntity('civicrm_tell_friend',
348 array(
349 'entity_id' => $parent_event_id,
350 'entity_table' => 'civicrm_event'
351 ),
352 array(
353 'entity_id' => $newEventObj->id
354 )
355 );
356
357 CRM_Core_BAO_RecurringEntity::copyCreateEntity('civicrm_pcp_block',
358 array(
359 'entity_id' => $parent_event_id,
360 'entity_table' => 'civicrm_event'
361 ),
362 array(
363 'entity_id' => $newEventObj->id
364 )
365 );
366 }
367 }
368 }
369
370 static function getListOfCurrentAndFutureEvents($ids=''){
371 if(isset($ids) and !empty($ids)){
372 $curDate = date('YmdHis');
373 $query = "SELECT group_concat(id) as ids FROM civicrm_event
374 WHERE id IN ({$ids})
375 AND ( end_date >= {$curDate} OR
376 (
377 ( end_date IS NULL OR end_date = '' ) AND start_date >= {$curDate}
378 ))";
379 $dao = CRM_Core_DAO::executeQuery($query);
380 $dao->fetch();
381 }
382 return $dao;
383 }
384
385 static function deleleRelationsForEventsInPast($ids=''){
386 if(isset($ids) and !empty($ids)){
387 $query = "DELETE FROM civicrm_recurring_entity
388 WHERE entity_id IN ({$ids})";
389 $dao = CRM_Core_DAO::executeQuery($query);
390 }
391 return;
392 }
393
394 }