/**
 * Outputs an HTML unordered list (ul), with each list item representing a
 * calendar in the authenticated user's calendar list.
 *
 * @param  Zend_Http_Client $client The authenticated client object
 * @return void
 */
function outputCalendarList($client)
{
    $gdataCal = new Zend_Gdata_Calendar($client);
    $calFeed = $gdataCal->getCalendarListFeed();
    echo "<h1>" . $calFeed->title->text . "</h1>\n";
    echo "<ul>\n";
    foreach ($calFeed as $calendar) {
        echo "\t<li>" . $calendar->title->text . "</li>\n";
    }
    echo "</ul>\n";
}
 /**
  * @param string $username
  * @param string $password
  *
  * @return Zend_Gdata_Calendar_ListFeed|NULL
  */
 public static function getCalendars($username, $password)
 {
     try {
         $client = Zend_Gdata_ClientLogin::getHttpClient($username, $password, Zend_Gdata_Calendar::AUTH_SERVICE_NAME);
         $gdataCal = new Zend_Gdata_Calendar($client);
         return $gdataCal->getCalendarListFeed();
     } catch (Exception $e) {
         JError::raiseWarning(200, $e->getMessage());
     }
     return null;
 }
Ejemplo n.º 3
0
    /**
     * 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;
    }
Ejemplo n.º 4
0
 /**
  * Display list of calendars in the sidemenu with 
  * checkbox ahead of each calendar's title.
  *
  * @param Zend client object
  *
  * @return void
  */
 public function outputCalendarList($client)
 {
     $gdataCal = new Zend_Gdata_Calendar($client);
     $calFeed = $gdataCal->getCalendarListFeed();
     //Get calendar list from database
     $query = "SELECT * FROM %scalendar_google_sync WHERE userid=%d";
     $rowval = queryDB($query, array(TABLE_PREFIX, $_SESSION['member_id']), TRUE);
     $prevval = $rowval['calids'];
     $selectd = '';
     $i = 1;
     //Iterate through each calendar id
     foreach ($calFeed as $calendar) {
         //set state according to database and if changed then update database
         if (strpos($prevval, $calendar->id->text . ',') === false) {
             $selectd = '';
         } else {
             $selectd = "checked='checked'";
         }
         echo "\t <div class='fc-square fc-inline-block'\n                    style='background-color:" . $calendar->color->value . "' ></div>\n                    <input id='gcal" . $i . "' type='checkbox' name ='calid' value='" . $calendar->id->text . "' " . $selectd . " onclick='if(this.checked) \$.get(\"mods/_standard/calendar/google_calendar_db_sync.php\",\n                    { calid: this.value, mode: \"add\" },function (data){ refreshevents(); } );\n                    else \$.get(\"mods/_standard/calendar/google_calendar_db_sync.php\",\n                    { calid: this.value, mode: \"remove\" },function (data){ refreshevents(); } );'\n                    />\n                    <label for='gcal" . $i . "'>" . $calendar->title->text . "</label><br/>";
         $i++;
     }
 }
 public function googleAction()
 {
     //$this->_helper->layout()->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
     $my_calendar = 'http://www.google.com/calendar/feeds/default/private/full';
     if (!isset($_SESSION['cal_token'])) {
         if (isset($_GET['token'])) {
             // You can convert the single-use token to a session token.
             $session_token = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
             // Store the session token in our session.
             $_SESSION['cal_token'] = $session_token;
         } else {
             // Display link to generate single-use token
             $googleUri = Zend_Gdata_AuthSub::getAuthSubTokenUri('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'], $my_calendar, 0, 1);
             echo "Click <a href='{$googleUri}'>here</a> " . "to authorize this application.";
             exit;
         }
     }
     // Create an authenticated HTTP Client to talk to Google.
     $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['cal_token']);
     // Create a Gdata object using the authenticated Http Client
     $cal = new Zend_Gdata_Calendar($client);
     var_export($cal->getCalendarListFeed()->count());
 }
Ejemplo n.º 6
0
 /**
  * Grabs a list of a users calendars
  *
  * @param String $client - Access token
  * @return calendars in array form
  */
 function outputCalendarList($client)
 {
     $gdataCal = new Zend_Gdata_Calendar($client);
     $calFeed = $gdataCal->getCalendarListFeed();
     return $calFeed;
 }
Ejemplo n.º 7
0
 /**
  * Method to get a calendar
  * @return object with data
  */
 function getOnlineData()
 {
     $this->loadZendClasses();
     $client = $this->getAuthSubHttpClient();
     if (!$client) {
         $this->_data = array();
     } else {
         $gdataCal = new Zend_Gdata_Calendar($client);
         $calFeed = $gdataCal->getCalendarListFeed();
         $tmp = array();
         JTable::addIncludePath(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_gcalendar' . DS . 'tables');
         foreach ($calFeed as $calendar) {
             $table_instance =& $this->getTable('import');
             $table_instance->id = 0;
             $cal_id = substr($calendar->id->text, strripos($calendar->id->text, '/') + 1);
             $table_instance->calendar_id = $cal_id;
             $table_instance->name = $calendar->title->text;
             if (strpos($calendar->color->value, '#') === 0) {
                 $color = str_replace("#", "", $calendar->color->value);
             }
             $table_instance->color = $color;
             $tmp[] = $table_instance;
         }
         $this->_data = $tmp;
     }
     return $this->_data;
 }
Ejemplo n.º 8
0
        function export_google_calendar() {
		ajx_current("empty");
                
                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');
                
                $users = ExternalCalendarUsers::findByContactId();
                if($users){
                    if($users->getSync() == 1){
                        $sql = "SELECT ec.* FROM `".TABLE_PREFIX."external_calendars` ec,`".TABLE_PREFIX."external_calendar_users` ecu 
                                WHERE ec.calendar_feng = 1 AND ecu.contact_id = ".logged_user()->getId();
                        $calendar_feng = DB::executeOne($sql);
                        $events = ProjectEvents::findNoSync();

                        $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);

                                if ($calendar_feng){
                                    foreach ($events as $event){
                                        $calendarUrl = 'http://www.google.com/calendar/feeds/'.$calendar_feng['calendar_user'].'/private/full';

                                        $newEvent = $gdataCal->newEventEntry();
                                        $newEvent->title = $gdataCal->newTitle($event->getObjectName());
                                        $newEvent->content = $gdataCal->newContent($event->getDescription());

                                        $star_time = explode(" ",$event->getStart()->format("Y-m-d H:i:s"));
                                        $end_time = explode(" ",$event->getDuration()->format("Y-m-d H:i:s"));

                                        if($event->getTypeId() == 2){
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0];
                                            $when->endTime = $end_time[0];
                                            $newEvent->when = array($when);
                                        }else{                                    
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0]."T".$star_time[1].".000-00:00";
                                            $when->endTime = $end_time[0]."T".$end_time[1].".000-00:00";
                                            $newEvent->when = array($when);
                                        }

                                        // insert event
                                        $createdEvent = $gdataCal->insertEvent($newEvent, $calendarUrl);

                                        $event_id = explode("/",$createdEvent->id->text);
                                        $special_id = end($event_id); 
                                        $event->setSpecialID($special_id);
                                        $event->setUpdateSync(ProjectEvents::date_google_to_sql($createdEvent->updated));
                                        $event->setExtCalId($calendar_feng['id']);
                                        $event->save();
                                    }                             
                                }else{
                                    $appCalUrl = '';
                                    $calFeed = $gdataCal->getCalendarListFeed();        
                                    foreach ($calFeed as $calF){
                                        $instalation = explode("/", ROOT_URL);
                                        $instalation_name = end($instalation);
                                        if($calF->title->text == lang('feng calendar',$instalation_name)){
                                            $appCalUrl = $calF->content->src;
                                            $t_calendario = $calF->title->text;
                                        }
                                    }    

                                    if($appCalUrl != ""){
                                        $title_cal = $t_calendario;
                                    }else{
                                        $instalation = explode("/", ROOT_URL);
                                        $instalation_name = end($instalation);
                                        $appCal = $gdataCal -> newListEntry();
                                        $appCal -> title = $gdataCal-> newTitle(lang('feng calendar',$instalation_name));                         
                                        $own_cal = "http://www.google.com/calendar/feeds/default/owncalendars/full";                        
                                        $new_cal = $gdataCal->insertEvent($appCal, $own_cal);

                                        $title_cal = $new_cal->title->text;
                                        $appCalUrl = $new_cal->content->src;                                
                                    }               

                                    $cal_src = explode("/",$appCalUrl);
                                    array_pop($cal_src);
                                    $calendar_visibility = end($cal_src);
                                    array_pop($cal_src);
                                    $calendar_user = end($cal_src);                            

                                    $calendar = new ExternalCalendar();
                                    $calendar->setCalendarUser($calendar_user);
                                    $calendar->setCalendarVisibility($calendar_visibility);
                                    $calendar->setCalendarName($title_cal);
                                    $calendar->setExtCalUserId($users->getId());
                                    $calendar->setCalendarFeng(1);
                                    $calendar->save();

                                    foreach ($events as $event){                               
                                        $calendarUrl = 'http://www.google.com/calendar/feeds/'.$calendar->getCalendarUser().'/private/full';

                                        $newEvent = $gdataCal->newEventEntry();

                                        $newEvent->title = $gdataCal->newTitle($event->getObjectName());
                                        $newEvent->content = $gdataCal->newContent($event->getDescription());

                                        $star_time = explode(" ",$event->getStart()->format("Y-m-d H:i:s"));
                                        $end_time = explode(" ",$event->getDuration()->format("Y-m-d H:i:s"));

                                        if($event->getTypeId() == 2){
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0];
                                            $when->endTime = $end_time[0];
                                            $newEvent->when = array($when);
                                        }else{                                    
                                            $when = $gdataCal->newWhen();
                                            $when->startTime = $star_time[0]."T".$star_time[1].".000-00:00";
                                            $when->endTime = $end_time[0]."T".$end_time[1].".000-00:00";
                                            $newEvent->when = array($when);
                                        }

                                        // insert event
                                        $createdEvent = $gdataCal->insertEvent($newEvent, $calendarUrl);

                                        $event_id = explode("/",$createdEvent->id->text);
                                        $special_id = end($event_id); 
                                        $event->setSpecialID($special_id);
                                        $event->setUpdateSync(ProjectEvents::date_google_to_sql($createdEvent->updated));
                                        $event->setExtCalId($calendar->getId());
                                        $event->save();
                                    } 
                                }
                                flash_success(lang('success add sync'));
                                ajx_current("reload");
                        }
                        catch(Exception $e)
                        {
                        		Logger::log($e->getMessage());
                                flash_error(lang('could not connect to calendar'));
                                ajx_current("empty");
                        }
                    }
                }
	}
Ejemplo n.º 9
0
             apologize("The club's categories could not be stored.");
         }
     }
 }
 // mark user as an administrator
 $rows = query("UPDATE users SET admin = ? WHERE id = ?", true, $_SESSION["id"]);
 $privacy = query("SELECT * FROM privacy WHERE description = 'admin'");
 // insert user into subscriptions database (as an admin for this club)
 $result = query("INSERT INTO subscriptions (userID, clubID, level) \n                VALUES(?, ?, ?)", $_SESSION["id"], $clubID, $privacy[0]["level"]);
 // if user subscription not added, notify user
 if ($result === false) {
     apologize("Your subscription to this club could not be added to the database.");
 }
 $gdataCal = new Zend_Gdata_Calendar($_SESSION["client"]);
 //Get list of existing calendars
 $calFeed = $gdataCal->getCalendarListFeed();
 $levels = query("SELECT * FROM privacy");
 $num = count($levels);
 for ($i = 1; $i <= $num; $i++) {
     // ensure that when POST  variables are extracted  during loops, the abbr is not incorrect
     $abbreviation = strtoupper($abbreviation);
     if (isset($_POST["abbreviation"]) && $abbreviation == "") {
         $abbreviation = strtoupper($_POST[name]);
     }
     // I actually had to guess this method based on Google API's "magic" factory
     $appCal = $gdataCal->newListEntry();
     // I only set the title, other options like color are available.
     $appCal->title = $gdataCal->newTitle($abbreviation . $i);
     //This is the right URL to post to for new calendars...
     //Notice that the user's info is nowhere in there
     $own_cal = "http://www.google.com/calendar/feeds/default/owncalendars/full";
Ejemplo n.º 10
0
/**
 * 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;
}