PHP using Zend for Google Calendar not generating webpage - php

I am working on the tutorial on IBM.com for using the Zend framework to work with the Google Calendar API. I literally copied a chunk of code from the tutorial and tried to use it, but it does not seem to be working. My php file includes the following:
<!--Some HTML is above here-->
<body>
<?php
// load library
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');
// create authenticated HTTP client for Calendar service
$gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user = "username#gmail.com"; //replace with my username
$pass = "pass"; //replace with my password
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal);
$gcal = new Zend_Gdata_Calendar($client);
// generate query to get event list
$query = $gcal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('basic');
// get and parse calendar feed
// print output
try {
echo "<!--this comment is seen-->\n";
$feed = $gcal->getCalendarEventFeed($query);
echo "<!--this comment is not seen-->\n";
} catch (Zend_Gdata_App_Exception $e) {
//this doesn't happen.
echo "Error: " . $e->getResponse();
}
?>
<h1><?php echo $feed->title; ?></h1>
<?php echo $feed->totalResults; ?> event(s) found.
<p/>
<ol>
</body>
Literally the only changes I made to this code is replacing the username and password with my own email address and password. When the code execution reaches the statement in the try block, it seems to fail, but is not caught in the catch block, even when I change it to catch any exception, not just Zend_Gdata_App_Exception. The generated page source clearly shows that the PHP is crashing, though:
<!--Some HTML is above here-->
<body>
<!--this comment is seen-->
with nothing after that. I am learning PHP on the fly here, so any help would be extremely appreciated!

<?php
**$path = 'ZendGdata/library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $path);**
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
...
and you should download the ZendGdata/library like they explain here https://developers.google.com/google-apps/calendar/v1/developers_guide_php
that is the official google calendar api Developer's Guide. The code you are using is deprecated though. I'm still using it but they suggest you switch over to google calendar API v3, you can find the documentation for that, on the same page.

Related

twilio play hold music and redirecting to dial

Aim: I want that when the call is created it should play music instead of ringing and noone is available to pick call . after playing music it should say it.
after that it should redirect to feedback page
Now: call is created and mp3 is played when we pick the call and feedback page is running when it is dialling the call
So I want a solution to handle this
<?php
if (($nowtime >= $start_time) && ($nowtime <= $end_time)){
$the_mnum = $con ->load_field($the_id, 'the_mnum');
//$m= $the_mnum;
//echo $the_mnum;
?> <Say voice="woman">
We are directing your call to the therapist.
</Say>
<?php
$check_therapist = true;
$_SESSION["the_mnum"] = $the_mnum;
break;
}
}
if ($check_therapist){
$version = '';
$sid = '';
$token = '';
$client = new Services_Twilio($sid, $token, $version);
$call = $client->account->calls->create("+1", $the_mnum, "wekaw1.mp3", array());
echo $call->sid;
?>
<Redirect>feedback.php</Redirect>
<?php } else {?>
<Say voice="woman">
No listener is available right now.
We will give you a call back shortly when we have available listener.
</Say>
<?php } ?>
</Response>
In order to play hold music instead of rings before 2 numbers are connected you need to use <Enqueue> and <Queue> combined and initiate a call via our Rest API.
The following is an example implementation in PHP.
You need to assign the file below to your phone number. This code will <enqueue> the call and initiate a call forwarding to your number. This will also initiate a request to the second file that you need to create (modify_leg.php).
In some file first.php:
$name = $_POST['CallSid'];
echo '<Response><Enqueue>'.$name.'</Enqueue></Response>';
// Make sure to include php-helper library
require('../Services/Twilio.php'); // Loads the library
$account_sid = 'ACxxxxxxxxxxxxxxxxx';
$auth_token = 'aaxxxxxxxxxxx';
$from_number = '+1xxxxxx';
$to_number = '+1xxxxxxxx';
$client = new Services_Twilio($account_sid, $auth_token);
$message = $client->account->calls->create($from_number, $to_number, 'http://Your-FQDN/modify_leg.php?callSid='.$name);
Now in (modify_leg.php) you will pass $_GET[callSid] so it will actually connect both calls once you answer the phone and the caller will listen to music until you actually pick up the call.
<?php
$who = $_GET['callSid'];
?>
<Response>
<Dial><Queue><?php echo $who ?></Queue></Dial>
</Response>

Error when using QuickBooks PHP DevKit examples

I have successfully setup the Quickbooks PHP DevKit, but I am currently trying to run the example_customer_add script with my sandbox. When I do, I get the following error:
Notice: Undefined variable: Context in /Applications/MAMP/htdocs/quickbooks-php/test_qb.php on line 54
I've tried to track down the $Context variable, but it is used all over the place, and I'm unsure of where it being set, etc...
Any help is appreciated! Thanks!
EDIT
I'm just using the script included in the docs folder of the Quickbooks PHP DevKit:
<?php
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/views/header.tpl.php';
?>
<pre>
<?php
$CustomerService = new QuickBooks_IPP_Service_Customer();
$Customer = new QuickBooks_IPP_Object_Customer();
$Customer->setTitle('Ms');
$Customer->setGivenName('Shannon');
$Customer->setMiddleName('B');
$Customer->setFamilyName('Palmer');
$Customer->setDisplayName('Shannon B Palmer ' . mt_rand(0, 1000));
// Terms (e.g. Net 30, etc.)
$Customer->setSalesTermRef(4);
// Phone #
$PrimaryPhone = new QuickBooks_IPP_Object_PrimaryPhone();
$PrimaryPhone->setFreeFormNumber('860-532-0089');
$Customer->setPrimaryPhone($PrimaryPhone);
// Mobile #
$Mobile = new QuickBooks_IPP_Object_Mobile();
$Mobile->setFreeFormNumber('860-532-0089');
$Customer->setMobile($Mobile);
// Fax #
$Fax = new QuickBooks_IPP_Object_Fax();
$Fax->setFreeFormNumber('860-532-0089');
$Customer->setFax($Fax);
// Bill address
$BillAddr = new QuickBooks_IPP_Object_BillAddr();
$BillAddr->setLine1('72 E Blue Grass Road');
$BillAddr->setLine2('Suite D');
$BillAddr->setCity('Mt Pleasant');
$BillAddr->setCountrySubDivisionCode('MI');
$BillAddr->setPostalCode('48858');
$Customer->setBillAddr($BillAddr);
// Email
$PrimaryEmailAddr = new QuickBooks_IPP_Object_PrimaryEmailAddr();
$Customer->setPrimaryEmailAddr($PrimaryEmailAddr);
if ($resp = $CustomerService->add($Context, $realm, $Customer))
{
print('Our new customer ID is: [' . $resp . '] (name "' . $Customer- >getDisplayName() . '")');
}
else
{
print($CustomerService->lastError($Context));
}
?>
</pre>
<?php
require_once dirname(__FILE__) . '/views/footer.tpl.php';
The quickbooks_oauth table looks like this after attempting to connect:
'1', 'DO_NOT_CHANGE_ME', '12345', 'qyprdaX1yo1uYqu3GU8xxPvs8raoTss2ZVRBE3fHWy7qZdAB', 'IWZHlW2e956sqR9GVIxa2JOU82NdSrJixZLpb3af', 'KNwiKE2bUXtqFqJ/Vb0NhjzBGYMXwRRcT9xtFOQiV6F8aEgUoqGzA7aheRLPJ/z6EPYy1ZS4e6ZuVpteBaQtxc5H0cN5VcCmWLfj+lryaCpLgw8mGK5+E/Muv2wJ+3UwbOyqVstU+pYQw/yNgFKhfSuA3lOgjgqctuO6ZpMK1wWr42IycA05QrJuOB4+LQ==', 'rCj1V3zl4Jj5mHgTw+BPCPN7SDcJkzLQPWb1tyerEXedsQB0WsZ+caMCBafS+hfN3ECZl3mfNDSyIqKDK+t8RSEAKyFWwRSPOh3UcWDCDEhXrTSUddmKhoIq6pL6yVtNEyETyNtfMaKYN+U6uIwSEMKZB/4IUjK8c0GP5KhoKSl0dv+Bp9w=', '1391140255', 'QBO', NULL, '2015-06-04 19:57:58', '2015-06-04 19:58:36', '2015-06-04 19:58:36'
The code you posted is missing several lines at the top of the script. Look at the example on GitHub:
https://github.com/consolibyte/quickbooks-php/blob/master/docs/partner_platform/example_app_ipp_v3/example_customer_add.php#L3
There are two require_once statements that you are missing. $Context is defined in those required files.
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/views/header.tpl.php';
Fix your code so that you're using the example code completely, and making sure those required files actually get included.
If you continue to have trouble, please post your updated code.
You can see where $Context gets defined here:
https://github.com/consolibyte/quickbooks-php/blob/master/docs/partner_platform/example_app_ipp_v3/config.php#L110
Note that you must be connected to QuickBooks to run the example. I'm assuming you have clicked the "Connect to QuickBooks" button and gotten connected already... right?

Youtube API V3 PHP Search by Keyword code sample not working

I tried running the sample code that Google gives you on their developer Code Sample page (https://developers.google.com/youtube/v3/code_samples/php#search_by_keyword) isn't working for me. I made sure to download the latest version of the library from GitHub, installed it to my PHP5/Apache2 server, changed the Include Path, and for some reason, one of the require_once items is not working properly. Here is the code that I have (modified only with some echo statements). I put in my developer key, but have removed it in this post for obvious reasons.
<?php
$htmlBody = <<<END
<form method="GET">
<div>
Search Term: <input type="search" id="q" name="q" placeholder="Enter Search Term">
</div>
<div>
Max Results: <input type="number" id="maxResults" name="maxResults" min="1" max="50" step="1" value="25">
</div>
<input type="submit" value="Search">
</form>
END;
// This code will execute if the user entered a search query in the form
// and submitted the form. Otherwise, the page displays the form above.
if ($_GET['q'] && $_GET['maxResults']) {
echo "echo 1";
echo "<br/>";
// Call set_include_path() as needed to point to your client library.
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/pi/google-api-php-client/src');
require_once('Google/Client.php');
echo "echo 2<br/>";
require_once ('Google/Service/YouTube.php');
echo "echo 3";
echo "<br/>";
/*
* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
* Google Developers Console <https://console.developers.google.com/>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$DEVELOPER_KEY = 'my-api-key-here';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
try {
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => $_GET['maxResults'],
));
$videos = '';
$channels = '';
$playlists = '';
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind']) {
case 'youtube#video':
$videos .= sprintf('<li>%s (%s)</li>',
$searchResult['snippet']['title'], $searchResult['id']['videoId']);
break;
case 'youtube#channel':
$channels .= sprintf('<li>%s (%s)</li>',
$searchResult['snippet']['title'], $searchResult['id']['channelId']);
break;
case 'youtube#playlist':
$playlists .= sprintf('<li>%s (%s)</li>',
$searchResult['snippet']['title'], $searchResult['id']['playlistId']);
break;
}
}
$htmlBody .= <<<END
<h3>Videos</h3>
<ul>$videos</ul>
<h3>Channels</h3>
<ul>$channels</ul>
<h3>Playlists</h3>
<ul>$playlists</ul>
END;
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
?>
<!doctype html>
<html>
<head>
<title>YouTube Search</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
with the interesting part being here
echo "echo 1";
echo "<br/>";
// Call set_include_path() as needed to point to your client library.
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/pi/google-api-php-client/src');
require_once('Google/Client.php');
echo "echo 2<br/>";
require_once ('Google/Service/YouTube.php');
echo "echo 3";
echo "<br/>";
When I run the page, the output is this
echo 1
echo 2
What's happening with the second require_once statement that causes the page to stop running after that? At one point I had an echo statement immediately following the set_include_path(), but that seemed to be working properly, so I removed it.
I solved the issue by adding all dependencies manually. After adding all required dependencies, this is what I ended up with.
require_once ('Google/Logger/Null.php');
require_once('Google/Client.php');
require_once ('Google/Config.php');
require_once ('Google/Model.php');
require_once ('Google/Collection.php');
require_once ('Google/Service.php');
require_once ('Google/Service/Resource.php');
require_once ('Google/Service/YouTube.php');
You can add
require_once 'include/Google/autoload.php';
in front of code, and delete all other require like:
//require_once 'include/Google/Client.php';
//require_once 'include/Google/Service/YouTube.php';
But the php version should greater than 5.3
Some things you can try:
Turn on PHP's error output. If an error occurs, you get an information in the resulting html. You can find more information on how to enable it in this thread.
Make sure Google/Service/YouTube.php exists. Navigate to the folder and check manually.
Print the include path before including YouTube.php (I don't actually think this could be the problem, but who knows...)
Looks like you didn't set your PHP's include path correctly. If you add this client library's src/ file into include path, it should just work fine.

Google Adword PHP client library couldn't connect to host

Im working on connecting my website to connect to Google Adwords to create ads and campains depending up on the products in my site. I tried connecting by sending direct curl request and parse the received SOAP response. But that is too becoming complex for each request. So i tried using the PHP client library provided in Google Code. But none of the example is working correctly. I changed the user account details in auth.ini file but still on excecuting the example files it says
Failed to get authToken. Reason:
couldn't connect to host'.
I tried running the scripts in different servers but still getting the same error.
Following is the code to fetch all ads from Google adwords and this is a example file from Client library
$path = dirname(__FILE__) . '/../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Api/Ads/AdWords/Lib/AdWordsUser.php';
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log SOAP XML request and response.
$user->LogDefaults();
// Get the AdGroupAdService.
$adGroupAdService = $user->GetAdGroupAdService();
$adGroupId = (float) '01';
// Create selector.
$selector = new Selector();
$selector->fields = array('Id', 'AdGroupId', 'Status');
$selector->ordering = array(new OrderBy('Id', 'ASCENDING'));
// Create predicates.
$adGroupIdPredicate = new Predicate('AdGroupId', 'IN', array($adGroupId));
// By default disabled ads aren't returned by the selector. To return them
// include the DISABLED status in a predicate.
$statusPredicate =
new Predicate('Status', 'IN', array('ENABLED', 'PAUSED', 'DISABLED'));
$selector->predicates = array($adGroupIdPredicate, $statusPredicate);
// Get all ads.
$page = $adGroupAdService->get($selector);
// Display ads.
if (isset($page->entries)) {
foreach ($page->entries as $adGroupAd) {
printf("Ad with id '%s', type '%s', and status '%s' was found.\n",
$adGroupAd->ad->id, $adGroupAd->ad->AdType, $adGroupAd->status);
}
} else {
print "No ads were found.\n";
}
} catch (Exception $e) {
echo 'Inside catch exception';
print $e->getMessage();
}
and in the settings.ini file
DEFAULT_SERVER =
"https://adwords-sandbox.google.com"
; AUTH_SERVER = "<SERVER>"
In auth.ini file
My Google account's username and password are set correctly.
Can someone help me in getting this issue fixed.
Thanks
It's the AUTH_SERVER setting, not DEFAULT_SERVER, that indicates where authentication requests are being sent. This should be at the bottom of settings.ini but is normally commented out so that the default setting of https://www.google.com is used. You should check that AUTH_SERVER is commented out and that you can connect to https://www.google.com.

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

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.

Categories