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 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());
         }
     }
 }