function getFeeds($startdate, $enddate) { global $dayinseconds; $feeds = array(); $calendars = array('*****@*****.**', '*****@*****.**', 'communityhigh.net_cqt4f59nci2gvtftuqseal396o%40group.calendar.google.com', 'communityhigh.net_5d3b9b97gj76hqmk9ir4s2usm8%40group.calendar.google.com'); foreach ($calendars as $user) { /* @var $service Zend_Gdata_Calendar */ $service = new Zend_Gdata_Calendar(); /* @var $query Zend_Gdata_Calendar_EventQuery */ $query = $service->newEventQuery(); $query->setUser($user); $query->setOrderby('starttime'); $query->setSortOrder('ascending'); $query->setMaxResults(100000); //get days events: event: name, description $query->setStartMin(date(DATE_RFC3339, $startdate)); $query->setStartMax(date(DATE_RFC3339, $enddate + 6 * $dayinseconds)); try { $feeds[] = $service->getCalendarEventFeed($query); //foreach($eventFeed as $event) // var_dump($event->when); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getMessage(); } } return $feeds; }
/** * Pull the events from google * @param <object> $SyncState * @return <array> google Records */ public function getCalendar($SyncState) { $calendars = new Zend_Gdata_Calendar($this->apiInstance); $query = $calendars->newEventQuery($query); $query->setVisibility('private'); $query->setMaxResults($this->maxResults); $query->setStartIndex(1); $query->setOrderBy('lastmodified'); $query->setsortorder('ascending'); if (Google_Utils_Helper::getSyncTime('Calendar')) { $query->setUpdatedMin(Google_Utils_Helper::getSyncTime('Calendar')); } $feed = $calendars->getCalendarEventFeed($query); $this->totalRecords = $feed->totalResults->text; $calendarRecords = array(); if (count($feed->entry) > 0) { $maxModifiedTime = date('Y-m-d H:i:s', strtotime(Google_Contacts_Model::vtigerFormat(end($feed->entry)->updated->text)) + 1); if ($this->totalRecords > $this->maxResults) { if (!Google_Utils_Helper::getSyncTime('Calendar')) { $query->setUpdatedMin(date('Y-m-d H:i:s', strtotime(Google_Contacts_Model::vtigerFormat(end($feed->entry)->updated->text)))); $query->setStartIndex($this->maxResults); } $query->setMaxResults(500); $query->setUpdatedMax($maxModifiedTime); $extendedFeed = $calendars->getCalendarEventFeed($query); $calendarRecords = array_merge($feed->entry, $extendedFeed->entry); } else { $calendarRecords = $feed->entry; } } $googleRecords = array(); foreach ($calendarRecords as $i => $calendar) { $recordModel = Google_Calendar_Model::getInstanceFromValues(array('entity' => $calendar)); $deleted = false; if (end(explode('.', $calendar->eventstatus->value)) == 'canceled') { $deleted = true; } if (!$deleted) { $recordModel->setType($this->getSynchronizeController()->getSourceType())->setMode(WSAPP_SyncRecordModel::WSAPP_UPDATE_MODE); } else { $recordModel->setType($this->getSynchronizeController()->getSourceType())->setMode(WSAPP_SyncRecordModel::WSAPP_DELETE_MODE); } $googleRecords[$calendar->id->text] = $recordModel; } $this->createdRecords = count($googleRecords); if (isset($maxModifiedTime)) { Google_Utils_Helper::updateSyncTime('Calendar', $maxModifiedTime); } else { Google_Utils_Helper::updateSyncTime('Calendar'); } return $googleRecords; }
// various copy includes require_once "../../config.gen.inc.php"; require_once "data/data.inc.php"; // records stats require_once "../page_builder/page_header.php"; // sets up google calendar classes require_once "lib/google_calendar.init.php"; // libs require_once "lib/calendar.lib.php"; require_once "lib/textformat.lib.php"; $search_terms = $_REQUEST['filter']; $search_options = SearchOptions::get_options(); $timeframe = isset($_REQUEST['timeframe']) ? $_REQUEST['timeframe'] : 0; $dates = SearchOptions::search_dates($timeframe); $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // predefined service name for calendar $client = Zend_Gdata_ClientLogin::getHttpClient($username . '@gmail.com', $password, $service); $gdataCal = new Zend_Gdata_Calendar($client); $query = $gdataCal->newEventQuery(); $query->setUser($calendars['all']['user']); $query->setVisibility('private'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setSortorder('a'); $query->setStartMin($dates['start']); $query->setStartMax($dates['end']); $query->setmaxresults('50'); $query->setQuery($search_terms); $eventFeed = $gdataCal->getCalendarEventFeed($query); require "templates/{$prefix}/search.html"; $page->output();
/** * Get the user notes from Google calendar (Gdata Zend functions are necessary) */ public function gCalendar() { // Security check $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWagendas::', '::', ACCESS_READ)); // get user uid $user = (UserUtil::getVar('uid') == '') ? '-1' : UserUtil::getVar('uid'); $usability = ModUtil::func('IWagendas', 'user', 'getGdataFunctionsUsability'); if ($usability !== true) { throw new Zikula_Exception_Forbidden(); } //Load required classes 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_HttpClient'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); //@var string Location of AuthSub key file. include_path is used to find this $_authSubKeyFile = null; // Example value for secure use: 'mykey.pem' //@var string Passphrase for AuthSub key file. $_authSubKeyFilePassphrase = null; $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $userSettings = ModUtil::func('IWagendas', 'user', 'getUserGCalendarSettings'); if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) { try { $client = Zend_Gdata_ClientLogin::getHttpClient($userSettings['gUserName'], base64_decode($userSettings['gUserPass']), $service); } catch (exception $e) { $authSubUrl = ModUtil::func('IWagendas', 'user', 'getAuthSubUrl'); return System::redirect(ModUtil::url('IWwebbox', 'user', 'main', array('url' => str_replace('&', '*', str_replace('?', '**', $authSubUrl))))); } } else $client = ModUtil::func('IWagendas', 'user', 'getAuthSubHttpClient'); try { $gdataCal = new Zend_Gdata_Calendar($client); } catch (exception $e) { LogUtil::registerError($this->__('Connection with Google failed. Imposible to synchronize the agenda')); return false; } //get user calendars try { $calFeed = $gdataCal->getCalendarListFeed(); } catch (exception $e) { LogUtil::registerError($this->__('Connection with Google failed. Imposible to synchronize the agenda')); return false; } $gCalendarsIdsArray = array(); foreach ($calFeed as $calendar) { $gCalendarsIdsArray[] = $calendar->id; } // Get all existing google calendars stored in database. We need them to know if the received google calendars exists or not $gAgendas = ModUtil::apiFunc('IWagendas', 'user', 'getAllAgendas', array('gAgendas' => 1, 'gCalendarsIdsArray' => $gCalendarsIdsArray)); $gCalendarsIdsArray = array(); foreach ($gAgendas as $g) { $gIds[$g['gCalendarId']] = $g; } $existingCalendar = array(); // Create or edit the calendars if it were necessary foreach ($calFeed as $calendar) { //sincronize calendars $id = $calendar->id; $resp = '$' . $user . '$'; $accessLevel = '$' . substr($calendar->accessLevel->value, 0, 4) . '|' . $user . '$'; $color = '$' . $calendar->color->value . '|' . $user . '$'; // Create a calendar array based on the calendar id $existingCalendar["$id"] = 1; if (!array_key_exists("$id", $gIds)) { $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue'); $agenda = ModUtil::apiFunc('IWagendas', 'admin', 'create', array('nom_agenda' => $calendar->title, 'descriu' => $calendar->summary->text, 'c1' => $this->__('What'), 'c2' => $this->__('End'), 'c3' => $this->__('Where'), 'c4' => $this->__('Content'), 'c5' => $this->__('Author'), 'tc1' => 1, 'tc2' => 1, 'tc3' => 1, 'tc4' => 2, 'tc5' => 1, 'activa' => 1, 'adjunts' => 0, 'protegida' => 1, 'gColor' => '$' . $color, 'color' => '', 'gCalendarId' => $id, 'gAccessLevel' => '$' . $accessLevel, 'resp' => '$' . $resp, 'sv' => $sv)); // add new agenda into the array in case the agenda is created recently $gIds["$id"] = $agenda; } else { if ($gIds["$id"]['nom_agenda'] != $calendar->title || $gIds["$id"]['descriu'] != $calendar->summary->text || strpos($gIds["$id"]['gColor'], $color) === false || strpos($gIds["$id"]['resp'], $resp) === false || strpos($gIds["$id"]['gAccessLevel'], $accessLevel) === false) { if (strpos($gIds["$id"]['gAccessLeve l'], $accessLevel) === false) { // Change the gCalendar access level $pos = strpos($gIds["$id"]['gAccessLevel'], '|' . $user . '$'); $userAccessLevel = ($pos > 0) ? substr($gIds["$id"]['gAccessLevel'], $pos - 5, (int) strlen($user) + 7) : ''; $newAccessLevelString = ($pos > 0) ? str_replace($userAccessLevel, $accessLevel, $gIds["$id"]['gAccessLevel']) : $gIds["$id"]['gAccessLevel'] . $accessLevel; } if (strpos($gIds["$id"]['gColor'], $color) === false) { // Change the gCalendar access level $pos = strpos($gIds["$id"]['gColor'], '|' . $user . '$'); $userColor = ($pos > 0) ? substr($gIds["$id"]['gColor'], $pos - 8, (int) strlen($user) + 10) : ''; $newColorString = ($pos > 0) ? str_replace($userColor, $color, $gIds["$id"]['gColor']) : $gIds["$id"]['gColor'] . $color; } $resp = (strpos($gIds["$id"]['resp'], $resp) === false) ? $resp : ''; $items = array('nom_agenda' => $calendar->title, 'descriu' => $calendar->summary->text, 'gColor' => $newColorString, 'resp' => $gIds["$id"]['resp'] . $resp, 'gAccessLevel' => $newAccessLevelString); $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue'); ModUtil::apiFunc('IWagendas', 'admin', 'editAgenda', array('daid' => $gIds["$id"]['daid'], 'items' => $items, 'sv' => $sv)); } } } // Get data from google for 2 months ago and 4 future months more or less $time = time(); $beginDate = $time - 2 * 30 * 24 * 60 * 60; $endDate = $time + 4 * 30 * 24 * 60 * 60; $beginOndate = date('Y-m-d', $beginDate); $endOnDate = date('Y-m-d', $endDate); //get all the google notes $gCalendarNotes = ModUtil::apiFunc('IWagendas', 'user', 'getAllGCalendarNotes', array('beginDate' => $beginDate, 'endDate' => $endDate, 'gIds' => $gIds)); foreach ($calFeed as $calendar) { $id = $calendar->id; $query = $gdataCal->newEventQuery(); $calFeed = $gdataCal->getCalendarListFeed(); $gUser = str_replace(Zend_Gdata_Calendar::CALENDAR_FEED_URI . '/default/', "", $id); // kind of dirty way to get the info, nut it lokks working :) $query->setUser($gUser); $query->setVisibility('private'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setStartMin($beginOndate); $query->setStartMax($endOnDate); $eventFeed = array(); if ($calendar->accessLevel->value == 'owner' || $calendar->accessLevel->value == 'editor' || $calendar->accessLevel->value == 'read') { $eventFeed = $gdataCal->getCalendarEventFeed($query); } foreach ($eventFeed as $event) { foreach ($event->when as $when) { $startTime = $when->startTime; $day = substr($startTime, 8, 2); $month = substr($startTime, 5, 2); $year = substr($startTime, 0, 4); $hour = substr($startTime, 11, 2); $minute = substr($startTime, 14, 2); $startTime = gmmktime($hour, $minute, 0, $month, $day, $year); $day = date('d', $startTime); $month = date('m', $startTime); $year = date('Y', $startTime); $hour = date('H', $startTime); $minute = date('i', $startTime); $endTime = $when->endTime; $dayEnd = substr($endTime, 8, 2); $monthEnd = substr($endTime, 5, 2); $yearEnd = substr($endTime, 0, 4); $hourEnd = substr($endTime, 11, 2); $minuteEnd = substr($endTime, 14, 2); $endTime = gmmktime($hourEnd, $minuteEnd, 0, $monthEnd, $dayEnd, $yearEnd); $dayEnd = date('d', $endTime); $monthEnd = date('m', $endTime); $yearEnd = date('Y', $endTime); $hourEnd = date('H', $endTime); $minuteEnd = date('i', $endTime); $allDay = (($minute == '' || $minute == '00') && ($hour == '' || $hour == '23') && ($minuteEnd == '' || $minuteEnd == '00') && ($hourEnd == '' || $hourEnd == '00')) ? 1 : 0; $end = ($allDay == 0) ? $this->__('Foreseen time to finish') . ': ' . $hourEnd . ':' . $minuteEnd : $this->__('All day'); if (!array_key_exists("$event->id", $gCalendarNotes)) { //create item $lid = ModUtil::apiFunc('IWagendas', 'user', 'crear', array('dia' => $day, 'mes' => $month, 'any' => $year, 'c1' => $event->title, 'c2' => $end, 'c3' => $event->where[0]->valueString, 'c4' => $event->content, 'c5' => $event->author[0]->email->text, 'c6' => '', 'minut' => $minute, 'hora' => $hour, 'totdia' => $allDay, 'tasca' => 0, 'nivell' => 0, 'rid' => '-1', 'daid' => $gIds["$id"]['daid'], 'nova' => '$$' . $user . '$', 'oculta' => 0, 'fitxer' => '', 'origen' => '', 'gCalendarEventId' => $event->id, 'protegida' => 0)); } else { $existing["$event->id"] = 1; $item = $gCalendarNotes["$event->id"]; if ($allDay) { $hour = 23; $minute = 59; } $data = mktime($hour, $minute, 0, $month, $day, $year); //check if item has changed. If it has changed it is updated if ($item['c1'] != $event->title || $item['data'] != $data || $item['c2'] != $end || $item['c3'] != $event->where[0]->valueString || $item['c4'] != $event->content) { $items = array('c1' => $event->title, 'c2' => $end, 'c3' => $event->where[0]->valueString, 'c4' => $event->content, 'data' => $data, 'totdia' => $allDay, 'origen' => $calendar->title, 'totdia' => $allDay); //modify of a simple entry $lid = ModUtil::apiFunc('IWagendas', 'user', 'editNote', array('aid' => $item['aid'], 'items' => $items, 'daid' => $item['daid'])); } //delete event from gCalendar if it were necessary if ($item['deleted'] == 1) { //delete of a simple entry try { $event->delete(); } catch (Zend_Gdata_App_Exception $e) { return $this->__('You are not allowed to administrate the agendas'); } } } } } } // Delete the calendars where user can't access any more $diff = array_diff_key($gIds, $existingCalendar); foreach ($diff as $d) { if ($resp == '$') { // Nobody else needs the calendar and it is deleted $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue'); ModUtil::apiFunc('IWagendas', 'admin', 'delete', array('daid' => $d['daid'], 'sv' => $sv)); } else { // The user access to the calendar is deleted $items = array('gColor' => $newColorString, 'resp' => $resp, 'gAccessLevel' => $newAccessLevelString); $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue'); ModUtil::apiFunc('IWagendas', 'admin', 'editAgenda', array('daid' => $d['daid'], 'items' => $items, 'sv' => $sv)); } } // set as deleted the not existing gCalendar notes $diff = array_diff_key($gCalendarNotes, $existing); foreach ($diff as $d) { if (strpos($gAgendas[$d['daid']]['gAccessLevel'], '$free|' . $user . '$') === false) { $items = array('deleted' => 1, 'protegida' => 0); $lid = ModUtil::apiFunc('IWagendas', 'user', 'editNote', array('aid' => $d['aid'], 'daid' => $d['daid'], 'items' => $items)); } } //save that the sincronization has been made $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue'); ModUtil::func('IWmain', 'user', 'userSetVar', array('uid' => $user, 'name' => 'sincroGCalendar', 'module' => 'IWagendas', 'sv' => $sv, 'value' => '1', 'lifetime' => $userSettings['gRefreshTime'] * 60)); //get all notes from gCalendar that has been created without connexion and create them $notesNotInGCalendar = ModUtil::apiFunc('IWagendas', 'user', 'getAllGCalendarNotes', array('beginDate' => $beginDate, 'endDate' => $endDate, 'gIds' => $gIds, 'notInGCalendar' => 1)); foreach ($notesNotInGCalendar as $note) { $data = $note['data']; $data1 = $note['data1']; //Protect correct format for dateStart and dataEnd if ($data1 < $data) $data1 = $data; // Create a new entry using the calendar service's magic factory method $event = $gdataCal->newEventEntry(); // Populate the event with the desired information // Note that each attribute is crated as an instance of a matching class $event->title = $gdataCal->newTitle($note['c1']); $event->where = array($gdataCal->newWhere($note['c3'])); $event->content = $gdataCal->newContent($note['c4']); // Set the date using RFC 3339 format. $startDate = date('Y-m-d', $data); $endDate = date('Y-m-d', $data1); $when = $gdataCal->newWhen(); if ($note['totdia'] == 0) { $tzOffset = ($userSettings['tzOffset'] == '') ? '+02' : $userSettings['tzOffset']; //protect correct time format $startTime = date('H:i', $data); $endTime = date('H:i', $data1); $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00"; $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00"; } else { $when->startTime = "$startDate"; $when->endTime = "$endDate"; } $event->when = array($when); $calendarURL = str_replace(Zend_Gdata_Calendar::CALENDAR_FEED_URI . '/default/', "", $gAgendas[$note['daid']]['gCalendarId']); $calendarURL = 'http://www.google.com/calendar/feeds/' . $calendarURL . '/private/full'; // Upload the event to the calendar server // A copy of the event as it is recorded on the server is returned try { $newEvent = $gdataCal->insertEvent($event, $calendarURL); } catch (Zend_Gdata_App_Exception $e) { return $this->__('Error produced during gCalendar\'s event creation'); } $gCalendarEventId = $newEvent->id; // Edit note gCalendarEventId $items = array('gCalendarEventId' => $gCalendarEventId); //modify of a simple entry $lid = ModUtil::apiFunc('IWagendas', 'user', 'editNote', array('aid' => $note['aid'], 'items' => $items, 'daid' => $note['daid'])); } return true; }
/** * Returns an entry object representing the event with the specified ID. * * @param Zend_Http_Client $client The authenticated client object * @param string $eventId The event ID string * @return Zend_Gdata_Calendar_EventEntry|null if the event is found, null if it's not */ function getEvent(Zend_Http_Client $client, $eventId) { $gdataCal = new Zend_Gdata_Calendar($client); $query = $gdataCal->newEventQuery(); $query->setUser('default'); $query->setVisibility('private'); $query->setProjection('full'); $query->setEvent($eventId); try { $eventEntry = $gdataCal->getCalendarEventEntry($query); return $eventEntry; } catch (Zend_Gdata_App_Exception $e) { return null; } }
/** * List events matching a full text query. Full text query searches * both title and event description for matches * * @param String $client - Access token * @param String $eventQuery - Query in string form * @return list of matching events in array form */ function calFullTextQuery($client, $eventQuery) { $gdataCal = new Zend_Gdata_Calendar($client); $query = $gdataCal->newEventQuery(); $query->setUser('default'); $query->setVisibility('private'); $query->setProjection('full'); $query->setQuery($eventQuery); $eventFeed = $gdataCal->getCalendarEventFeed($query); return $eventFeed; }
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"); } } }
/** * Do the plugin action * * @param array &$data selected data * @param object &$listModel list model * * @return number of records updated */ public function process(&$data, &$listModel) { $params = $this->getParams(); $gcal_url = $params->get('gcal_sync_gcal_url'); $matches = array(); /* This matches a standard GCal URL, found under the Google "Calender Details" tab, using the XML button. * It should match any form, for public or private ... * http://www.google.com/calendar/feeds/hugh.messenger%40gmail.com/public/basic * http://www.google.com/calendar/feeds/hugh.messenger%40gmail.com/private-3081eca2b0asdfasdf8f106ea6f63343056/basic */ if (preg_match('#feeds/(.*?)/(\\w+-\\w+|\\w+)/(\\w+)#', $gcal_url, $matches)) { // Grab the bits of the URL we need for the Zend framework call $gcal_user = $matches[1]; $gcal_visibility = $matches[2]; $gcal_projection = $matches[3]; $gcal_email = urldecode($gcal_user); // Grab the table model and find table name and PK $table = $listModel->getTable(); $table_name = $table->db_table_name; /* For now, we have to read the table ourselves. We can't rely on the $data passed to us * because it can be filtered, and we need to see all records to know if the GCal events * already exist in the table */ $mydata = array(); $db = FabrikWorker::getDbo(); $query = $db->getQuery(true); $query->select('*')->from($table_name); $db->setQuery($query); $mydata[0] = $db->loadObjectList(); // Grab all the field names to use $gcal_label_element_long = $params->get('gcal_sync_label_element'); $gcal_label_element = FabrikString::shortColName($gcal_label_element_long); $gcal_desc_element_long = $params->get('gcal_sync_desc_element'); $gcal_desc_element = FabrikString::shortColName($gcal_desc_element_long); $gcal_start_date_element_long = $params->get('gcal_sync_startdate_element'); $gcal_start_date_element = FabrikString::shortColName($gcal_start_date_element_long); $gcal_end_date_element_long = $params->get('gcal_sync_enddate_element'); $gcal_end_date_element = FabrikString::shortColName($gcal_end_date_element_long); $gcal_id_element_long = $params->get('gcal_sync_id_element'); $gcal_id_element = FabrikString::shortColName($gcal_id_element_long); $gcal_userid_element_long = $params->get('gcal_sync_userid_element'); $gcal_userid_element = FabrikString::shortColName($gcal_userid_element_long); // Sanity check, make sure required elements have been specified if (empty($gcal_label_element_long) || empty($gcal_start_date_element_long) || empty($gcal_end_date_element_long) || empty($gcal_id_element_long)) { return; } // If they selected a User ID element to use, see if we can find a J! user with matching email to this feed's owner $our_userid = 0; if ($gcal_userid_element_long) { $query = $db->getQuery(true); $query->select('id')->from('#__users')->whre('email = ' . $db->quote('$gcal_email')); $db->setQuery($query); $our_userid = $db->loadResult(); // Better make sure it's not NULL, in case underlying column is NOT NULL if (empty($our_userid)) { $our_userid = 0; } } // Include the Zend stuff $path = JPATH_SITE . '/libraries'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); $path = get_include_path(); require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); /* Won't need these loaded until we add sync'ing events back to Google * Zend_Loader::loadClass('Zend_Gdata_AuthSub'); * Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); */ Zend_Loader::loadClass('Zend_Gdata_Calendar'); // See if they want to sync to gcal, and provided a login $gcal_sync_upload = $params->get('gcal_sync_upload_events', 'from'); if ($gcal_sync_upload == 'both' || $gcal_sync_upload == 'to') { Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); $email = $params->get('gcal_sync_login', ''); $passwd = $params->get('gcal_sync_passwd', ''); try { $client = Zend_Gdata_ClientLogin::getHttpClient($email, $passwd, 'cl'); } catch (Zend_Gdata_App_CaptchaRequiredException $cre) { echo 'URL of CAPTCHA image: ' . $cre->getCaptchaUrl() . "\n"; echo 'Token ID: ' . $cre->getCaptchaToken() . "\n"; return; } catch (Zend_Gdata_App_AuthException $ae) { echo 'Problem authenticating: ' . $ae->exception() . "\n"; return; } $gdataCal = new Zend_Gdata_Calendar($client); } else { $gdataCal = new Zend_Gdata_Calendar(); } // Set up and execute the call to grab the feed from google $query = $gdataCal->newEventQuery(); $query->setUser($gcal_user); $query->setVisibility($gcal_visibility); $query->setProjection($gcal_projection); $eventFeed = $gdataCal->getCalendarEventFeed($query); // Build an array of the events from the feed, indexed by the Google ID $event_ids = array(); foreach ($eventFeed as $key => $event) { $short_id = $this->_getGcalShortId($event->id->text); $gcal_event_ids[$short_id] = $eventFeed[$key]; } /* Run through our table data, and build an array of our events indexed by the Google ID * (of course not all events may have a Google ID) */ $our_event_ids = array(); $our_upload_ids = array(); foreach ($mydata as $gkey => $group) { if (is_array($group)) { foreach ($group as $rkey => $row) { if ($row->{$gcal_id_element}) { $our_event_ids[$row->{$gcal_id_element}] = $mydata[$gkey][$rkey]; } else { $our_upload_ids[] = $mydata[$gkey][$rkey]; } } } } // Now go through the google events id's, and process the ones which aren't in our table. $our_event_adds = array(); foreach ($gcal_event_ids as $id => $event) { if (!array_key_exists($id, $our_event_ids)) { // we don't have the ID, so add the event to our table $row = array(); $row[$gcal_start_date_element] = strftime('%Y-%m-%d %H:%M:%S', strtotime($event->when[0]->startTime)); $row[$gcal_end_date_element] = strftime('%Y-%m-%d %H:%M:%S', strtotime($event->when[0]->endTime)); $row[$gcal_label_element] = $event->title->text; $row[$gcal_desc_element] = $event->content->text; $row[$gcal_id_element] = $id; if ($gcal_userid_element_long) { $row[$gcal_userid_element] = $our_userid; } $listModel->storeRow($row, 0); } } // If upload syncing (from us to gcal) is enabled ... if ($gcal_sync_upload == 'both' || $gcal_sync_upload == 'to') { // Grab the tzOffset. Note that gcal want +/-XX (like -06) // but J! gives us +/-X (like -6) so we sprintf it to the right format $config = JFactory::getConfig(); $tzOffset = (int) $config->getValue('config.offset'); $tzOffset = sprintf('%+03d', $tzOffset); // Loop thru the array we built earlier of events we have that aren't in gcal foreach ($our_upload_ids as $id => $event) { // Skip if a userid element is specified, and doesn't match the owner of this gcal if ($gcal_userid_element_long) { if ($event->{$gcal_userid_element} != $our_userid) { continue; } } // Now start building the gcal event structure $newEvent = $gdataCal->newEventEntry(); $newEvent->title = $gdataCal->newTitle($event->{$gcal_label_element}); if ($gcal_desc_element_long) { $newEvent->content = $gdataCal->newContent($event->{$gcal_desc_element}); } else { $newEvent->content = $gdataCal->newContent($event->{$gcal_label_element}); } $when = $gdataCal->newWhen(); // Grab the start date, apply the tx offset, and format it for gcal $start_date = JFactory::getDate($event->{$gcal_start_date_element}); $start_date->setOffset($tzOffset); $start_fdate = $start_date->toFormat('%Y-%m-%d %H:%M:%S'); $date_array = explode(' ', $start_fdate); $when->startTime = "{$date_array[0]}T{$date_array[1]}.000{$tzOffset}:00"; /* We have to provide an end date for gcal, so if we don't have one, * default it to start date + 1 hour */ if ($event->{$gcal_end_date_element} == '0000-00-00 00:00:00') { $startstamp = strtotime($event->{$gcal_start_date_element}); $endstamp = $startstamp + 60 * 60; $event->{$gcal_end_date_element} = strftime('%Y-%m-%d %H:%M:%S', $endstamp); } // Grab the end date, apply the tx offset, and format it for gcal $end_date = JFactory::getDate($event->{$gcal_end_date_element}); $end_date->setOffset($tzOffset); $end_fdate = $end_date->toFormat('%Y-%m-%d %H:%M:%S'); $date_array = explode(' ', $end_fdate); $when->endTime = "{$date_array[0]}T{$date_array[1]}.000{$tzOffset}:00"; $newEvent->when = array($when); // Fire off the insertEvent to gcal, catch any errors try { $retEvent = $gdataCal->insertEvent($newEvent); } catch (Zend_Gdata_App_HttpException $he) { $errStr = 'Problem adding event: ' . $he->getRawResponseBody() . "\n"; continue; } /* So, insertEvent worked, grab the gcal ID from the returned event data, * and update our event record with the short version of the ID */ $gcal_id = $this->_getGcalShortId($retEvent->id->text); $our_id = $event->id; $query = $db->getQuery(true); $query->update($table_name)->set($gcal_id_element . ' = ' . $db->quote($gcal_id))->where('id = ' . $db->quote($our_id)); $db->setQuery($query); $db->query(); } } } }
function getEventByUrl($eventEditUrl) { $gdataCal = new Zend_Gdata_Calendar($client); $query = $gdataCal->newEventQuery(); $query->setUser('default'); $query->setVisibility('private'); $query->setProjection('full'); $query->setEvent($eventId); try { $eventEntry = $gdataCal->getCalendarEventEntry($query); return $eventEntry; } catch (Zend_Gdata_App_Exception $e) { var_dump($e); return false; } }
//echo $uriRedirect; $uriCalendar = 'http://www.google.com/calendar/feeds/'; $hostedDomain = 'nexchie.com'; $uriGoogleAuth = Zend_Gdata_AuthSub::getAuthSubTokenUri($uriRedirect, $uriCalendar, 0, 1); header("Location: " . $uriGoogleAuth . "&hd=nexchie.com"); //echo $uriGoogleAuth; echo "<h1>Googleカレンダータイムシート</h1>"; echo "<a href='{$uriGoogleAuth}'>ログイン</a>"; } } if (isset($_SESSION['cal_token'])) { // 認証済みHTTPクライアント作成 $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['cal_token']); // Calendarサービスのインスタンス作成 $service = new Zend_Gdata_Calendar($client); $query = $service->newEventQuery(); $query->setUser('default'); // MagicCookie 認証の場合は // $query->setVisibility('private-magicCookieValue') とします $query->setVisibility('private'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setFutureevents('false'); $query->setStartMin($_GET[s]); $query->setStartMax($_GET[e]); //$query->setStartMin('2009-05-01'); //$query->setStartMax('2009-06-01'); $query->setmaxResults(999); // カレンダーサーバからイベントの一覧を取得します try { $eventFeed = $service->getCalendarEventFeed($query);
function loadEventsFromFeed() { // Create the Calendar client $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; try { $client = Zend_Gdata_ClientLogin::getHttpClient($this->user, $this->password, $service); } catch (Exception $ex) { $this->log("Error: Caught this creating a Gdata client (pi.googlecal_events) : " . $ex->getMessage()); return; } $calendar = new Zend_Gdata_Calendar($client); $query = $calendar->newEventQuery(); $query->setVisibility('private'); $query->setProjection('composite'); $query->setStartMin($this->calendar_start_date); $query->setStartMax($this->calendar_end_date); $this->events = array(); foreach ($this->google_calendars as $google_calendar) { $query->setUser($google_calendar); try { $eventFeed = $calendar->getCalendarEventFeed($query); } catch (Exception $ex) { $this->log("Error: Caught this retrieving the Google Calendar feed (pi.googlecal_events) : " . $ex->getMessage()); return; } $newEvents = $this->parseEventFeed($eventFeed); $this->events = array_merge($this->events, $newEvents); } // Sort the list of events usort($this->events, "eventCmp"); }
/** * @return Zend_Gdata_App_Entry|NULL */ public static function internalGetEvent($calendar, $eventId) { try { $client = new Zend_Http_Client(); if (!empty($calendar->username) && !empty($calendar->password)) { $client = Zend_Gdata_ClientLogin::getHttpClient($calendar->username, $calendar->password, Zend_Gdata_Calendar::AUTH_SERVICE_NAME); } $service = new Zend_Gdata_Calendar($client); $query = $service->newEventQuery(); $query->setUser($calendar->calendar_id); if ($calendar->magic_cookie != null) { $query->setVisibility('private-' . $calendar->magic_cookie); } $query->setProjection('full'); $query->setEvent($eventId); $query->setParam('ctz', 'Etc/GMT'); $query->setParam('hl', GCalendarUtil::getFrLanguage()); $event = $service->getEntry($query, 'GCalendar_Entry'); $event->setParam('gcid', $calendar->id); $event->setParam('gccolor', $calendar->color); $event->setParam('gcname', $calendar->name); return $event; } catch (Zend_Gdata_App_Exception $e) { JError::raiseWarning(200, $e->getMessage()); return null; } }
/** * Iterate through all the Google Calendars and create a JSON encoded array of events. * * @return array of events in JSON format */ function outputCalendarByDateRange($client, $startDate, $endDate, $idsofcal, $gcalobj) { $gdataCal = new Zend_Gdata_Calendar($client); $rows = array(); $idsofcal = explode(',', $idsofcal); $calFeed = $gdataCal->getCalendarListFeed(); foreach ($idsofcal as $idofcal) { if ($idofcal != '') { $query = $gdataCal->newEventQuery(); $query->setUser(substr($idofcal, strrpos($idofcal, "/") + 1)); $query->setVisibility('private'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setStartMin($startDate); $query->setStartMax($endDate); $eventFeed = $gdataCal->getCalendarEventFeed($query); $color = CALENDAR_DEF_COLOR; $accesslevl = true; foreach ($calFeed as $calendar) { if (strpos($idofcal, $calendar->id->text) !== false) { $color = $calendar->color->value; if ($calendar->accesslevel->value == 'read') { $accesslevl = false; } } } foreach ($eventFeed as $event) { foreach ($event->when as $when) { $startD = substr($when->startTime, 0, 19); $startD = str_replace('T', ' ', $startD); $endD = substr($when->endTime, 0, 19); $endD = str_replace('T', ' ', $endD); /* * If both start time and end time are different and their time parts differ then allDay is false */ if ($startD != $endD && substr($startD, 0, 10) == substr($endD, 0, 10)) { $allDay = "false"; } else { $allDay = "true"; } $row = array(); $row["title"] = $event->title->text; $row["id"] = $event->id->text; $row["editable"] = $accesslevl; $row["start"] = $startD; $row["end"] = $endD; $row["allDay"] = $allDay; $row["color"] = $color; $row["textColor"] = "white"; $row["calendar"] = "Google Calendar event"; array_push($rows, $row); } } } } //Encode in JSON format. $str = json_encode($rows); //Replace "true","false" with true,false for javascript. $str = str_replace('"true"', 'true', $str); $str = str_replace('"false"', 'false', $str); //Return the events in the JSON format. echo $str; }