Zend Calendar Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 401 - zend-framework

I want inteface this script with google calendar using Zend Framework.
This code works locally but doesn't works on altervista.
The error is
Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with
message 'Expected response code 200, got 401
<?php
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 = "xxx#gmail.com";
$pass = "xxxxx";
$title= "Evento ";
$content="evento presso nome associaizone";
$where="luogo";
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
try {
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cl');
} catch (Zend_Gdata_App_CaptchaRequiredException $cre) {
echo 'URL of CAPTCHA image: ' . $cre->getCaptchaUrl() . "\n";
echo 'Token ID: ' . $cre->getCaptchaToken() . "\n";
} catch (Zend_Gdata_App_AuthException $ae) {
echo 'Problem authenticating: ' . $ae->exception() . "\n";
}
$service = new Zend_Gdata_Calendar($client);
//
// Create a new entry using the calendar service's magic factory method
$event= $service->newEventEntry();
// Populate the event with the desired information
// Note that each attribute is crated as an instance of a matching class
$event->title = $service->newTitle($title);
$event->content= $service->newContent($content);
$event->where = array($service->newWhere($where));
// Set the date using RFC 3339 format.
$startDate = "2014-03-18";
$startTime = "14:00";
$endDate = "2014-03-19";
$endTime = "16:00";
$tzOffset = "-08";
$when = $service->newWhen();
$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
$event->when = array($when);
// Upload the event to the calendar server
// A copy of the event as it is recorded on the server is returned
$newEvent = $service->insertEvent($event);
?>

Zend_Gdata and ZendGData are out of maintenance.
Instead the recomendation is migrate to the official Google SDK https://code.google.com/p/google-api-php-client/

Related

Fatal error: require_once(): Failed opening required ... Novice programmer, appreciate any guidance

I'm a novice in server-side programming so any advice is appreciated.
I have some PHP files uploaded on a virtual server (000webhost.com) and I'm having trouble with locating a file I'm requiring in another PHP file. The register.php is attempting to "require_once" the update_user_info.php
Here's the code for register.php (Which I've taken from a tutorial and adjusted it with my variables):
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'../update_user_info.php');
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST ['password']) && isset($_POST['branch']) && isset($_POST['gender'])) {
// receiving the post params
$username = $_POST['username'];
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$branch = $_POST['branch'];
$gender = $_POST['gender'];
// check if user is already existed with the same email
if ($db->CheckExistingUser($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->StoreUserInfo($username, $name, $email, $password, $branch, $gender);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["branch"] = $user["branch"];
$response["user"]["gender"] = $user["gender"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter (username, name, email or password) is missing!";
echo json_encode($response);
}
?>
And here's a screenshot of the error that's occurring when attempting to visit the link containing the register.php:
Screenshot of the error
What I've tried so far:
1- tried to use require_once __DIR__."/../filename.php"; and lots more of the same, basically tinkering the statement with different language constructs and constants.
2-Read tutorials on the correct way to use require once but their cases is almost always very different. Either they are using WAMP/XAMPP -meaning they have a local path not a virtual one- So no luck there.
3- tried to change .htaccess file, as someone said in a post that it solved his problem.
4- I'm certain that both files are uploaded to the same directory. Yet it says "No such file".
Does anyone have an idea of where the error could be stemming from? Thanks in advance!

Facebook Graph Api error "An unexpected error has occurred. Please retry your request later"

I'm trying to retrieve all members in a Facebook group getting this error:
array(5) {
["message"]=>
string(66) "An unexpected error has occurred. Please retry your request later."
["type"]=>
string(14) "OAuthException"
["is_transient"]=>
bool(true)
["code"]=>
int(2)
["fbtrace_id"]=>
string(11) "AnfsXcdgM"
}
Here is my code:
$this->_facebook = new Facebook\Facebook(array('app_id' => "$app_id",'app_secret' => "$secret",'default_graph_version' => 'v2.10'));
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name";
try{
$response = $this->_facebook->get($query);
while($pagesEdge)
{
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
$id = $member->id;
}
}
}catch (Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); }
It works for groups with few hundreads of people (even once for a group with 10.000 members) but randomly I'm occurring to this.
This might be caused by a server side timeout. I get this error every now and then when I request a huge amount of data. Maybe you should try to limit your request by using the limit parameter (default should be 25).
I solved this by doing a cron that takes 100 data at the time and putting into a file text the value of the token for the next call.
I add this string on the query and when the fields inside $url are empty I quit my execution
<?php
public function updateGroupMembers($groupID)
{
$tempNext = file_get_contents($this->dirM); //check if the next string token is in the file
if (!empty($tempNext))
{
$queryUntil = $tempNext;
}
// Sets the default fallback access token so we don't have to pass it to each request
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
// Create table name
$tableName = $groupID . "_Members";
// Query the Graph API to get all current member's ID and name
try
{
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name".$queryUntil; //add the next string to my query
$response = $this->_facebook->get($query);
$pagesEdge = $response->getGraphEdge();
// Index for the elements fetched from the API below
$i = 0;
// Get current time
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
/* ...get data and process them... */
}
$temp = $pagesEdge->getMetaData();
$next = parse_url($temp['paging']['next']);
parse_str($next['query'], $url);
$access_token = '&access_token='.$url['access_token'];
$fields = '&fields='.$url['fields'];
$limit = '&limit=100';
$after = '&after='.$url['after'];
$res['until'] = $access_token.$fields.$limit.$after;
file_put_contents($this->dirM, $res['until'], LOCK_EX);
if ( empty($url['access_token']) || empty($url['fields']) || empty($url['limit']) || empty($url['after']) )
{
file_put_contents($this->dirM, '', LOCK_EX); //clean my txt file that contains my next string
die('FINE');
}
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'm2Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'm2Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}

(403) User does not have any Google Analytics account

i have issue with google api service account i have done successfull authentication and got the access token. when i try to run the query it shows error
Warning: You need to set Client ID, Email address and the location of
the Key from the Google API console:
http://developers.google.com/consoleThere wan a general error : Error
calling GE T
(403)
User does not have any Google Analytics account.
i have multiple websites and multiple accounts in it. the google account is an admin account please check the code below.
$key_file_location = 'key path';
$client = new Google_Client();
$client->setApplicationName("name");
$client->setClientId($client_id);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$client->setAccessType('offline_access');
$client->getAccessToken();
$service = new Google_Service_Analytics($client);
$analytics_id = 'ga:xxxxxx';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $service->data_ga->get($analytics_id, $lastWeek, $today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}

PHPMailer attachment is not receiving

I have written code for sending mail with pdf file as attachment , mail sending is working. I used class.phpmailer.php. Below is my code.
$mpdf=new mPDF();
$mpdf->ignore_invalid_utf8 = true;
$stylesheet = file_get_contents('appstyle_pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($output);
$comname = preg_replace("/[^A-Za-z0-9]/","",$_POST['company']);
$name = $dirname.str_replace(" ","-",$comname)."_".$time_stamp.".pdf";
$mpdf->Output($name,"F");
$filename = basename($name);
$file_size = filesize($name);
$content = chunk_split(base64_encode(file_get_contents($name)));
$mail = new PHPMailer;
$msg = 'Message';
$body = '<html><body><p>' . $msg . '</p></body></html>'; //msg contents
$body = preg_replace("[\\\]", '', $body);
$mail->AddReplyTo('no-replay#enkapps.com', "ACIC");
$mail->SetFrom('orders#enkapps.com', "ACIC Order");
$address = 'narendar_medoju#tecnics.com'; //email recipient
$mail->AddAddress($address, "NAME");
$mail->Subject = 'SUBJECT of ACIC order form';
$mail->MsgHTML($body);
$mail->AddStringAttachment($content , $filename);
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent Successfully please check attachement!";
}
When I use the above code attachment is coming to mail but file is corrupting. The error message is like "Adobe reader could not open abc.pdf because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."
Why are you doing this?
$content = chunk_split(base64_encode(file_get_contents($name)));
...
$mail->AddStringAttachment($content , $filename);
That's completely unnecessary. Just do this:
$mail->addAttachment($name);
Also I suspect you are using an old version of PHPMailer; get the latest from github.

passing a string as parameter in a facebook api request

I am working on a facebook application, and some of the data that I want are the groups of that user and the other members of that group as shown in this code:
$groups = $facebook->api('/me/groups?since=0');
mysqlc();
foreach($groups['data'] as $group){
$gid=GetSQLValueString($group['id'], "text");
$name=GetSQLValueString($group['name'], "text");
//echo $gid." -> ".$name;
$query = sprintf("SELECT * FROM `group` WHERE gid = %s", $gid);
$res = mysql_query($query) or die('Query failed: ' . mysql_error() . "<br />\n$sql");
if(mysql_num_rows($res) == 0){
$iquery = sprintf("INSERT INTO `group`(gid, name) values(%s,%s)", $gid, $name);
$ires = mysql_query($iquery) or die('Query failed: ' . mysql_error() . "huhuhu<br />\n$sql");
}
$c = explode("'", $gid);
$params = "/".$c[1]."/members";
echo "'".$params."'";
$members = $facebook->api("'".$params."'");
print_r($members);
}
what I wanted to have after this code are the members of each group that the user has, but this code is not working properly.. So my main query is what is the proper way or replacement to this line:
$members = $facebook->api("'".$params."'");
where I can use the fetched group Id. thanks a lot to those who will answer my query.