static function addInvitations($result_events, $user_id = -1)
 {
     if ($user_id == -1) {
         $user_id = logged_user()->getId();
     }
     if (isset($result_events) && is_array($result_events) && count($result_events)) {
         foreach ($result_events as $event) {
             $inv = EventInvitations::findById(array('event_id' => $event->getId(), 'user_id' => $user_id));
             if ($inv != null) {
                 $event->addInvitation($inv);
             }
         }
     }
 }
Esempio n. 2
0
        $duration = lang('CAL_NOT_SPECIFIED');
    } elseif ($typeofevent == "4") {
        $duration = lang('CAL_NOT_SPECIFIED');
    }
    $permission = ProjectEvents::findById($id)->canEdit(logged_user());
    ?>
<div style="padding:7px;">
<div class="event" style="height:100%;">

<?php 
    $title = lang($event->getObjectTypeName()) . ": " . format_descriptive_date($event->getStart()) . ' - ' . clean($event->getObjectName());
    $description = $event->getTypeId() == 2 ? lang('CAL_FULL_DAY') : lang('CAL_TIME') . ": {$time}";
    tpl_assign('description', $description);
    $att_form = '';
    if (!$event->isNew() && !$event->isTrashed()) {
        $event_inv = EventInvitations::findById(array('event_id' => $event->getId(), 'contact_id' => logged_user()->getId()));
        if ($event_inv != null) {
            $event->addInvitation($event_inv);
            $event_inv_state = $event_inv->getInvitationState();
            if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_update_other_users_invitations')) {
                $options = array(option_tag(lang('yes'), 1, $event_inv_state == 1 ? array('selected' => 'selected') : null), option_tag(lang('no'), 2, $event_inv_state == 2 ? array('selected' => 'selected') : null), option_tag(lang('maybe'), 3, $event_inv_state == 3 ? array('selected' => 'selected') : null));
                if ($event_inv_state == 0) {
                    $options[] = option_tag(lang('decide later'), 0, $event_inv_state == 0 ? array('selected' => 'selected') : null);
                }
                $att_form = '<form style="height:100%;background-color:white" class="internalForm" action="' . get_url('event', 'change_invitation_state') . '" method="post">';
                $att_form .= '<table><tr><td style="padding-right:6px;"><b>' . lang('attendance') . '<b></td><td>';
                $att_form .= select_box('event_attendance', $options, array('id' => 'viewEventFormComboAttendance')) . '</td><td>';
                $att_form .= input_field('event_id', $event->getId(), array('type' => 'hidden'));
                $att_form .= input_field('user_id', logged_user()->getId(), array('type' => 'hidden'));
                $att_form .= submit_button(lang('Save'), null, array('style' => 'margin-top:0px;margin-left:10px')) . '</td></tr></table></form>';
            }
 function notifyAction($object, $action, $log_data)
 {
     if (!$object instanceof ContentDataObject) {
         return;
     }
     if ($object instanceof Comment) {
         $subscribers = $object->getRelObject()->getSubscribers();
     } else {
         $subscribers = $object->getSubscribers();
     }
     if ($object instanceof ProjectEvent && $action == ApplicationLogs::ACTION_ADD) {
         //remove invited people from subscribers to avoid repeated notifications
         $tmp_subs = array();
         foreach ($subscribers as $person) {
             $inv = EventInvitations::findById(array('event_id' => $object->getId(), 'contact_id' => $person->getId()));
             if (!$inv instanceof EventInvitation) {
                 $tmp_subs[] = $person;
             }
         }
         $subscribers = $tmp_subs;
     }
     if ($object instanceof ProjectTask && $object->getAssignedToContactId() > 0) {
         //remove assigned_to from subscribers to avoid repeated notifications
         $tmp_subs = array();
         foreach ($subscribers as $person) {
             if ($person->getId() != $object->getAssignedToContactId()) {
                 $tmp_subs[] = $person;
             }
         }
         $subscribers = $tmp_subs;
     }
     if ($object instanceof ProjectTask && $action == ApplicationLogs::ACTION_CLOSE) {
         // notify users assigned to tasks depending on this tasks that this task has been completed
         self::notifyDependantTaskAssignedUsersOfTaskCompletion($object);
     }
     if (!is_array($subscribers) || count($subscribers) == 0) {
         return;
     }
     if ($action == ApplicationLogs::ACTION_ADD) {
         self::objectNotification($object, $subscribers, logged_user(), 'new');
     } else {
         if ($action == ApplicationLogs::ACTION_EDIT) {
             $contactIds = $log_data;
             if ($contactIds) {
                 $contacts = Contacts::instance()->findAll(array("conditions" => " o.id IN (" . $contactIds . ")"));
                 foreach ($contacts as $contact) {
                     $subscribers[] = $contact;
                 }
             }
             self::objectNotification($object, $subscribers, logged_user(), 'modified');
         } else {
             if ($action == ApplicationLogs::ACTION_TRASH) {
                 self::objectNotification($object, $subscribers, logged_user(), 'deleted');
             } else {
                 if ($action == ApplicationLogs::ACTION_CLOSE) {
                     $contactIds = $log_data;
                     if ($contactIds) {
                         $contacts = Contacts::instance()->findAll(array("conditions" => " o.id IN (" . $contactIds . ")"));
                         foreach ($contacts as $contact) {
                             $subscribers[] = $contact;
                         }
                     }
                     self::objectNotification($object, $subscribers, logged_user(), 'closed');
                 } else {
                     if ($action == ApplicationLogs::ACTION_OPEN) {
                         $contactIds = $log_data;
                         if ($contactIds) {
                             $contacts = Contacts::instance()->findAll(array("conditions" => " o.id IN (" . $contactIds . ")"));
                             foreach ($contacts as $contact) {
                                 $subscribers[] = $contact;
                             }
                         }
                         self::objectNotification($object, $subscribers, logged_user(), 'open');
                     } else {
                         if ($action == ApplicationLogs::ACTION_SUBSCRIBE) {
                             $contactIds = $log_data;
                             if ($contactIds) {
                                 $contacts = Contacts::instance()->findAll(array("conditions" => " o.id IN (" . $contactIds . ")"));
                             } else {
                                 $contacts = array();
                             }
                             self::objectNotification($object, $contacts, logged_user(), 'subscribed');
                         } else {
                             if ($action == ApplicationLogs::ACTION_COMMENT) {
                                 self::newObjectComment($object, $subscribers);
                             } else {
                                 if ($action == ApplicationLogs::ACTION_UPLOAD) {
                                     self::objectNotification($object, $subscribers, logged_user(), ApplicationLogs::ACTION_UPLOAD);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
        function import_google_calendar() {
                ajx_current("empty");
                $users = ExternalCalendarUsers::findByContactId();  
                if($users){
                    $calendars = ExternalCalendars::findByExtCalUserId($users->getId());

                    require_once 'Zend/Loader.php';

                    Zend_Loader::loadClass('Zend_Gdata');
                    Zend_Loader::loadClass('Zend_Gdata_AuthSub');
                    Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
                    Zend_Loader::loadClass('Zend_Gdata_Calendar');

                    $user = $users->getAuthUser();
                    $pass = $users->getAuthPass();
                    $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;

                    try
                    {
                            $client = Zend_Gdata_ClientLogin::getHttpClient($user,$pass,$service);                                                       
                            $gdataCal = new Zend_Gdata_Calendar($client);

                            //update or insert events for calendars                        
                            foreach ($calendars as $calendar){

                                //check the deleted calendars
                                $delete_calendar = false;
                                $calFeed = $gdataCal->getCalendarListFeed();        
                                foreach ($calFeed as $calF){
                                    $cal_src = explode("/",$calF->content->src);
                                    array_pop($cal_src);
                                    $calendar_visibility = end($cal_src);
                                    array_pop($cal_src);
                                    $calendar_user = end($cal_src); 

                                    if($calendar_user == $calendar->getCalendarUser()){
                                        $delete_calendar = true;
                                    }
                                }

                                if($delete_calendar){
                                    $calendar_user = $calendar->getCalendarUser();
                                    $calendar_visibility = $calendar->getCalendarVisibility();
                                    $start_sel = date('Y-m-d', strtotime('-1 week'));
                                    $end_sel = date('Y-m-d', strtotime('+2 year'));

                                    $query = $gdataCal->newEventQuery();
                                    $query->setUser($calendar_user);
                                    $query->setVisibility($calendar_visibility);
                                    $query->setSingleEvents(true);
                                    $query->setProjection('full');
                                    $query->setOrderby('starttime');
                                    $query->setSortOrder('ascending'); 
                                    $query->setStartMin($start_sel);
                                    $query->setStartMax($end_sel);
                                    $query->setMaxResults(50);
                                    // execute and get results
                                    $event_list = $gdataCal->getCalendarEventFeed($query);

                                    $array_events_google = array();
                                    foreach ($event_list as $event){                                        
                                        $event_id = explode("/",$event->id->text);
                                        $special_id = end($event_id); 
                                        $event_name = lang("untitle event");
                                        if($event->title->text != ""){
                                            $event_name = $event->title->text;
                                        }
                                        $array_events_google[] = $special_id;
                                        $new_event = ProjectEvents::findBySpecialId($special_id);
                                        if($new_event){
                                            if(strtotime(ProjectEvents::date_google_to_sql($event->updated)) > $new_event->getUpdateSync()->getTimestamp()){
                                                $start = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                                $fin = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                                if(($fin - $start) == 86400){
                                                    $new_event->setStart(date("Y-m-d H:i:s",$start));
                                                    $new_event->setDuration(date("Y-m-d H:i:s",$start));
                                                    $new_event->setTypeId(2);
                                                }elseif(($fin - $start) > 86400){                                                
                                                    $t_s = explode(' ', date("Y-m-d H:i:s",$start));
                                                    $t_f = explode(' ', date("Y-m-d H:i:s",$fin));

                                                    $date_s = new DateTimeValue(strtotime($t_s[0]."00:00:00") - logged_user()->getTimezone() * 3600);
                                                    $date_f = new DateTimeValue(strtotime($t_f[0]."23:59:59 -1 day") - logged_user()->getTimezone() * 3600);

                                                    $new_event->setStart(date("Y-m-d H:i:s",$date_s->getTimestamp()));
                                                    $new_event->setDuration(date("Y-m-d H:i:s",$date_f->getTimestamp()));
                                                    $new_event->setTypeId(2);
                                                }else{
                                                    $new_event->setStart(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                                    $new_event->setDuration(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                                }

                                                $new_event->setObjectName($event_name);
                                                $new_event->setDescription($event->content->text);
                                                $new_event->setUpdateSync(ProjectEvents::date_google_to_sql($event->updated));
                                                $new_event->setExtCalId($calendar->getId());
                                                $new_event->save(); 
                                            }
                                        }else{
                                            $new_event = new ProjectEvent();
                                            
                                            $start = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                            $fin = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                            if(($fin - $start) == 86400){
                                                $new_event->setStart(date("Y-m-d H:i:s",$start));
                                                $new_event->setDuration(date("Y-m-d H:i:s",$start));
                                                $new_event->setTypeId(2);
                                            }elseif(($fin - $start) > 86400){
                                                $t_s = explode(' ', date("Y-m-d H:i:s",$start));
                                                $t_f = explode(' ', date("Y-m-d H:i:s",$fin));
                                                
                                                $date_s = new DateTimeValue(strtotime($t_s[0]."00:00:00") - logged_user()->getTimezone() * 3600);
                                                $date_f = new DateTimeValue(strtotime($t_f[0]."23:59:59 -1 day") - logged_user()->getTimezone() * 3600);
                                                
                                                $new_event->setStart(date("Y-m-d H:i:s",$date_s->getTimestamp()));
                                                $new_event->setDuration(date("Y-m-d H:i:s",$date_f->getTimestamp()));
                                                $new_event->setTypeId(2);
                                            }else{
                                                $new_event->setStart(ProjectEvents::date_google_to_sql($event->when[0]->startTime));
                                                $new_event->setDuration(ProjectEvents::date_google_to_sql($event->when[0]->endTime));
                                                $new_event->setTypeId(1);
                                            }
                                            
                                            $new_event->setObjectName($event_name);
                                            $new_event->setDescription($event->content->text);
                                            $new_event->setSpecialID($special_id);
                                            $new_event->setUpdateSync(ProjectEvents::date_google_to_sql($event->updated));
                                            $new_event->setExtCalId($calendar->getId());                                            
                                            $new_event->save(); 
                                            
                                            $conditions = array('event_id' => $new_event->getId(), 'contact_id' => logged_user()->getId());
                                            //insert only if not exists 
                                            if (EventInvitations::findById($conditions) == null) { 
                                                $invitation = new EventInvitation();
                                                $invitation->setEventId($new_event->getId());
                                                $invitation->setContactId(logged_user()->getId());
                                                $invitation->setInvitationState(1);
                                                $invitation->save();
                                            }
                                            
                                            //insert only if not exists 
                                            if (ObjectSubscriptions::findBySubscriptions($new_event->getId()) == null) { 
                                                $subscription = new ObjectSubscription();
                                                $subscription->setObjectId($new_event->getId());
                                                $subscription->setContactId(logged_user()->getId());
                                                $subscription->save();
                                            }

                                            if($users->getRelatedTo()){
                                                $member = array();
                                                $member_ids = explode(",",$users->getRelatedTo());
                                                foreach ($member_ids as $member_id){
                                                    $member[] = $member_id;
                                                }
                                                $object_controller = new ObjectController();
                                                $object_controller->add_to_members($new_event, $member); 
                                            }else{
                                                $member_ids = array();
                                                $context = active_context();
                                                foreach ($context as $selection) {
                                                    if ($selection instanceof Member) $member_ids[] = $selection->getId();
                                                }		        
                                                $object_controller = new ObjectController();
                                                $object_controller->add_to_members($new_event, $member_ids); 
                                            }                                            
                                        }           
                                    }// foreach event list 

                                    //check the deleted events
                                    $events_delete = ProjectEvents::findByExtCalId($calendar->getId());
                                    if($events_delete){
                                        foreach($events_delete as $event_delete){  
                                            if(!in_array($event_delete->getSpecialID(), $array_events_google)){
                                                $event_delete->trash();

                                                $event_delete->setSpecialID("");
                                                $event_delete->setExtCalId(0);
                                                $event_delete->save();    
                                            }                                        
                                        }  
                                    }
                                }else{                
                                    $events = ProjectEvents::findByExtCalId($calendar->getId());
                                    if($calendar->delete()){
                                        if($events){
                                            foreach($events as $event){                            
                                                $event->trash();

                                                $event->setSpecialID("");
                                                $event->setExtCalId(0);
                                                $event->save();
                                            }  
                                        }
                                    }
                                }
                            }//foreach calendars
                    }
                    catch(Exception $e)
                    {
                    		Logger::log($e->getMessage());
                            flash_error(lang('could not connect to calendar'));
                            ajx_current("empty");
                    }
                }
	}
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('event');
     $event = ProjectEvents::findById(get_id());
     $user_filter = isset($_GET['user_id']) ? $_GET['user_id'] : logged_user()->getId();
     $inv = EventInvitations::findById(array('event_id' => $event->getId(), 'user_id' => $user_filter));
     if ($inv != null) {
         $event->addInvitation($inv);
     }
     if (!$event->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     tpl_assign('active_projects', logged_user()->getActiveProjects());
     $event_data = array_var($_POST, 'event');
     if (!is_array($event_data)) {
         $tag_names = $event->getTagNames();
         $setlastweek = false;
         $rsel1 = false;
         $rsel2 = false;
         $rsel3 = false;
         $forever = $event->getRepeatForever();
         $occ = 1;
         if ($event->getRepeatD() > 0) {
             $occ = 2;
             $rjump = $event->getRepeatD();
         }
         if ($event->getRepeatD() > 0 and $event->getRepeatD() % 7 == 0) {
             $occ = 3;
             $rjump = $event->getRepeatD() / 7;
         }
         if ($event->getRepeatM() > 0) {
             $occ = 4;
             $rjump = $event->getRepeatM();
         }
         if ($event->getRepeatY() > 0) {
             $occ = 5;
             $rjump = $event->getRepeatY();
         }
         if ($event->getRepeatH() > 0) {
             $occ = 6;
         }
         if ($event->getRepeatH() == 2) {
             $setlastweek = true;
         }
         if ($event->getRepeatEnd()) {
             $rend = $event->getRepeatEnd();
         }
         if ($event->getRepeatNum() > 0) {
             $rnum = $event->getRepeatNum();
         }
         if (!isset($rjump) || !is_numeric($rjump)) {
             $rjump = 1;
         }
         // decide which repeat type it is
         if ($forever) {
             $rsel1 = true;
         } else {
             if (isset($rnum) and $rnum > 0) {
                 $rsel2 = true;
             } else {
                 if (isset($rend) and $rend instanceof DateTimeValue) {
                     $rsel3 = true;
                 }
             }
         }
         //repeat until
         //if(isset($rend) AND $rend=="9999-00-00") $rend = "";
         // organize the time and date data for the html select drop downs.
         $thetime = $event->getStart()->getTimestamp() + logged_user()->getTimezone() * 3600;
         $durtime = $event->getDuration()->getTimestamp() + logged_user()->getTimezone() * 3600 - $thetime;
         $hour = date('G', $thetime);
         // format time to 24-hour or 12-hour clock.
         if (!user_config_option('time_format_use_24')) {
             if ($hour >= 12) {
                 $pm = 1;
                 $hour = $hour - 12;
             } else {
                 $pm = 0;
             }
         }
         $event_data = array('subject' => $event->getSubject(), 'description' => $event->getDescription(), 'name' => $event->getCreatedById(), 'username' => $event->getCreatedById(), 'typeofevent' => $event->getTypeId(), 'forever' => $event->getRepeatForever(), 'usetimeandduration' => $event->getTypeId() == 3 ? 0 : 1, 'occ' => $occ, 'rjump' => $rjump, 'setlastweek' => $setlastweek, 'rend' => isset($rend) ? $rend : NULL, 'rnum' => isset($rnum) ? $rnum : NULL, 'rsel1' => $rsel1, 'rsel2' => $rsel2, 'rsel3' => $rsel3, 'thetime' => $event->getStart()->getTimestamp(), 'hour' => $hour, 'minute' => date('i', $thetime), 'month' => date('n', $thetime), 'year' => date('Y', $thetime), 'day' => date('j', $thetime), 'durtime' => $event->getDuration()->getTimestamp() - $thetime, 'durationmin' => $durtime / 60 % 60, 'durationhour' => $durtime / 3600 % 24, 'durday' => floor($durtime / 86400), 'pm' => isset($pm) ? $pm : 0, 'tags' => is_array($tag_names) ? implode(', ', $tag_names) : '', 'repeat_dow' => $event->getRepeatDow(), 'repeat_wnum' => $event->getRepeatWnum(), 'repeat_mjump' => $event->getRepeatMjump());
         // array
     }
     // if
     tpl_assign('event_data', $event_data);
     tpl_assign('event', $event);
     if (is_array(array_var($_POST, 'event'))) {
         //	MANAGE CONCURRENCE WHILE EDITING
         $upd = array_var($_POST, 'updatedon');
         if ($upd && $event->getUpdatedOn()->getTimestamp() > $upd && !array_var($_POST, 'merge-changes') == 'true') {
             ajx_current('empty');
             evt_add("handle edit concurrence", array("updatedon" => $event->getUpdatedOn()->getTimestamp(), "genid" => array_var($_POST, 'genid')));
             return;
         }
         if (array_var($_POST, 'merge-changes') == 'true') {
             $this->setTemplate('view_event');
             $editedEvent = ProjectEvents::findById($event->getId());
             $this->viewevent();
             ajx_set_panel(lang('tab name', array('name' => $editedEvent->getTitle())));
             ajx_extra_data(array("title" => $editedEvent->getTitle(), 'icon' => 'ico-event'));
             ajx_set_no_toolbar(true);
             ajx_set_panel(lang('tab name', array('name' => $editedEvent->getTitle())));
             return;
         }
         try {
             $data = $this->getData($event_data);
             // run the query to set the event data
             $event->setFromAttributes($data);
             $this->registerInvitations($data, $event, false);
             if (isset($data['confirmAttendance'])) {
                 $this->change_invitation_state($data['confirmAttendance'], $event->getId(), $user_filter);
             }
             if (isset($data['send_notification']) && $data['send_notification']) {
                 $users_to_inv = array();
                 foreach ($data['users_to_invite'] as $us => $v) {
                     if ($us != logged_user()->getId()) {
                         $users_to_inv[] = Users::findById(array('id' => $us));
                     }
                 }
                 Notifier::notifEvent($event, $users_to_inv, 'modified', logged_user());
             }
             foreach ($data['users_to_invite'] as $user_id => $v) {
                 $user = Users::findById(array('id' => $user_id));
                 if ($user instanceof User) {
                     $phone_num = Users::getPhoneNumberCustomProperty($user_id);
                     $sms_obj = new SmsController();
                     $sms_obj->prepareEventInvitee($user->getDisplayName(), $event->getTitle(), get_class($event));
                     $sms_obj->sendSms($phone_num);
                 }
             }
             if (!logged_user()->isMemberOfOwnerCompany()) {
                 $event->setIsPrivate(false);
             }
             DB::beginWork();
             $event->save();
             $event->setTagsFromCSV(array_var($event_data, 'tags'));
             $object_controller = new ObjectController();
             $object_controller->add_to_workspaces($event);
             $object_controller->link_to_new_object($event);
             $object_controller->add_subscribers($event);
             $object_controller->add_custom_properties($event);
             $object_controller->add_reminders($event);
             $event->resetIsRead();
             ApplicationLogs::createLog($event, $event->getWorkspaces(), ApplicationLogs::ACTION_EDIT);
             DB::commit();
             flash_success(lang('success edit event', clean($event->getObjectName())));
             if (array_var($_POST, 'popup', false)) {
                 ajx_current("reload");
             } else {
                 ajx_current("back");
             }
             ajx_add("overview-panel", "reload");
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
             //tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
 function icalendar_import()
 {
     @set_time_limit(0);
     if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) {
         unset($_SESSION['history_back']);
     }
     if (isset($_SESSION['history_back'])) {
         if ($_SESSION['history_back'] > 0) {
             $_SESSION['history_back'] = $_SESSION['history_back'] - 1;
         }
         if ($_SESSION['history_back'] == 0) {
             unset($_SESSION['history_back']);
         }
         ajx_current("back");
     } else {
         $ok = false;
         $this->setTemplate('cal_import');
         $filedata = array_var($_FILES, 'cal_file');
         if (is_array($filedata)) {
             $filename = $filedata['tmp_name'] . 'vcal';
             copy($filedata['tmp_name'], $filename);
             $events_data = CalFormatUtilities::decode_ical_file($filename);
             if (count($events_data)) {
                 try {
                     DB::beginWork();
                     foreach ($events_data as $ev_data) {
                         $event = new ProjectEvent();
                         $event->setFromAttributes($ev_data);
                         $event->save();
                         ApplicationLogs::createLog($event, ApplicationLogs::ACTION_ADD);
                         $conditions = array('event_id' => $event->getId(), 'contact_id' => logged_user()->getId());
                         //insert only if not exists
                         if (EventInvitations::findById($conditions) == null) {
                             $invitation = new EventInvitation();
                             $invitation->setEventId($event->getId());
                             $invitation->setContactId(logged_user()->getId());
                             $invitation->setInvitationState(1);
                             $invitation->save();
                         }
                         //insert only if not exists
                         if (ObjectSubscriptions::findBySubscriptions($event->getId()) == null) {
                             $subscription = new ObjectSubscription();
                             $subscription->setObjectId($event->getId());
                             $subscription->setContactId(logged_user()->getId());
                             $subscription->save();
                         }
                         $member_ids = array();
                         $context = active_context();
                         foreach ($context as $selection) {
                             if ($selection instanceof Member) {
                                 $member_ids[] = $selection->getId();
                             }
                         }
                         $object_controller = new ObjectController();
                         $object_controller->add_to_members($event, $member_ids);
                     }
                     DB::commit();
                     $ok = true;
                     flash_success(lang('success import events', count($events_data)));
                     $_SESSION['history_back'] = 1;
                 } catch (Exception $e) {
                     DB::rollback();
                     flash_error($e->getMessage());
                 }
             } else {
                 flash_error(lang('no events to import'));
             }
             unset($filename);
             if (!$ok) {
                 ajx_current("empty");
             }
         } else {
             if (array_var($_POST, 'atimportform', 0)) {
                 ajx_current("empty");
             }
         }
     }
 }
 function import_google_calendar_for_user($user)
 {
     if ($user instanceof ExternalCalendarUser) {
         $calendars = ExternalCalendars::findByExtCalUserId($user->getId());
         $service = $this->connect_with_google_calendar($user);
         $contact = Contacts::findById($user->getContactId());
         try {
             //update or insert events for calendars
             foreach ($calendars as $calendar) {
                 if ($calendar->getSync() == 0) {
                     continue;
                 }
                 $optParams = array();
                 $syncToken = $calendar->getExternalCalendarPropertyValue("syncToken");
                 //if syncToken is not present we have to make a full sync
                 if ($syncToken) {
                     //incremental sync get events created or updated from las check
                     $optParams['syncToken'] = $syncToken;
                 } else {
                     //full sync get events starting from past 2 weeks
                     $previous_week = strtotime("-2 week");
                     $time_min = date(DATE_RFC3339, $previous_week);
                     $optParams['timeMin'] = $time_min;
                 }
                 //Try to get events for this calendar
                 try {
                     $events = $service->events->listEvents($calendar->getOriginalCalendarId(), $optParams);
                 } catch (Exception $e) {
                     Logger::log("Fail to get events from external calendar: " . $calendar->getId());
                     Logger::log($e->getMessage());
                     //remove the syncToken for this calendar so the next time we do a full sync
                     $syncTokenProp = $calendar->getExternalCalendarProperty("syncToken");
                     if ($syncTokenProp) {
                         $syncTokenProp->delete();
                     }
                     //go to the next calendar
                     continue;
                 }
                 //Working with events
                 while (true) {
                     foreach ($events->getItems() as $event) {
                         //check if is a cancelled event
                         if ($event->getStatus() == "cancelled") {
                             $cancelled_event = ProjectEvents::findBySpecialId($event->getId(), $calendar->getId());
                             //delete ProjectEvent
                             if ($cancelled_event instanceof ProjectEvent) {
                                 $cancelled_event->delete();
                             }
                             continue;
                         }
                         //check if is a recurrent event
                         if (is_array($event->getRecurrence())) {
                             continue;
                         }
                         //check if is a recurrent event instance
                         if (!is_null($event->getRecurringEventId()) && $event->getRecurringEventId() != '') {
                             continue;
                         }
                         //get all the data that we need from google event
                         $event_id = $event->getId();
                         $event_name = $event->getSummary();
                         $event_desc = $event->getDescription();
                         $event_start_date = ExternalCalendarController::date_google_to_sql($event->getStart());
                         $event_end_date = ExternalCalendarController::date_google_to_sql($event->getEnd());
                         $event_type = 1;
                         if ($event->getStart()->getDate()) {
                             $event_type = 2;
                             //set this times because we have a bug with all day events times
                             $event_start_date = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $event_start_date);
                             $event_start_date->advance(12 * 3600);
                             $event_start_date = $event_start_date->toMySQL();
                             $event_end_date = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $event_start_date);
                             $event_end_date->advance(1 * 3600);
                             $event_end_date = $event_end_date->toMySQL();
                         }
                         $event_updated_date = EMPTY_DATETIME;
                         if (!is_null($event->getUpdated()) && $event->getUpdated() != '') {
                             $event_updated_date_str = strtotime($event->getUpdated());
                             $event_updated_date = date(DATE_MYSQL, $event_updated_date_str);
                         }
                         //Save event
                         try {
                             DB::beginWork();
                             //if event exist update it
                             $new_event = ProjectEvents::findBySpecialId($event_id, $calendar->getId());
                             if (!$new_event instanceof ProjectEvent) {
                                 //Create ProjectEvent from google event
                                 $new_event = new ProjectEvent();
                             }
                             $new_event->setSpecialID($event_id);
                             $new_event->setStart($event_start_date);
                             $new_event->setDuration($event_end_date);
                             $new_event->setTypeId($event_type);
                             $new_event->setObjectName($event_name);
                             $new_event->setDescription($event_desc);
                             $new_event->setUpdateSync($event_updated_date);
                             $new_event->setExtCalId($calendar->getId());
                             $new_event->save();
                             //Invitation insert only if not exists
                             $conditions = array('event_id' => $new_event->getId(), 'contact_id' => $user->getContactId());
                             if (EventInvitations::findById($conditions) == null) {
                                 $invitation = new EventInvitation();
                                 $invitation->setEventId($new_event->getId());
                                 $invitation->setContactId($user->getContactId());
                                 $invitation->setInvitationState(1);
                                 $invitation->setUpdateSync();
                                 $invitation->setSpecialId($event_id);
                                 $invitation->save();
                             }
                             //Subscription insert only if not exists
                             if (ObjectSubscriptions::findBySubscriptions($new_event->getId(), $contact) == null) {
                                 $subscription = new ObjectSubscription();
                                 $subscription->setObjectId($new_event->getId());
                                 $subscription->setContactId($user->getContactId());
                                 $subscription->save();
                             }
                             $member = array();
                             if ($calendar->getRelatedTo()) {
                                 $member_ids = explode(",", $calendar->getRelatedTo());
                                 foreach ($member_ids as $member_id) {
                                     $member[] = $member_id;
                                 }
                             }
                             $object_controller = new ObjectController();
                             $object_controller->add_to_members($new_event, $member, $contact);
                             DB::commit();
                         } catch (Exception $e) {
                             DB::rollback();
                             Logger::log("Fail to save event for external calendar user: "******"syncToken", $nextSyncToken);
                         }
                         break;
                     }
                 }
             }
             //foreach calendars
         } catch (Exception $e) {
             Logger::log("Fail to get events for external calendar user: " . $user->getId());
             Logger::log($e->getMessage());
         }
     }
 }