Google Calendar PHP - Event URL / ID? (Zend_Gdata) - php

I have modified my PHP web app to add events to a Google Calendar. Currently, it adds successfully.
However, now I wish to delete and edit events. This seems easy to do, except for the fact that I don't know what event URL is associated with each event.
Am I supposed to set this event URL (or ID?) upon adding an event? How am I supposed to figure out what it is?
I can't seem to find this information anywhere else...
Thanks!
EDIT:
I have been using the Zend Framework for this (Gdata package)...
EDIT:
$newIncludePath = array();
$newIncludePath[] = '../ZendGdata-1.8.4PL1/library';
$newIncludePath = implode($newIncludePath);
set_include_path($newIncludePath);
// load classes
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
Zend_Loader::loadClass('Zend_Http_Client');
// connect to service
$gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user = "********#gmail.com";
$pass = "*****";
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal);
$gcal = new Zend_Gdata_Calendar($client);
// construct event object
// save to server
try {
$event = $gcal->newEventEntry();
$event->title = $gcal->newTitle($title);
$event->content = $gcal->newContent($desc);
$when = $gcal->newWhen();
$when->startTime = $date;
$when->endTime = $date;
$event->when = array($when);
$gcal->insertEvent($event);
echo $event->getEditLink()->href;
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: Unable to add event to Google Calendar" . $e->getResponse();
}

This is plainly documented in the Zend_Gdata documentation:
http://framework.zend.com/manual/en/zend.gdata.calendar.html#zend.gdata.calendar.deleting_events
// Option 1: Events can be deleted directly
$event->delete();
or
// Option 2: Events can be deleted supplying the edit URL of the event
// to the calendar service, if known
$service->delete($event->getEditLink()->href);
It sounds like you need the latter.
Edit:
Get the edit link from your $event. It's shown in the code above:
$event->getEditLink()->href;
This will be available on a saved event. e.g.
$newEvent = $service->insertEvent($event);
echo $newEvent->getEditLink()->href;

You could have a look at Zend_Gdata and Zend_Gdata_Calendar : those would probably help for all the hard work -- and if you don't have to spend code to communicate with Google's API, it gives you more time to develop other things ;-)
And it seems it can be used outsid of the Zend FRamework : it's even available as a standalone download : http://framework.zend.com/download/gdata
(If you really want to do it yourself, you can still try to understand how Zend_Gdata does it ^^ )

Here's a GREAT resource to help you with this:
Integrate your PHP application with Google Calendar
Here's how I obtain the unique ID of the calendar event after publishing the event with newEventEntry. I store the $id value in the database, in case I have to edit it later with update or delete.
try {
$event = $gcal->newEventEntry();
$event->title = $gcal->newTitle($title);
$when = $gcal->newWhen();
$when->startTime = $start;
$when->endTime = $end;
$event->when = array($when);
$gcal->insertEvent($event);
$id = substr($event->id, strrpos($event->id, '/')+1); // trim off everything but the id
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getResponse();
}
// Do mysql Insert functions here to store the record in db (removed for clarity)
echo 'Event '. $id. 'successfully added!';
Then, when I need to access that particular event I can use it to target just that event for updating/deleting using a $_POST of the ID:
try {
$event = $gcal->getCalendarEventEntry('http://www.google.com/calendar/feeds/default/private/full/' . $_POST['id']);
$event->title = $gcal->newTitle($title);
$when = $gcal->newWhen();
$when->startTime = $start;
$when->endTime = $end;
$event->when = array($when);
$event->save();
} catch (Zend_Gdata_App_Exception $e) {
die("Error: " . $e->getResponse());
}
echo 'Event successfully modified!';
Hope this answers your question - I struggled with getting this working, but share my findings with you here, if it helps I'm happy to have assisted.
Scott

Well if you dont want to store event ids in local database, here another good way to deleting event if you have infomration about start time, end time and calendar id(specific calendar for which you want to delete event between start time and end time)
function deleteEvent($client,$startDate,$endDate,$startTime,$endTime,$tzOffset,$cal_id)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser($cal_id);
$query->setVisibility('private');
$query->setProjection('full');
$query->setOrderby('starttime');
$query->setStartMin("{$startDate}T{$startTime}:00.000{$tzOffset}");
$query->setStartMax("{$endDate}T{$endTime}:00.000{$tzOffset}");
$eventFeed = $gdataCal->getCalendarEventFeed($query);
foreach ($eventFeed as $event) {
$event->delete();
}
}
Hope it helps to somebody, like it did to me.

Related

craftcms 3 plugin which imports channel entries

I try to finish a plugin which imports data into my craftcms project. I already created a console based method/service, which I trigger/run in my shell. Inside my method(s) I receive data (XML or JSON) I parse my data and try to create and fill an entry of a specific channel I already created.
I tried "saveElement()" which doesn't work.
I found some tuts and informations for craftcms v2 (for example: https://docs.craftcms.com/api/v2/craft-entriesservice.html#public-methods)
Now i am stuck and i can not find any informations on how to solve this with craftcms v3.
Here is my last version of code after hours of different trys :(
$section = Craft::$app->sections->getSectionByHandle('testentry');
$entryTypes = $section->getEntryTypes();
$entryType = $entryTypes[0];
// Save Entry
//$entry = new EntryModel();
$entry = new \craft\elements\Entry();
$entry->sectionId = $section->id;
$entry->typeId = $entryType->id;
//$entry->locale = Craft::$app->i18n->getPrimarySiteLocaleId();
//$entry->authorId = 1; // TODO: Set author
$entry->enabled = true;
$entry->postDate = $post['post_date'];
$entry->slug = $post['post_name'];
// $entry->getContent()->title = $post['post_title'];
// $entry->setContentFromPost(array(
// 'body' => $postContent,
// 'categoryCareer' => NULL,
// ));
if (Craft::$app->elements->saveElement($entry)) {
$result = true;
}
else {
echo 'Could not save the Job entry.'."\n";
$result = false;
}

How to retrieve all lead fields from salesforce?

I am using salesforce Enterprise api to add leads in salesforce.
$SFDCUSERNAME = "myusername";
$SFDCPASSWORD = "mypassword!";
$SFDCSECURITY_TOKEN = "mytoken";
$SFDCCLIENT = "soapclient/SforceEnterpriseClient.php";
$SFDCWSDL = "soapclient/enterprise.wsdl.xml";
require_once($SFDCCLIENT);
try {
$mySforceConnection = new SforceEnterpriseClient();
$myConnection = $mySforceConnection->createConnection($SFDCWSDL);
$myLogin = $mySforceConnection->login($SFDCUSERNAME, $SFDCPASSWORD.$SFDCSECURITY_TOKEN);
}
catch(Exception $e) {
print_r($e);
}
I can create leads using api.
Now I want to retrieve all fields which are available to a lead in salesforce(not only the custom fields but also the default/in_built fields) and show it in a HTML drop down field.
Is it possible to retrieve all fields of a lead using salesforce api?
After a long search I got an answer and it worked for me. I am posting it here , hoping it may be helpful to someone some other time.
try {
$mySforceConnection = new SforceEnterpriseClient();
$myConnection = $mySforceConnection->createConnection($SFDCWSDL);
$myLogin = $mySforceConnection->login($SFDCUSERNAME, $SFDCPASSWORD.$SFDCSECURITY_TOKEN);
echo "<pre>";
print_r($mySforceConnection->describeSObject('Lead'));
echo "</pre><br>";
}
catch(Exception $e) {
print_r($e);
}
There is a function in salesforce api describeSObject() which outputs the complete details about the object including the field details.
REFERENCE

PHP script to pull from Facebook events from multiple pages

Bonjour everyone,
Currently, the script below is on my server as a PHP page (pull.php). It reads the events from a Facebook page using its ID, e.g: 12345678, and outputs them to a file, e.g: 1234568.ics.
What I'd like to ask this community for help with:
1) how would one modify the code below to read from many Facebook pages (an array where I would put in the page ID manually, e.g: 12345678, 24681357, 12348765) and output to many files 12345678.ics, 24682357.ics, 12348765.ics
2) I'm looking for these .ics files to be created and updated (crushed) right on my server, at the same location as where the script runs. The idea is that I'll run a CRON job that would run this script nightly. I then have a plugin on my Facebook page that updates events on the website based on the .ics feed.
CODE:
$access_token = MY_ACCESS_TOKEN;
$page = "12345678";
// We don't want to query the Facebook Graph API over and over, so we'll cache our results. You can force the cache to update by visiting the script and appending "?f=true", otherwise it will only run (rather than display the cache) if the cache is older than 3600 seconds (one hour).
$cache = $page . ".cache";
$f = false;
if($_GET['f'] == "true"){
$f = true;
}
if(!file_exists($cache) || filemtime($cache) <= time()-3600 || $f){
// Get and decode the data - your page's event list - from the API
$graph_url = "https://graph.facebook.com/" . $page . "/events?access_token=" . $access_token;
$data = file_get_contents($graph_url);
$data = json_decode($data);
if(!empty($data->error)){
echo '<b>$data error</b><br />';
echo $data->error->type . " error (" . $data->error->code . "/" . $data->error->error_subcode . "): " . $data->error->message;
exit;
}
// Go through the list of events, and get and decode more detailed information on each event.
foreach ($data->data as $event){
$event_data = file_get_contents("https://graph.facebook.com/" . $event->id . "?access_token=" . $access_token);
$event_data = json_decode($event_data);
if(!empty($event_data->error)){
echo '<b>$event_data error</b><br />';
echo $event_data->error->type . " error (" . $event_data->error->code . "/" . $event_data->error->error_subcode . "): " . $event_data->error->message;
exit;
}
// Store it in an array for later use.
$events[] = $event_data;
}
// We're now done fetching the data from Facebook's Graph API. Now we'll have to create an iCal file.
// This requires the iCalcreator PHP class, which you can downloead from kigkonsult at kigkonsult.se/iCalcreator/index.php
require_once("icalcreator/iCalcreator.class.php");
// Create the calendar, set up some basic properties
$c = new vcalendar(array('unique_id' => $page));
$c->setProperty('X-WR-CALNAME', $page . ' events');
$c->setProperty('X-WR-CALDESC', 'Facebook events for ' . $page);
$c->setProperty('X-WR-TIMEZONE', $events[0]->timezone); // We assume all of the events use the same timezone.
// Loop through the events, create event components in the calendar
foreach($events as $key => $event){
$e[$key] = & $c->newComponent('vevent');
$e[$key]->setProperty('summary', $event->name);
$e[$key]->setProperty('dtstart', $event->start_time);
$e[$key]->setProperty('dtend', $event->end_time);
if (!isset($event->end_time)) {
$e[$key]->setProperty('dtend', $event->start_time);
}
$e[$key]->setProperty('description', $event->description . "\n\nhttp://www.facebook.com/events/" . $event->id);
$e[$key]->setProperty('location', $event->location);
}
// Remove the cache if it exists
if(file_exists($cache)){
unlink($cache);
}
// Open (create) the cache file
if(!$handle = fopen($cache, 'w')){
echo "Cannot open output file: " . $cache;
exit;
}
// Write the calendar to the cache
if(fwrite($handle, $c->createCalendar()) === FALSE){
echo "Cannot write to output file: " . $cache;
exit;
}
// Close the cache file
fclose($handle);
}
// Now we've got the calendar in the cache file, either newly generated and stored there just a few lines ago or from earlier. Now we'll just display it.
header("Content-Type: text/calendar; charset=UTF-8");
header("Content-Disposition: filename=" . $page . ".ics");
require($cache);
?>
Might anyone have a clue how to do this?
Thanks in advance! Upvotes your way if you can help me out!
You can use a FQL query to get results for multiple pages at once, like this:
select eid, creator, name, description, start_time, end_time, timezone, location from event where creator in ({PAGE1_ID}, {PAGE2_ID}, ...) and start_time > now() order by creator asc
You can issue the (URL encoded) query via the
GET /fql?q=...
endpoint like this (replace Page IDs!):
http://graph.facebook.com/fql?q=select%20eid%2C%20creator%2C%20name%2C%20description%2C%20start_time%2C%20end_time%2C%20timezone%2C%20location%20from%20event%20where%20creator%20in%20(1234,5678)%20and%20start_time%20%3E%20now()%20order%20by%20creator%20asc
But then you have to restructure your code a little bit, because the result will look like the following:
{
"data": [
{
"eid": 2289962603,
"creator": 1146614804,
"name": "eventname",
"description": "descr",
"start_time": "2014-05-30T21:00:00+0200",
"end_time": null,
"timezone": "Europe/Berlin",
"location": "thelocation"
},
...
]
}
You then have to react on changes of the value for the creator field, which then indicated that there's a new calendar to be created (creator = page_id)

INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session

Similar issues -
INVALID_SESSION_ID using partner/enterprise wsdl for two different SF users - Tried solution but didn't work.
I was trying to use Salesforce PHP toolkit with ZF 2. I have added namespace to php files in salesforce soap client and used it in zend controller.
Added follwing line to all php files in Salesforce SOAP client library.
namespace Salesforce\Soapclient;
Then included it in ZF controller.
use Salesforce\Soapclient;
Here is the connetion code -
$empid = 'e1234567';
$sf_WSDL = 'C:\wamp\www\myapp\app\vendor\salesforce\wsdl\enterprise.wsdl.xml';
$sf_username = $config['salesforce']['username'];
$sf_password = $config['salesforce']['password'];
$sf_token = $config['salesforce']['token'];
/***********/
try {
// Create SOAP client instance
$sfSoapClient = new Soapclient\SforceEnterpriseClient();
// Create connection
$sfSoapClient->createConnection($sf_WSDL);
var_dump($_SESSION['enterpriseSessionId']);
if (isset($_SESSION['enterpriseSessionId'])) {
$location = $_SESSION['enterpriseLocation'];
$sessionId = $_SESSION['enterpriseSessionId'];
$sfSoapClient->setEndpoint($location);
$sfSoapClient->setSessionHeader($sessionId);
} else {
// Login to SF
$sfSoapClient->login($sf_username,$sf_password . $sf_token);
$_SESSION['enterpriseLocation'] = $sfSoapClient->getLocation();
$_SESSION['enterpriseSessionId'] = $sfSoapClient->getSessionId();
}
var_dump($_SESSION['enterpriseSessionId']);
// Get candidate profile by employee id
$candidate_profile = $this->getCandidateTable()->getCandidateByEmpId($empid);
$ids = array();
array_push($ids, $empid);
// If no profile for logged internal employee
if (!$candidate_profile){
$query = "SELECT Id, First_Name__c from Employee__c";
$response = $sfSoapClient->query($query);
echo "Results of query '$query'<br/><br/>\n";
foreach ($response->records as $record) {
echo $record->Id . ": " . $record->First_Name__c . "<br/>\n";
}
}
} catch (Exception $exc) {
//TODO Handle error login exception
die('Connection could not established.');
}
But I'm getting following error -
INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal
Session
Note that "Lock sessions to the IP address from which they originated" setting is turned off.

Writing to Google Docs Spreadsheet using PHP

Is there anyway I could write data to a Google Docs Spreadsheet using PHP, besides the Zend library? I have tried the Zend library, and while it is helpful, I want to be able to specify a specific row and column to write to, instead of writing to the last row of the specified column. From what I have seen, the Zend library is not capable of this.
Any links or code would be greatly appreciated!
I Hope this one useful for anyone..
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "someuser#gmail.com";
$pass = "somepass";
try {
// connect to API
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$service = new Zend_Gdata_Spreadsheets($client);
// set target spreadsheet and worksheet
$ssKey = 'ssid';
$wsKey = 'wsid';
// update cell at row 6, column 5
$entry = $service->updateCell('6', '5', 'Hello, world', $ssKey, $wsKey);
echo 'Updated cell ' . $entry->getTitle()->getText() . '';
// clear cell at row 1, column 1
$entry = $service->updateCell('1', '1', '', $ssKey, $wsKey);
echo 'Cleared cell ' . $entry->getTitle()->getText();
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
The Zend library should be able to edit the contents of a given cell within the spreadsheet. See documentation here: http://code.google.com/apis/spreadsheets/data/1.0/developers_guide_php.html#updateCell
The 'updateCell' method allows you to pass in a row and column as your target, and set the contents to the new value. Have you had a chance to try this method?

Categories