/**
  * Add an Event to the specified calendar
  *
  * @param string   $calendarId        Calendar's ID in which you want to insert your event
  * @param datetime $eventStart        Event's start date
  * @param datetime $eventEnd          Event's end date
  * @param string   $eventSummary      Event's title
  * @param string   $eventDescription  Event's description where you should put all your informations
  * @param array    $eventAttendee     Event's attendees : to use the invitation system you should add the calendar owner to the attendees
  * @param array    $optionalParams    Optional params
  *
  * @return object Event
  */
 public function addEvent($calendarId, $eventStart, $eventEnd, $eventSummary, $eventDescription, $eventAttendee, $optionalParams = [])
 {
     // Your new GoogleEvent object
     $event = new \Google_Service_Calendar_Event();
     // Set the title
     $event->setSummary($eventSummary);
     // Set and format the start date
     $formattedStart = $eventStart->format(\DateTime::RFC3339);
     $formattedEnd = $eventEnd->format(\DateTime::RFC3339);
     $start = new \Google_Service_Calendar_EventDateTime();
     $start->setDateTime($formattedStart);
     $event->setStart($start);
     $end = new \Google_Service_Calendar_EventDateTime();
     $end->setDateTime($formattedEnd);
     $event->setEnd($end);
     // Default status for newly created event
     $event->setStatus('tentative');
     // Set event's description
     $event->setDescription($eventDescription);
     // Attendees - permit to manage the event's status
     $attendee = new \Google_Service_Calendar_EventAttendee();
     $attendee->setEmail($eventAttendee);
     $event->attendees = [$attendee];
     // Event insert
     return $this->getCalendarService()->events->insert($calendarId, $event, $optionalParams);
 }
Beispiel #2
0
 /**
  * @param AB_Appointment $appointment
  */
 private function handleEventData(AB_Appointment $appointment)
 {
     $start_datetime = new Google_Service_Calendar_EventDateTime();
     $start_datetime->setDateTime(DateTime::createFromFormat('Y-m-d H:i:s', $appointment->get('start_date'), new DateTimeZone(AB_Utils::getTimezoneString()))->format(DateTime::RFC3339));
     $end_datetime = new Google_Service_Calendar_EventDateTime();
     $end_datetime->setDateTime(DateTime::createFromFormat('Y-m-d H:i:s', $appointment->get('end_date'), new DateTimeZone(AB_Utils::getTimezoneString()))->format(DateTime::RFC3339));
     $service = new AB_Service();
     $service->load($appointment->get('service_id'));
     $description = __('Service', 'bookly') . ": " . $service->get('title') . PHP_EOL;
     $client_names = array();
     foreach ($appointment->getCustomerAppointments() as $ca) {
         $description .= sprintf("%s: %s\n%s: %s\n%s: %s\n", __('Name', 'bookly'), $ca->customer->get('name'), __('Email', 'bookly'), $ca->customer->get('email'), __('Phone', 'bookly'), $ca->customer->get('phone'));
         $description .= $ca->getFormattedCustomFields('text');
         $description .= PHP_EOL;
         $client_names[] = $ca->customer->get('name');
     }
     $staff = new AB_Staff();
     $staff->load($appointment->get('staff_id'));
     $title = strtr(get_option('ab_settings_google_event_title', '[[SERVICE_NAME]]'), array('[[SERVICE_NAME]]' => $service->get('title'), '[[CLIENT_NAMES]]' => implode(', ', $client_names), '[[STAFF_NAME]]' => $staff->get('full_name')));
     $this->event->setStart($start_datetime);
     $this->event->setEnd($end_datetime);
     $this->event->setSummary($title);
     $this->event->setDescription($description);
     $extended_property = new Google_Service_Calendar_EventExtendedProperties();
     $extended_property->setPrivate(array('customers' => json_encode(array_map(function ($ca) {
         return $ca->customer->get('id');
     }, $appointment->getCustomerAppointments())), 'service_id' => $service->get('id'), 'appointment_id' => $appointment->get('id')));
     $this->event->setExtendedProperties($extended_property);
 }
 public function testModelMutation()
 {
     $htmlLink = 'https://www.google.com/calendar/event?' . 'eid=NWdpMmFjNDkzbm5yZzh2N2poZXNhZmdldDggaWFuLmJhcmJlckBt';
     $data = json_decode('{
        "kind": "calendar#event",
        "etag": "\\"-kteSF26GsdKQ5bfmcd4H3_-u3g/MTE0NTUyNTAxOTk0MjAwMA\\"",
        "id": "1234566",
        "status": "confirmed",
        "htmlLink": "' . $htmlLink . '",
        "created": "2006-04-13T14:22:08.000Z",
        "updated": "2006-04-20T09:23:39.942Z",
        "summary": "Evening Jolt Q3 CTFL",
        "description": "6.30 - Adminning\\n9.30 - Game",
        "creator": {
          "email": "*****@*****.**",
          "displayName": "Ian Test",
          "self": true
        },
        "organizer": {
          "email": "*****@*****.**",
          "displayName": "Ian Test",
          "self": true
        },
        "start": {
          "date": "2006-04-23"
        },
        "end": {
          "date": "2006-04-24"
        },
        "iCalUID": "*****@*****.**",
        "sequence": 0,
        "reminders": {
          "useDefault": false
        }
      }', true);
     $event = new Google_Service_Calendar_Event($data);
     $date = new Google_Service_Calendar_EventDateTime();
     date_default_timezone_set('UTC');
     $dateString = Date("c");
     $summary = "hello";
     $date->setDate($dateString);
     $event->setStart($date);
     $event->setEnd($date);
     $event->setSummary($summary);
     $simpleEvent = $event->toSimpleObject();
     $this->assertEquals($dateString, $simpleEvent->start->date);
     $this->assertEquals($dateString, $simpleEvent->end->date);
     $this->assertEquals($summary, $simpleEvent->summary);
     $event2 = new Google_Service_Calendar_Event();
     $this->assertNull($event2->getStart());
 }
Beispiel #4
0
 /**
  * @param string $calendarId
  * @param string $summary
  * @param \DateTimeImmutable $start
  * @param \DateTimeImmutable $end
  * @param null|string $description
  * @return string Event ID in calendar
  */
 public function insertEvent($calendarId, $summary, \DateTimeImmutable $start, \DateTimeImmutable $end, $description = null)
 {
     $event = new \Google_Service_Calendar_Event();
     $event->setSummary($summary);
     $eventStart = new \Google_Service_Calendar_EventDateTime();
     $eventStart->setDateTime($start->format('c'));
     $event->setStart($eventStart);
     $eventEnd = new \Google_Service_Calendar_EventDateTime();
     $eventEnd->setDateTime($end->format('c'));
     $event->setEnd($eventEnd);
     $event->setDescription($description);
     $createdEvent = $this->service->events->insert($calendarId, $event);
     return $createdEvent->id;
 }
 public function registrarEvento()
 {
     require_once 'complements/Google/Client.php';
     require_once 'complements/Google/Service/Calendar.php';
     session_start();
     $client = new Google_Client();
     $client->setApplicationName("Google Calendar PHP Starter Application");
     // Visit https://code.google.com/apis/console?api=calendar to generate your
     // client id, client secret, and to register your redirect uri.
     $client->setClientId('1027408579728-fomlujink6upq6e1j2fu7nb4tu1frqq7.apps.googleusercontent.com');
     $client->setClientSecret('BTzww96MUByc_Ibsy2xX0asR');
     $client->setRedirectUri('http://www.hostf5.com.br/f5admin/agenda/redirect');
     $client->setDeveloperKey('AIzaSyB9AHH2apXJ7RJ25m5n2yLEMyhKOKA6sMU');
     $client->setScopes(array('https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly'));
     $cal = new Google_Service_Calendar($client);
     if (isset($_GET['logout'])) {
         unset($_SESSION['token']);
     }
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
         header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
     }
     if (isset($_SESSION['token'])) {
         $client->setAccessToken($_SESSION['token']);
     }
     if ($client->getAccessToken()) {
         $event = new Google_Service_Calendar_Event();
         $event->setSummary($title);
         $event->setLocation($location);
         $start = new Google_Service_Calendar_EventDateTime();
         $start->setTimeZone('America/Montreal');
         $start->setDateTime($date . 'T' . $startTime . ':00.000-06:00');
         $event->setStart($start);
         $end = new Google_Service_Calendar_EventDateTime();
         $end->setTimeZone('America/Montreal');
         $end->setDateTime($date . 'T' . $endTime . ':00.000-06:00');
         $event->setEnd($end);
         $attendee1 = new Google_Service_Calendar_EventAttendee();
         $attendee1->setEmail($email);
         $attendees = array($attendee1);
         $event->attendees = $attendees;
         $cal->events->insert($email, $event);
         $_SESSION['token'] = $client->getAccessToken();
     } else {
         $authUrl = $client->createAuthUrl();
         print "<a class='login' href='{$authUrl}'>Connect me!</a>";
     }
 }
 public function testModelMutation()
 {
     $data = json_decode($this->calendarData, true);
     $event = new Google_Service_Calendar_Event($data);
     $date = new Google_Service_Calendar_EventDateTime();
     date_default_timezone_set('UTC');
     $dateString = Date("c");
     $summary = "hello";
     $date->setDate($dateString);
     $event->setStart($date);
     $event->setEnd($date);
     $event->setSummary($summary);
     $simpleEvent = $event->toSimpleObject();
     $this->assertEquals($dateString, $simpleEvent->start->date);
     $this->assertEquals($dateString, $simpleEvent->end->date);
     $this->assertEquals($summary, $simpleEvent->summary);
     $event2 = new Google_Service_Calendar_Event();
     $this->assertNull($event2->getStart());
 }
 function addEvent($calendarId, $summary, $description, $location, $dataTimeStart, $dataTimeEnd, $email, $accept)
 {
     $event = new Google_Service_Calendar_Event();
     $event->setSummary($summary);
     $event->setLocation($location);
     $event->setDescription($description);
     $event->setVisibility('public');
     $start = new Google_Service_Calendar_EventDateTime();
     $start->setDateTime($dataTimeStart);
     $start->setTimeZone('America/Bogota');
     $event->setStart($start);
     $end = new Google_Service_Calendar_EventDateTime();
     $end->setDateTime($dataTimeEnd);
     $end->setTimeZone('America/Bogota');
     $event->setEnd($end);
     $reminder1 = new Google_Service_Calendar_EventReminder();
     $reminder1->setMethod('email');
     $reminder1->setMinutes('55');
     $reminder2 = new Google_Service_Calendar_EventReminder();
     $reminder2->setMethod('email');
     $reminder2->setMinutes('15');
     $reminder = new Google_Service_Calendar_EventReminders();
     $reminder->setUseDefault('false');
     $reminder->setOverrides(array($reminder1, $reminder2));
     $event->setReminders($reminder);
     //$event->setRecurrence(array('RRULE:FREQ=WEEKLY;UNTIL=20110701T170000Z'));
     $attendee1 = new Google_Service_Calendar_EventAttendee();
     $attendee1->setEmail($email);
     if ($accept == "true") {
         $attendee1->setResponseStatus('accepted');
     }
     $attendees = array($attendee1);
     $event->attendees = $attendees;
     $optParams = array('sendNotifications' => true, 'maxAttendees' => 1000);
     /*$creator = new Google_Service_Calendar_EventCreator();
             $creator->setDisplayName("UNAD Calendar");
             $creator->setEmail("*****@*****.**");
     
             $event->setCreator($creator);*/
     $nEvent = $this->service->events->insert($calendarId, $event, $optParams);
     return $nEvent;
 }
 /**
  * add event
  * @param string $class          class string(A,B,C,D,E)
  * @param string $subject        event title
  * @param int    $start_timestamp event start timestamp value
  * @param int    $end_timestamp  event end timestamp value
  */
 public function addEvent($class, $subject, $start_timestamp, $end_timestamp)
 {
     $pd_calendar_id = $this->getPdCalendarId($class);
     $event = new Google_Service_Calendar_Event();
     $event->setSummary($subject);
     $start_datetime = new Google_Service_Calendar_EventDateTime();
     $start_datetime->setDateTime(date('c', $start_timestamp));
     $event->setStart($start_datetime);
     $end_datetime = new Google_Service_Calendar_EventDateTime();
     $end_datetime->setDateTime(date('c', $end_timestamp));
     $event->setEnd($end_datetime);
     $reminder = new Google_Service_Calendar_EventReminder();
     $reminder->setMethod('popup');
     $reminder->setMinutes(10);
     $reminders = new Google_Service_Calendar_EventReminders();
     $reminders->setUseDefault(false);
     $reminders->setOverrides(array($reminder));
     $event->setReminders($reminders);
     echo "invent insert" . $class . ":" . date('c', $start_timestamp) . ":" . $subject . "\n";
     $this->getServiceCalendar()->events->insert($pd_calendar_id, $event);
 }
 /**
  * The customerCreate method prepares data for Stripe_Customer::create and attempts to
  * create a customer.
  *
  * @param array	$data The data passed directly to Stripe's API.
  * @return array $customer if success, string $error if failure.
  */
 public function updateEvent($data)
 {
     $client = new Google_Client();
     $client->setApplicationName("Plat");
     $key = file_get_contents($this->googleApiKeyFile);
     // separate additional scopes with a comma
     $scopes = "https://www.googleapis.com/auth/calendar";
     //$client->setScopes(array($scopes));
     $cred = new Google_Auth_AssertionCredentials($this->googleEmailAddress, array($scopes), $key);
     $client->setAssertionCredentials($cred);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($cred);
     }
     $service = new Google_Service_Calendar($client);
     $event = new Google_Service_Calendar_Event();
     //$event->setId($data['eventId']);
     $event->setSummary($data['eventSummary']);
     $event->setDescription($data['eventDescription']);
     $event->setLocation($data['eventLocation']);
     $start = new Google_Service_Calendar_EventDateTime();
     $start->setDateTime($data['eventStartDate']);
     $start->setTimeZone($data['eventTimeZone']);
     $event->setStart($start);
     $end = new Google_Service_Calendar_EventDateTime();
     $end->setDateTime($data['eventEndDate']);
     $end->setTimeZone($data['eventTimeZone']);
     $event->setEnd($end);
     $attendee1 = new Google_Service_Calendar_EventAttendee();
     $attendee1->setEmail(Configure::read("ADMIN_ORDER_EVENT_EMAIL"));
     $attendees = array($attendee1);
     $event->attendees = $attendees;
     $event->setSequence(Configure::read("GOOGLE_CALENDAR_API_SEQUENCE"));
     $calendar_id = Configure::read("GOOGLE_CALENDAR_ID");
     try {
         $updateEvent = $service->events->update($calendar_id, $data['eventId'], $event);
         //
         $new_event_status = $updateEvent->getStatus();
         return $new_event_status;
     } catch (Google_Service_Exception $e) {
         syslog(LOG_ERR, $e->getMessage());
         return $e->getMessage();
     }
 }
 /**
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function addAction(Request $request)
 {
     $responseData = ['error' => ''];
     try {
         $userId = $request->get('userid');
         $ticketId = $request->get('ticketid');
         $date = $request->get('startdate');
         $starttime = $request->get('starttime');
         $endtime = $request->get('endtime');
         $user = $this->getDoctrine()->getRepository('ProjectPreviewUserBundle:User')->find($userId);
         if (is_null($user)) {
             throw new \Exception('User not found');
         }
         $ticket = $this->getDoctrine()->getRepository('ProjectPreviewPreviewBundle:Ticket')->find($ticketId);
         if (is_null($ticket)) {
             throw new \Exception('Ticket not found');
         }
         $googleService = $this->get('google_api_service');
         $client = $googleService->getClient();
         $client->setAccessToken($user->getGoogleAgendaToken());
         $service = new \Google_Service_Calendar($client);
         $event = new \Google_Service_Calendar_Event();
         $event->setDescription('test');
         $startDateTime = new \DateTime($date . ' ' . $starttime);
         $formattedStart = $startDateTime->format(\DateTime::RFC3339);
         $endDateTime = new \DateTime($date . ' ' . $endtime);
         $formattedEnd = $endDateTime->format(\DateTime::RFC3339);
         $start = new \Google_Service_Calendar_EventDateTime();
         $start->setDateTime($formattedStart);
         $end = new \Google_Service_Calendar_EventDateTime();
         $end->setDateTime($formattedEnd);
         $event->setStart($start);
         $event->setEnd($end);
         $event->setSummary(sprintf('[%s] #%d', $ticket->getProject()->getName(), $ticket->getId()));
         $event->setDescription(sprintf('https://projets.preview-app.net/project/%d/issues/kanban?issue=%d', $ticket->getProject()->getId(), $ticket->getId()));
         $service->events->insert('primary', $event);
     } catch (\Exception $e) {
         $responseData['error'] = $e->getMessage();
     }
     return new JsonResponse($responseData);
 }
 public function  CUST_customercalendercreation1($calPrimary,$custid,$startdate,$startdate_starttime,$startdate_endtime,$enddate,$enddate_starttime,$enddate_endtime,$firstname,$lastname,$mobile,$intmobile,$office,$customermailid,$unit,$roomtype,$unitrmtype)
 {
     try{
     $calId=$this->GetEICalendarId();
     $initialsdate=$startdate;
     $initialedate=$enddate;
     $calendername= $firstname.' '.$lastname;
     $contactno="";
     $contactaddr="";
     if($mobile!=null)
     {$contactno=$mobile;}
     else if($intmobile!=null)
     {$contactno=$intmobile;}
     else if($office!=null)
     {$contactno=$office;}
     if($contactno!=null && $contactno!="")
     {
         $contactaddr=$custid." "."EMAIL :".$customermailid.",CONTACT NO :".$contactno;
     }
     else
     {
         $contactaddr=$custid." "."EMAIL :".$customermailid;
     }
     if($unitrmtype!="")
     {
         $details =$unit. " " . $calendername . " " .$unitrmtype." ". "CHECKIN";
     }
     else
     {
         $details =$unit. " " . $calendername . " " . "CHECKIN";
     }
     $details1 =$unit. " " .$roomtype ;
     if($initialsdate!="")
     {
         $event = new Google_Service_Calendar_Event();
         $startevents=$this->CalenderTime_Convertion($startdate, $startdate_starttime, $startdate_endtime);
         $event->setStart($startevents[0]);
         $event->setEnd($startevents[1]);
         $event->setDescription($contactaddr);
         $event->setLocation($details1);
         $event->setSummary($details);
         $createdEvent = $calPrimary->events->insert($calId, $event); // to create a event
     }
     $endevents=$this->CalenderTime_Convertion($enddate,$enddate_starttime,$enddate_endtime);
     $detailsend =$unit. " " . $calendername . " " . "CHECKOUT";
     $detailsend1 =$unit. " " .$roomtype ;
     if($initialedate!="")
     {
         $event = new Google_Service_Calendar_Event();
         $event->setStart($endevents[0]);
         $event->setEnd($endevents[1]);
         $event->setDescription($contactaddr);
         $event->setLocation($detailsend1);
         $event->setSummary($detailsend);
         $createdEvent = $calPrimary->events->insert($calId, $event); // to create a event
     }
         return 1;
     }
     catch(Exception $e){
         return $e->getMessage();
     }
 }
 public function  CUST_customercalendercreation_StartDate($servicedoc,$calId,$calPrimary,$calevents,$custid,$firstname,$lastname,$mobile,$intmobile,$office,$customermailid,$unit,$unitrmtype)
 {
     try{
         $folderIdCustomer=$this->Mdl_eilib_calender->getcustomerfileid($servicedoc,$custid);
         for($k=0;$k<count($calevents);$k++)
         {
             $attachments=[];
             $Events=explode(',',$calevents[$k]);
             if($Events[5]=="CHECKIN"){
                 for($j=0;$j<count($folderIdCustomer)&&count($folderIdCustomer)>0;$j++){
                     $servicedoc= $this->Mdl_eilib_common_function->get_service_document();
                     $file = $servicedoc->files->get($folderIdCustomer[$j]);
                     $attachments[]= array(
                         'fileUrl' => $file->alternateLink,
                         'mimeType' => $file->mimeType,
                         'title' => $file->title
                     );}}
             $initialsdate = $Events[2];
             $calendername = $firstname . ' ' . $lastname;
             $contactno = "";
             $contactaddr = "";
             if ($mobile != null) {
                 $contactno = $mobile;
             } else if ($intmobile != null) {
                 $contactno = $intmobile;
             } else if ($office != null) {
                 $contactno = $office;
             }
             if ($contactno != null && $contactno != "") {
                 $contactaddr = $custid . " " . "EMAIL :" . $customermailid . ",CONTACT NO :" . $contactno;
             } else {
                 $contactaddr = $custid . " " . "EMAIL :" . $customermailid;
             }
             if ($Events[1] != "") {
                 $details = $Events[0] . " " . $calendername . " " . $Events[1] . " " . $Events[5];
             } else {
                 $details = $Events[0] . " " . $calendername . " " . $Events[5];
             }
             $details1 = $Events[0] . " " . $Events[1];
             if ($initialsdate != "") {
                 $event = new Google_Service_Calendar_Event();
                 $startevents = $this->CalenderTime_Convertion($Events[2], $Events[3], $Events[4]);
                 $event->setStart($startevents[0]);
                 $event->setEnd($startevents[1]);
                 $event->setDescription($contactaddr);
                 $event->setLocation($details1);
                 $event->setSummary($details);
                 if(count($folderIdCustomer)>0 && $Events[5]=="CHECKIN") {
                     $event->setAttachments($attachments);
                     $createdEvent = $calPrimary->events->insert($calId, $event,array('supportsAttachments' => TRUE)); // to create a event
                 }else{
                     $createdEvent = $calPrimary->events->insert($calId, $event);
                 }
             }
         }
         return 1;
     }
     catch(Exception $e){
         return $e->getMessage();
     }
 }
require_once dirname(__FILE__) . '/lib/autoloader.php';
// config parse
$pd_config = new PdConfig();
if ($pd_config->hasErrors()) {
    echo $pd_config->getErrorMessageText();
    exit(1);
}
$pd_calendar = new PdCalendar();
$pd_calendar->setAuthEmail($pd_config->getGcalAuthEmail());
$pd_calendar->setP12Key(file_get_contents($pd_config->getGcalP12KeyfilePath()));
$subject = 'イベント登録テスト';
$start_timestamp = strtotime('2015-04-09 07:00');
$end_timestamp = strtotime('2015-04-09 08:00');
$event = new Google_Service_Calendar_Event();
$event->setSummary($subject);
$start_datetime = new Google_Service_Calendar_EventDateTime();
$start_datetime->setDateTime(date('c', $start_timestamp));
$event->setStart($start_datetime);
$end_datetime = new Google_Service_Calendar_EventDateTime();
$end_datetime->setDateTime(date('c', $end_timestamp));
$event->setEnd($end_datetime);
$reminder = new Google_Service_Calendar_EventReminder();
$reminder->setMethod('popup');
$reminder->setMinutes(13);
$reminders = new Google_Service_Calendar_EventReminders();
$reminders->setUseDefault(false);
$reminders->setOverrides(array($reminder));
$event->setReminders($reminders);
echo "invent insert" . ":" . date('c', $start_timestamp) . ":" . $subject . "\n";
$pd_calendar->getServiceCalendar()->events->insert($pd_calendar->getPdCalendarId('C'), $event);
Beispiel #14
0
/**
 * Book a specific range of dates. A start date and end date
 * combination is provided. If the dates free, the dates
 * are marked as booked. The range is inclusive.
 * @param service the service which the API is 
 * 			called through
 * @param summary - the title of the event
 * @param date_start the start date of the event
 * @param date_end the end date of the event
 * @return nothing
 */
function bookDates($service, $summary, $date_start, $date_end)
{
    $calendarId = '*****@*****.**';
    date_default_timezone_set('Europe/Berlin');
    $event = new Google_Service_Calendar_Event();
    $event->setSummary($summary);
    // $event->setLocation('At the orchard');
    $start = new Google_Service_Calendar_EventDateTime();
    $start->setDateTime($date_start);
    $event->setStart($start);
    $end = new Google_Service_Calendar_EventDateTime();
    $end->setDateTime($date_end);
    $event->setEnd($end);
    $createdEvent = $service->events->insert($calendarId, $event);
}
Beispiel #15
0
     $hr += 12;
 }
 $event = new Google_Service_Calendar_Event();
 //            $event->setSummary($eventTitle);
 //
 //            $start = new Google_Service_Calendar_EventDateTime();
 //            //5 establishes eastern time
 //            $start->setDateTime("2015-01-04T'T' . $hr . ':' . $min . ':00.000-05:00');
 //            $event->setStart($start);
 //            $end = new Google_Service_Calendar_EventDateTime();
 //            $end->setDateTime($date . 'T' . $endhr . ':' . $endmin . ':00.000-05:00');
 //            $event->setEnd($end);
 $event->setSummary("hello");
 $start = new Google_Service_Calendar_EventDateTime();
 $start->setDateTime('2015-01-03T10:22:00.000-05:00');
 $event->setStart($start);
 $end = new Google_Service_Calendar_EventDateTime();
 $end->setDateTime('2015-01-05T10:25:00.000-05:00');
 $event->setEnd($end);
 alert("hello");
 $attendee1 = new Google_Service_Calendar_EventAttendee();
 $attendee1->setEmail($email);
 $attendees = array($attendee1);
 $createdEvent = $service->events->insert('primary', $event);
 echo $createdEvent->getId();
 alert("Hello2");
 echo $date;
 echo $hr;
 echo $min;
 echo $eventTitle;
 echo $ampm;
Beispiel #16
0
 public function onRaidCreate($aRaidId)
 {
     if ($this->authenticate()) {
         // Query the given raid, make sure we include canceled and closed
         // raids
         $Parameters = array('raid' => $aRaidId, 'canceled' => true, 'closed' => true);
         $RaidResult = Api::queryRaid($Parameters);
         if (count($RaidResult) > 0) {
             // As we specified a specific raid id, we are only
             // interested in the first (and only) raid.
             // Cache and set UTC timezone just to be sure.
             $Raid = $RaidResult[0];
             $LocationName = $this->mLocations[$Raid['LocationId']];
             $Url = getBaseURL() . 'index.php#raid,' . $aRaidId;
             $Timezone = date_default_timezone_get();
             try {
                 date_default_timezone_set('UTC');
                 $Start = new Google_Service_Calendar_EventDateTime();
                 $Start->setDateTime(date($this->mDateFormat, intval($Raid['Start'])));
                 $Start->setTimeZone('UTC');
                 $End = new Google_Service_Calendar_EventDateTime();
                 $End->setDateTime(date($this->mDateFormat, intval($Raid['End'])));
                 $End->setTimeZone('UTC');
                 $Properties = new Google_Service_Calendar_EventExtendedProperties();
                 $Properties->setShared(array('RaidId' => $aRaidId));
                 $Source = new Google_Service_Calendar_EventSource();
                 $Source->setTitle('Raidplaner link');
                 $Source->setUrl($Url);
                 $Event = new Google_Service_Calendar_Event();
                 $Event->setSummary($LocationName . ' (' . $Raid['Size'] . ')');
                 $Event->setLocation($LocationName);
                 $Event->setDescription($Raid['Description']);
                 $Event->setOriginalStartTime($Start);
                 $Event->setStart($Start);
                 $Event->setEnd($End);
                 $Event->setExtendedProperties($Properties);
                 $Event->setSource($Source);
                 $this->mCalService->events->insert(GOOGLE_CAL_ID, $Event);
             } catch (Exception $Ex) {
                 $Out = Out::getInstance();
                 $Out->pushError($Ex->getMessage());
             }
             date_default_timezone_set($Timezone);
         }
     }
 }
 public function createEvent($calendarID, array $eventData)
 {
     $event = new Google_Service_Calendar_Event();
     $event->setSummary($eventData['summary']);
     $event->setLocation($eventData['location']);
     $event->setDescription($eventData['description']);
     $start = new Google_Service_Calendar_EventDateTime();
     //$start->setDateTime('2014-9-30T10:00:00.000-05:00');
     if (!isset($eventData['startDatetime'])) {
         $start->setDateTime($eventData['startDate'] . 'T' . $eventData['startTime']);
     } else {
         $start->setDateTime($eventData['startDateTime']);
     }
     $event->setStart($start);
     $end = new Google_Service_Calendar_EventDateTime();
     //$end->setDateTime('2014-9-30T10:25:00.000-05:00');
     if (!isset($eventData['endDateTime'])) {
         $end->setDateTime($eventData['endDate'] . 'T' . $eventData['endTime']);
     } else {
         $end->setDateTime($eventData['startDateTime']);
     }
     $event->setEnd($end);
     $createdEvent = $this->service->events->insert($calendarID, $event);
     return $createdEvent->getID();
 }
function URSRC_calendar_create($loggin,$fileId,$loginid_name,$URSC_uld_id,$finaldate,$calenderid,$status,$form,$filesarray,$URSRC_firstname,$URSRC_lastname,$folderid){
    global $con,$ClientId,$ClientSecret,$RedirectUri,$DriveScopes,$CalenderScopes,$Refresh_Token;
    $drive = new Google_Client();
    $drive->setClientId($ClientId);
    $drive->setClientSecret($ClientSecret);
    $drive->setRedirectUri($RedirectUri);
    $drive->setScopes(array($DriveScopes,$CalenderScopes));
    $drive->setAccessType('online');
    $authUrl = $drive->createAuthUrl();
    $refresh_token= $Refresh_Token;
    $drive->refreshToken($refresh_token);
    $service = new Google_Service_Drive($drive);
    if($form=='TERMINATE'){
        $file_arraycount=1;
        try {
            $permissions = $service->permissions->listPermissions($fileId);
            $return_value= $permissions->getItems();
        } catch (Exception $e) {
            $ss_flag=0;
        }
        foreach ($return_value as $key => $value) {
            if ($value->emailAddress==$loggin) {
                $permission_id=$value->id;
            }
        }
        if($permission_id!=''){
            try {
                $service->permissions->delete($fileId, $permission_id);
                $ss_flag=1;
            } catch (Exception $e) {
                $ss_flag=0;
            }
        }
        else{

            $ss_flag=1;
        }
    }
    else{
        $value=$loggin;
        $type='user';
        $role='reader';
        $email=$loggin;
        $newPermission = new Google_Service_Drive_Permission();
        $newPermission->setValue($value);
        $newPermission->setType($type);
        $newPermission->setRole($role);
        $newPermission->setEmailAddress($email);
        try {
            $service->permissions->insert($fileId, $newPermission);
            $ss_flag=1;
        } catch (Exception $e) {
            $ss_flag=0;
        }

        if($ss_flag==1){
            if($filesarray!='')
            {
                $file_array=array();
                $allfilearray=(explode(",",$filesarray));
                foreach ($allfilearray as $value)
                {
                    $uploadfilename=$value;
                    $drivefilename=$URSRC_firstname.' '.$URSRC_lastname.'-'.$uploadfilename;
                    $extension =(explode(".",$uploadfilename));
                    if($extension[1]=='pdf'){$mimeType='application/pdf';}
                    if($extension[1]=='jpg'){$mimeType='image/jpeg';}
                    if($extension[1]=='png'){$mimeType='image/png';}
                    $file_id_value =insertFile($service,$drivefilename,'PersonalDetails',$folderid,$mimeType,$uploadfilename);
                    if($file_id_value!=''){
                        array_push($file_array,$file_id_value);
                    }
                }
                $file_arraycount=count($file_array);
            }
            else{
                $file_arraycount=1;
            }
        }


    }
    if($ss_flag==1 && $file_arraycount>0){
        $cal = new Google_Service_Calendar($drive);
        $event = new Google_Service_Calendar_Event();
        $event->setsummary($loginid_name.'  '.$status);
        $event->setDescription($URSC_uld_id);
        $start = new Google_Service_Calendar_EventDateTime();
        $start->setDate($finaldate);//setDate('2014-11-18');
        $event->setStart($start);
        $event->setEnd($start);
        try{
            $createdEvent = $cal->events->insert($calenderid, $event);
            $cal_flag=1;
        }
        catch(Exception $e){
            $cal_flag=0;
        }
    }
    $flag_array=[$ss_flag,$cal_flag,$file_id_value,$file_array];
    return $flag_array;
}
function URSRC_calendar_create($loginid_name, $URSC_uld_id, $finaldate, $calenderid, $status)
{
    global $con, $ClientId, $ClientSecret, $RedirectUri, $DriveScopes, $CalenderScopes, $Refresh_Token;
    $drive = new Google_Client();
    $Client = get_servicedata();
    $ClientId = $Client[0];
    $ClientSecret = $Client[1];
    $RedirectUri = $Client[2];
    $DriveScopes = $Client[3];
    $CalenderScopes = $Client[4];
    $Refresh_Token = $Client[5];
    $drive->setClientId($ClientId);
    $drive->setClientSecret($ClientSecret);
    $drive->setRedirectUri($RedirectUri);
    $drive->setScopes(array($DriveScopes, $CalenderScopes));
    $drive->setAccessType('online');
    $authUrl = $drive->createAuthUrl();
    $refresh_token = $Refresh_Token;
    $drive->refreshToken($refresh_token);
    $cal = new Google_Service_Calendar($drive);
    $event = new Google_Service_Calendar_Event();
    $event->setsummary($loginid_name . '  ' . $status);
    if ($status == 'JOIN DATE') {
        $event->setDescription($URSC_uld_id);
    }
    $start = new Google_Service_Calendar_EventDateTime();
    $start->setDate($finaldate);
    //setDate('2014-11-18');
    $event->setStart($start);
    $event->setEnd($start);
    try {
        $createdEvent = $cal->events->insert($calenderid, $event);
        $cal_flag = 1;
    } catch (Exception $e) {
        $cal_flag = 0;
    }
    return $cal_flag;
}
 public function handleTask(&$context)
 {
     $entityDataKey = "block_" . $this->getBlockId() . "_eventid";
     // Setze das Datum und verwende das RFC 3339 Format.
     $startDate = $this->get("eventstartdate", $context);
     $this->addStat('Startdate' . $startDate);
     $startTime = $this->get("eventstarttime", $context);
     $this->addStat('Starttime' . $startTime);
     $parts = explode(':', $startTime);
     if (count($parts) == 3) {
         $startTime = $parts[0] . ':' . $parts[1];
     }
     if (strlen($startTime) < 5) {
         $startTime = "0" . $startTime;
     }
     $duration = $this->get("eventduration", $context);
     $date = strtotime("+" . $duration . " minutes", strtotime($startDate . " " . $startTime));
     $endDate = date("Y-m-d", $date);
     $endTime = date("H:i", $date);
     $tzOffset = "+01";
     $this->init();
     if (1 == 0 && $context->existEntityData($entityDataKey)) {
         $entityId = $context->getEntityData($entityDataKey);
         try {
             $event = $service->getCalendarEventEntry($entityId);
             $when = $service->newWhen();
             $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
             $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
             $event->when = array($when);
             $event->save();
             return "yes";
         } catch (Zend_Gdata_App_Exception $e) {
             $this->addStat("existing Event not found. Create new!");
         }
     }
     $event = new Google_Service_Calendar_Event();
     $event->setSummary($this->get("eventtitle", $context));
     #$event->setLocation('Somewhere');
     $start = new Google_Service_Calendar_EventDateTime();
     $start->setDateTime("{$startDate}T{$startTime}:00.000{$tzOffset}:00");
     #$start->setTimeZone('America/Los_Angeles');
     $event->setStart($start);
     $event->setDescription($this->get("eventdescr", $context));
     $end = new Google_Service_Calendar_EventDateTime();
     $end->setDateTime("{$endDate}T{$endTime}:00.000{$tzOffset}:00");
     #$end->setTimeZone('America/Los_Angeles');
     $event->setEnd($end);
     $event->setVisibility($this->get("privacy"));
     $event = $this->service->events->insert(html_entity_decode($this->get("calendar")), $event);
     $context->addEntityData($entityDataKey, $event->getId());
     $this->storeAccessKey();
     return "yes";
 }
 private function update_event_on_google_calendar($event, $ext_calendar, $ext_user, $service)
 {
     $insert_event = false;
     //update event
     if ($event->getSpecialID() != "") {
         //First retrieve the event from the google API.
         try {
             $newEvent = $service->events->get($ext_calendar->getOriginalCalendarId(), $event->getSpecialID());
         } catch (Exception $e) {
             Logger::log("Fail to get event from google: " . $event->getId());
             Logger::log($e->getMessage());
             throw $e;
         }
     }
     //insert event
     if (!$newEvent instanceof Google_Service_Calendar_Event) {
         //create google event
         $newEvent = new Google_Service_Calendar_Event();
         $insert_event = true;
     }
     $newEvent->setSummary($event->getObjectName());
     $newEvent->setDescription($event->getDescription());
     $start = new Google_Service_Calendar_EventDateTime();
     $end = new Google_Service_Calendar_EventDateTime();
     //All day event
     if ($event->getTypeId() == 2) {
         $star_time = date("Y-m-d", $event->getStart()->getTimestamp());
         $end_time = date("Y-m-d", $event->getDuration()->getTimestamp());
         $start->setDate($star_time);
         $end->setDate($end_time);
     } else {
         $star_time = date(DATE_RFC3339, $event->getStart()->getTimestamp());
         $end_time = date(DATE_RFC3339, $event->getDuration()->getTimestamp());
         $start->setDateTime($star_time);
         $end->setDateTime($end_time);
     }
     $newEvent->setStart($start);
     $newEvent->setEnd($end);
     try {
         if ($insert_event) {
             // insert event
             $createdEvent = $service->events->insert($ext_calendar->getOriginalCalendarId(), $newEvent);
         } else {
             // update event
             $createdEvent = $service->events->update($ext_calendar->getOriginalCalendarId(), $newEvent->getId(), $newEvent);
         }
     } catch (Exception $e) {
         Logger::log("Fail to add event: " . $event->getId());
         Logger::log($e->getMessage());
         throw $e;
     }
     $event->setSpecialID($createdEvent->getId());
     $event->setUpdateSync(ExternalCalendarController::date_google_to_sql($createdEvent->getUpdated()));
     $event->setExtCalId($ext_calendar->getId());
     $event->save();
     $invitation = EventInvitations::findOne(array('conditions' => array('contact_id = ' . $ext_user->getContactId() . ' AND event_id =' . $event->getId())));
     if ($invitation) {
         $invitation->setUpdateSync(ExternalCalendarController::date_google_to_sql($createdEvent->getUpdated()));
         $invitation->setSpecialId($createdEvent->getId());
         $invitation->save();
     }
 }
Beispiel #22
0
 /**
  * Creates a new google calendar event and returns
  * the resulting event inside an Event object.
  *
  * @param Event $event
  *
  * @return Event
  */
 public function createEvent(Event $event)
 {
     $this->setCalendarId($event->calendar_id);
     /*
      * Create new google event object
      */
     $googleEvent = new \Google_Service_Calendar_Event();
     /*
      * Set Details
      */
     $googleEvent->setSummary($event->title);
     $googleEvent->setDescription($event->description);
     $googleEvent->setLocation($event->location);
     /*
      * Set Start Date
      */
     $start = $this->createDateTime($event->start, $event->timeZone, $event->all_day);
     $googleEvent->setStart($start);
     /*
      * Set End Date
      */
     $end = $this->createDateTime($event->end, $event->timeZone, $event->all_day);
     $googleEvent->setEnd($end);
     /*
      * Set Recurrence Rule, make sure it's not empty
      */
     if ($event->rrule) {
         $googleEvent->setRecurrence([$event->rrule]);
     }
     /*
      * Create the event
      */
     $newGoogleEvent = $this->service->events->insert($this->calendarId, $googleEvent);
     return $this->createEventObject($newGoogleEvent);
 }
Beispiel #23
0
 /**
  * Saves event
  *
  * @param DateTime booking start
  * @param DateTime booking end
  * @param array additional booking details
  * @param string calendarId of the calendar to save it to
  * @return boolean success or failure
  */
 public function saveEvent($start_date, $end_date, $details, $calendarId)
 {
     if ($this->authorised()) {
         // get memeber details so we can build the title
         $this->Member = new Member();
         $member = $this->Member->getMemberSummaryForMember($details['member'], false);
         // build the parts of the event
         $title = $member['Member']['firstname'] . " " . $member['Member']['surname'];
         $start = new Google_Service_Calendar_EventDateTime();
         $start->setDateTime($start_date->format(self::DATETIME_STR));
         $end = new Google_Service_Calendar_EventDateTime();
         $end->setDateTime($end_date->format(self::DATETIME_STR));
         // set up the event
         $event = new Google_Service_Calendar_Event();
         $event->setSummary($title);
         $event->setDescription(json_encode($details));
         $event->setStart($start);
         $event->setEnd($end);
         // send it to google
         $created = $this->__service->events->insert($calendarId, $event);
         if ($created->getId()) {
             return true;
         }
         return false;
     }
 }
Beispiel #24
0
 public function addEvent($recordid, $Data, $tzOffset)
 {
     set_include_path($this->root_directory . "modules/Calendar4You/");
     $startDate = $Data["date_start"];
     $endDate = $Data["due_date"];
     global $default_timezone;
     $startTime = $Data["time_start"];
     $endTime = $Data["time_end"];
     $event = new Google_Service_Calendar_Event();
     $event->setSummary(trim($Data["subject"]));
     $event->setDescription($Data["description"]);
     $event->setLocation(trim($Data["location"]));
     $start = new Google_Service_Calendar_EventDateTime();
     if (strlen($startTime) > 6) {
         $start->setDateTime($startDate . 'T' . $this->removeLastColon($startTime) . ':00.000');
     } else {
         $start->setDateTime($startDate . 'T' . $this->removeLastColon($startTime) . ':00:00.000');
     }
     $start->setTimeZone("{$default_timezone}");
     $event->setStart($start);
     $end = new Google_Service_Calendar_EventDateTime();
     if (strlen($endTime) > 6) {
         $end->setDateTime($endDate . 'T' . $this->removeLastColon($endTime) . ':00.000');
     } else {
         $end->setDateTime($endDate . 'T' . $this->removeLastColon($endTime) . ':00:00.000');
     }
     $end->setTimeZone("{$default_timezone}");
     $event->setEnd($end);
     $SendEventNotifications = new Google_Service_Calendar_EventReminders();
     //$SendEventNotifications->setValue(true);
     $event->setReminders($SendEventNotifications);
     $whos = $this->getInvitedUsersEmails($event, $recordid);
     if (count($whos) > 0) {
         $event->attendees = $whos;
     }
     //        $appCallUri = "";
     //
     //        foreach ($this->gListFeed as $calendar) {
     //            if ($calendar->id == $this->selected_calendar) $appCallUri = $calendar->content->src;
     //        }
     try {
         $createdEvent = $this->gService->events->insert($this->selected_calendar, $event);
         $eventid = urldecode($createdEvent->getId());
     } catch (Exception $e) {
         $status = null;
     }
     set_include_path($this->root_directory);
     return $eventid;
 }
        $defaultFolks = array("*****@*****.**");
        foreach ($defaultFolks as $defaultFolk) {
            $attendee = new Google_Service_Calendar_EventAttendee();
            $attendee->setEmail($defaultFolk);
            $attendees[] = $attendee;
        }
        $attendee = new Google_Service_Calendar_EventAttendee();
        $attendee->setEmail($email);
        $attendees[] = $attendee;
        $event->setAttendees($attendees);
        $start = new DateTime($date);
        $start->setTimezone(new DateTimeZone($timezone));
        $gstart = new Google_Service_Calendar_EventDateTime();
        $gstart->setDateTime($start->format(DateTime::ISO8601));
        $gstart->setTimeZone($timezone);
        $event->setStart($gstart);
        $end = new DateTime($date);
        $end->setTimezone(new DateTimeZone($timezone));
        $end->add(new DateInterval("PT1H"));
        $gend = new Google_Service_Calendar_EventDateTime();
        $gend->setDateTime($end->format(DateTime::ISO8601));
        $gend->setTimeZone($timezone);
        $event->setEnd($gend);
        //Next insert it into the calendar
        $calendarService->events->insert($calendarId, $event);
        sendMail($name, $date, $email);
        echo json_encode(true);
    }
}
function sendMail($name, $date, $to)
{
 public function addEventAfterReservation($hours_array, $client_id, $resDate, $reservation_id, $reserve_type)
 {
     $hour_id = $hours_array['hours_id'];
     $choosen_places = $hours_array['choosen_places'];
     $direction_id = $hours_array['dirID'];
     $instructorCursor = Dispatcher::$mysqli->query("select * from instructor join instructor_has_hours " . "on instructor.`Person_id`=instructor_has_hours.instructor_id " . "where instructor_has_hours.hours_id={$hour_id}");
     $instructorRow = $instructorCursor->fetch_assoc();
     $defaultInstructorID = $instructorRow['Person_id'];
     $defaultInstructorCalendarID = $instructorRow['calendar_id'];
     $clientCursor = Dispatcher::$mysqli->query("select * from person where id={$client_id}");
     $clientRow = $clientCursor->fetch_assoc();
     $hourCursor = Dispatcher::$mysqli->query("select *, voucher_info.`name` as voucherName from hours_to_display " . "join voucher_info on hours_to_display.during_type=voucher_info.`type` " . "where hours_to_display.id={$hour_id}");
     $hourRow = $hourCursor->fetch_assoc();
     $event = new Google_Service_Calendar_Event();
     $event->setSummary($choosen_places . " " . $hourRow['voucherName']);
     $event->setLocation('Saska, Praha 1');
     $start = new Google_Service_Calendar_EventDateTime();
     $start->setDateTime($resDate . 'T' . $hourRow['hour_from'] . ':00.000+02:00');
     $start->setTimeZone('Europe/Prague');
     $event->setStart($start);
     $end = new Google_Service_Calendar_EventDateTime();
     $end->setDateTime($resDate . 'T' . $hourRow['hour_to'] . ':00.000+02:00');
     $end->setTimeZone('Europe/Prague');
     $event->setEnd($end);
     $event->description = $clientRow['name'] . "\n" . $clientRow['email'] . "\n" . $clientRow['telefone'] . "\n" . $choosen_places . "\n\n";
     try {
         $new_event = $this->google_api_service->events->insert($defaultInstructorCalendarID, $event);
         $new_event_id = $new_event->getId();
         Dispatcher::$mysqli->query("insert into event(clndr_event_id, `instructor_Person_id`, hours_id, date, has_changes) " . "values ('{$new_event_id}', '{$defaultInstructorID}', '{$hour_id}', '{$resDate}', 0)");
         Dispatcher::$mysqli->query("insert into reservation_has_hours (reservation_id, `Person_id`, hours_id, " . "directions_en_id, " . "choosen_places, " . "date, reserve_type, event_clndr_event_id) " . "values ({$reservation_id}, {$client_id}, {$hour_id}, '{$direction_id}', {$choosen_places}, '{$resDate}', '{$reserve_type}', '{$new_event_id}')");
     } catch (Google_Service_Exception $e) {
         echo '<pre>';
         print_r($e);
         syslog(LOG_ERR, $e->getMessage());
     }
     print_r(Dispatcher::$mysqli->error);
 }
Beispiel #27
0
                // 削除処理
                $service->events->delete($calenderId, $eventId);
                echo '[Delete Event]' . ':' . $summary . ' (' . ($start->date ? $start->date : $start->dateTime) . ')' . "\n";
                continue;
            }
            // 既に登録されているデータなので、更新リストから除外
            unset($aipoEvents[$aipoId]);
        }
        $pageToken = $events->getNextPageToken();
        if ($pageToken) {
            $optParams = array('pageToken' => $pageToken);
            $events = $service->events->listEvents($calenderId, $optParams);
        } else {
            break;
        }
    }
    // イベント登録
    if (!empty($aipoEvents)) {
        foreach ($aipoEvents as $aipoEvent) {
            $event = new Google_Service_Calendar_Event();
            $event->setSummary($aipoEvent['summary']);
            $event->setStart($aipoEvent['start']);
            $event->setEnd($aipoEvent['end']);
            $event->setRecurrence($aipoEvent['recurrence']);
            $event->setICalUID($aipoEvent['uid']);
            $service->events->insert($calenderId, $event);
            echo '[Insert Event]' . ':' . $aipoEvent['summary'] . ' (' . ($aipoEvent['start']->date ? $aipoEvent['start']->date : $aipoEvent['start']->dateTime) . ')' . "\n";
        }
    }
}
exit(0);
 /**
  * @param User $user
  * @param      $time
  * @param      $summary
  * @param      $description
  *
  * @return bool
  */
 public function schedule(User $user, $time, $summary, $description)
 {
     $client = $this->getAuthenticateClient($user);
     $service = new \Google_Service_Calendar($client);
     /**
      * @var \Google_Service_Calendar_Event[] $events
      */
     $events = [];
     $total = $time;
     $step = $time > 10 ? 10 : $time;
     $count = 0;
     $id = rand(11111111, 99999999);
     while ($total > 0 && $step > 1) {
         $start = $this->getNextAvaliableSchedule($client, $step);
         if (is_null($start)) {
             $step--;
             continue;
         }
         $event = new \Google_Service_Calendar_Event();
         $eventStart = new \Google_Service_Calendar_EventDateTime();
         $eventStart->setDateTime($start->format(\DateTime::RFC3339));
         $event->setStart($eventStart);
         $eventEnd = new \Google_Service_Calendar_EventDateTime();
         $end = new \DateTime('@' . $start->getTimestamp());
         $end->modify('+' . $step * 60 . ' minute');
         $eventEnd->setDateTime($end->format(\DateTime::RFC3339));
         $event->setEnd($eventEnd);
         $event->setId($id . $count++);
         $event->setSummary($summary);
         $event->setDescription($description);
         $events[] = $event;
         $total -= $step;
         $step = $step < $total ? $step : $total;
         $service->events->insert('primary', $event);
     }
     if ($total > 0) {
         foreach ($events as $event) {
             $service->events->delete('primary', $event->getId());
         }
         return false;
     }
     return $events;
 }
Beispiel #29
0
 /**
  * Creates a simple dummy event with a duration of 1 hour
  * @param string $calendar_id calendar ID
  * @param int $date_from_ts Unix TS, from date
  * @param string $name event name
  * @return error code
  */
 public function createDummyEvent($calendar_id, $date_from_ts, $name)
 {
     $init_res = $this->initService();
     if ($init_res != self::NO_ERRORS) {
         return array($init_res, null);
     }
     $date_to_ts = $date_from_ts + 3600;
     $location = 'Elsewhere';
     $event = new Google_Service_Calendar_Event();
     $event->setSummary($name);
     $event->setLocation($location);
     $start = new Google_Service_Calendar_EventDateTime();
     $start->setDateTime(date('c', $date_from_ts));
     $event->setStart($start);
     $end = new Google_Service_Calendar_EventDateTime();
     $end->setDateTime(date('c', $date_to_ts));
     $event->setEnd($end);
     try {
         $createdEvent = $this->service->events->insert($calendar_id, $event);
         return self::NO_ERRORS;
     } catch (Exception $e) {
         return self::EVENT_CREATION_ERROR;
     }
     return $createdEvent;
 }
Beispiel #30
-6
 public function updateGoogleCalendarEvent($action)
 {
     try {
         // catch google exceptions so the whole app doesn't crash if google has a problem syncing
         $admin = Yii::app()->settings;
         if ($admin->googleIntegration) {
             if (isset($this->syncGoogleCalendarId) && $this->syncGoogleCalendarId) {
                 //                    // Google Calendar Libraries
                 //                    $timezone = date_default_timezone_get();
                 //                    require_once "protected/extensions/google-api-php-client/src/Google_Client.php";
                 //                    require_once "protected/extensions/google-api-php-client/src/contrib/Google_Service_Calendar.php";
                 //                    date_default_timezone_set($timezone);
                 //
                 //                    $client = new Google_Client();
                 //                    $client->setClientId($admin->googleClientId);
                 //                    $client->setClientSecret($admin->googleClientSecret);
                 //                    //$client->setDeveloperKey($admin->googleAPIKey);
                 //                    $client->setAccessToken($this->syncGoogleCalendarAccessToken);
                 //                    $client->setUseObjects(true); // return objects instead of arrays
                 //                    $googleCalendar = new Google_Service_Calendar($client);
                 $auth = new GoogleAuthenticator();
                 $googleCalendar = $auth->getCalendarService();
                 // check if the access token needs to be refreshed
                 // note that the google library automatically refreshes the access token if we need a new one,
                 // we just need to check if this happend by calling a google api function that requires authorization,
                 // and, if the access token has changed, save this new access token
                 $testCal = $googleCalendar->calendars->get($this->syncGoogleCalendarId);
                 //                    if($this->syncGoogleCalendarAccessToken != $client->getAccessToken()){
                 //                        $this->syncGoogleCalendarAccessToken = $client->getAccessToken();
                 //                        $this->update(array('syncGoogleCalendarAccessToken'));
                 //                    }
                 $summary = $action->actionDescription;
                 if ($action->associationType == 'contacts' || $action->associationType == 'contact') {
                     $summary = $action->associationName . ' - ' . $action->actionDescription;
                 }
                 $event = $googleCalendar->events->get($this->syncGoogleCalendarId, $action->syncGoogleCalendarEventId);
                 if (is_array($event)) {
                     $event = new Google_Service_Calendar_Event($event);
                 }
                 $event->setSummary($summary);
                 if (empty($action->dueDate)) {
                     $action->dueDate = time();
                 }
                 if ($action->allDay) {
                     $start = new Google_Service_Calendar_EventDateTime();
                     $start->setDate(date('Y-m-d', $action->dueDate));
                     $event->setStart($start);
                     if (!$action->completeDate) {
                         $action->completeDate = $action->dueDate;
                     }
                     $end = new Google_Service_Calendar_EventDateTime();
                     $end->setDate(date('Y-m-d', $action->completeDate + 86400));
                     $event->setEnd($end);
                 } else {
                     $start = new Google_Service_Calendar_EventDateTime();
                     $start->setDateTime(date('c', $action->dueDate));
                     $event->setStart($start);
                     if (!$action->completeDate) {
                         $action->completeDate = $action->dueDate;
                     }
                     // if no end time specified, make event 1 hour long
                     $end = new Google_Service_Calendar_EventDateTime();
                     $end->setDateTime(date('c', $action->completeDate));
                     $event->setEnd($end);
                 }
                 if ($action->color && $action->color != '#3366CC') {
                     $colorTable = array(10 => 'Green', 11 => 'Red', 6 => 'Orange', 8 => 'Black');
                     if (($key = array_search($action->color, $colorTable)) != false) {
                         $event->setColorId($key);
                     }
                 }
                 $newEvent = $googleCalendar->events->update($this->syncGoogleCalendarId, $action->syncGoogleCalendarEventId, $event);
             }
         }
     } catch (Exception $e) {
     }
 }