Client for Google API PHP Client and nested requires? - wordpress

I'm trying to implement Google analytics api in a wordpress dashboard plugin.
Following the simplest implementation for using the Google API for PHP for the first time, its not working right away at practically the first step.
According to the tutorial README.md, my app, placed ajacent to the library folder, should load the library like so:
require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';
$client = new Google_Client();
Now, the structure of the library within my app (plugin) is:
myapp.php
/Google
/Google/Client.php
/Google/otherfolders/otherfiles.php
and my app attempts to load the library per the require_once above. But of course the Client.php has many require_once calls itself such as:
require_once 'Google/Auth/AssertionCredentials.php';
Which seem to ignore its position -- already within /Google.
So I'm getting errors:
PHP Warning: require_once(Google/Auth/AssertionCredentials.php) [<a href='function.require-once'>function.require-once</a>]: failed to open stream: No such file or directory in <wpengine host path removed>/wp-content/plugins/mmstats/Google/Client.php on line 18
and
PHP Fatal error: require_once() [<a href='function.require'>function.require</a>]: Failed opening required 'Google/Auth/AssertionCredentials.php' (include_path='.:/usr/share/php:/usr/share/pear') in <wpengine host path removed>/wp-content/plugins/mmstats/Google/Client.php on line 18
This PHP is listed as "Beta" but surely I'm doing something wrong rather than this being a problem with Client.php
Any help appreciated!

The Google Director needs to be in the same directory as your file. If its not your going to have to edit all the required_once's yourself. Here is some working code for use with the Google Analytics API.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
You can find a tutorial for this code at Google Oauth2 PHP, there is a little test app at the bottom where you can see it working.

Related

PHPMailer & WordPress "Post by Email" - not creating post

I'm creating a script for a client using their PHP 5.4.16 (updating is not in the scope of this project), and therefore PHPMailer 5.2.25. My script (below) works if I change the SetAddress to my personal Gmail account (I get the email with subject, body, and attachment (the latter being the reason for using PHPMailer)), but if I change the SetAddress to my WordPress "Post by Email" address, nothing seems to be delivered.
Questions:
Is there anything wrong with my script? Missing headers? Badly formatted email?
If my script is apparently OK, what other avenues of investigation might there be?
Thanks
<?php
echo "<p>" . date("h:i:sa");
?>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/../www/phpmailer/class.phpmailer.php'); ?>
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/../www/phpmailer/class.smtp.php'); ?>
<?php
$mail = new PHPMailer();
$mail->IsSMTP(); // enable SMTP
//$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 587; // or 587
$mail->IsHTML(true);
$mail->Username = "my#gmail.com";
$mail->Password = "mypassword";
$mail->From = "my#gmail.com";
$mail->FromName = "Me";
//$mail->AddAddress("caju317davu#post.wordpress.com");
$mail->AddAddress("my#gmail.com");
$mail->AddReplyTo("my#gmail.com","developer");
$mail->AddAttachment($_SERVER['DOCUMENT_ROOT'] . '/../www/_assets/articles/223/610/7f10120230e612e03eea9aa54a48a68f.jpg', 'attachment.jpg');
$mail->Subject = "My test email";
$mail->Body = "Hi! This is my first successful post created through email.";
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
Now I am not sure if this will help at all but below is the code that I have for a working version of PHPMailer v5.2.9 that is running on a site using PHP version 5.4.16 so may help. The obvious differences I can see is the recipient's section don't have "set" or "Add" and also I can't seem to find the initiator ($mail->send();). Let me know if this helps and for any areas needing extra clarification.
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.host.co.uk'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#example.co.uk'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('email#example.co.uk', 'Company Name');
$mail->addAddress($email); //Gets the email the enquiry form field contains
$mail->addReplyTo('email#example.co.uk', 'Company Name');
$body='<div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica,
sans-serif; font-size:12px; margin:0; padding:0;">
<p>Thank you for your enquiry, a member of the team will be in touch shortly to discuss your requirements. In the mean time, please double check the below details entered on our website. If any of these are incorrect or you wish to add to it, please contact us via email or over the phone.</p></div>';
//Content
$mail->isHTML(true);
$mail->Subject = $subject ;
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$mail->send();
echo $thankyou_text;
} catch (Exception $e) {
echo $failed_text;
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
From a 'Happiness Engineer' at WordPress:
Hi there!
At WordPress.com we don't allow posts to be sent automatically from
scripts such as PHPMailer.
I guess that answers that! Now to forget PHPMailer, and try and get back to default PHP mail() :(
Sorry to have bothered you all

Which PHP Script File is needed for ical() class in Google Calendar PHP API v3

I am getting an error in a PHP script I am building:
Fatal error: Class 'ical' not found in /home/abc/public_html/app/mods/googleCalendar_3.0/cache_events.php on line 74
Here is a snippet from my script file:
define('CLIENT_ID', 'ASDLJJLDSJLASDJLajdl;jdsljkASD;LKJASDLKJASD.apps.googleusercontent.com');
require_once('autoload.php'); // 2014-11-24 part of /usr/local/lib/php/google-api-php-client
require_once('/usr/local/lib/php/google-api-php-client/src/Google/Client.php'); // 2014-11-25
require_once('/usr/local/lib/php/google-api-php-client/src/Google/Service/Calendar.php'); // 2014-11-25
$ical = new ical('https://www.google.com/calendar/ical/CLIENT-ID/public/basic.ics');
$eventListArray = array_filter($ical -> events(), "locationfilter");
$eventCount = count($eventListArray);
print_r($eventListArray); echo "<br>";
echo "Event Count:" . $eventCount;echo "<br>";
exit;
I am simply trying to retrieve all events in my public calendar
Notes:
Calendar is publicly viewable
Just to make sure, I added my Auth & API's > Credentials > Service Account > Email Address to it just to be safe
If you want to use a service account your code is off quite a bit. I cant test this code my local webserver is acting up but it should be close you may have to tweek the $service->Events->list(); part it was kind of a guess. Make sure that you have the Service account email address added as a user on the calendar in question and it should work.
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Calendar($client);
// you should only need to do this once print this and you will
// find the calendarId for the one you are looking for.
$calendars = $service->calendarList->list();
$events = $service->events->list($yourCalendarID);
Note: all you need is the Google Dir you can remove everything above that you dont really need it. Code was edited from the only tutorial i have that shows this in PHP.

Adding a wordpress user to Salesforce Contact

I'm trying to do a relatively simple task by hooking into the Wordpress registration and adding the user that's being registered to a Salesforce db. When I run the Salesforce db code outside of Wordpress it works flawlessly, but when I test this by registering on my wordpress website, I get an error stating: INVALID_LOGIN: Invalid username, password, security token; or user locked out.
Additionally, I receive this error from Wordpress "Cannot modify header information - headers already sent" which doesn't allow me to view the entire object data that's being sent to Salesforce.
This is my code:
$SF_USERNAME = 'test';
$SF_PASSWORD = 'test';
define( 'CD_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
require_once (CD_PLUGIN_PATH . 'Toolkit/soapclient/SforceEnterpriseClient.php');
require_once (CD_PLUGIN_PATH . 'Toolkit/soapclient/SforceHeaderOptions.php');
function add_user_to_SF($user_id) {
$user = get_userdata($user_id);
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(CD_PLUGIN_PATH . 'Toolkit/soapclient/enterprise.wsdl.xml');
$mylogin = $mySforceConnection->login($SF_USERNAME, $SF_PASSWORD);
print '<pre>';
print_r($mylogin);
print '</pre>';
print '<br/><br/>';
$sObject = new stdclass();
$sObject->FirstName = $user->first_name;
$sObject->LastName = $user->last_name;
$sObject->Email = $user->user_email;
//echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create(array($sObject), 'Contact');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
$errors->add( 'demo_error', __(print_r($_POST),'mydomain') );
$errors->add( 'demo_error', __($mySforceConnection->getLastRequest(),'mydomain') );
$errors->add( 'demo_error', __($e->faultstring,'mydomain') );
return $errors;
}
}
add_filter( 'registration_errors', 'add_user_to_SF', 10, 3 );
This is a php scope issue.
Adding:
global $SF_USERNAME;
global $SF_PASSWORD;
inside the function fixed the problem.
It looks like you might be missing the security token. It's appended to the end of the password.
This link explains how to generate the token
https://login.salesforce.com/help/doc/en/user_security_token.htm
You need to add your salesforce account security token with password
eg. Password - "testing"
Security Token - "2321njjn32j32"
You need to pass as - "testing2321njjn32j32"
This will work properly.

application loaded in iframe on facebook

I have an app loaded in iframe on facebook.
But after allow and redirected to my facekooksite from facebook authorization i cant fetch the "code" from the querrystring from within my code (because loaded in an iframe on facebook)
How will i be able to fetch the "code" parameter?
I guess you are following the server-side authentication flow. But since you are using Apps on Facebook, this flow will change since Facebook is sending a signed_request to your canvas iframe:
<?php
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
?>
Obviously when you are on Facebook, the user is either connected to your app or not so if he/she is not connected then you redirect them to the authentication URL.

Fatal error: Call to undefined method Facebook::require_frame() in /home/wubb/public_html/facebook/fbml.php on line 15

I am trying to integrate friend invite for facebook in my website. I am using php. I included the code:
<?PHP
// Get these from http://developers.facebook.com
$api_key = 'xxx';
$secret = 'xxx';
// Names and links
$app_name = "Application name";
$app_url = "app-url"; // Assumes application is at http://apps.facebook.com/app-url/
$invite_href = "invite.php"; // Rename this as needed
require_once 'facebook.php';
$facebook = new Facebook($api_key, $secret);
$facebook->require_frame();
$user = $facebook->require_login();
if(isset($_POST["ids"])) {
echo "<center>Thank you for inviting ".sizeof($_POST["ids"])." of your friends on <b>".$app_name."</b>.<br><br>\n";
echo "<h2>Click here to return to ".$app_name.".</h2></center>";
} else {
// Retrieve array of friends who've already authorized the app.
$fql = 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='.$user.') AND is_app_user = 1';
$_friends = $facebook->api_client->fql_query($fql);
// Extract the user ID's returned in the FQL request into a new array.
$friends = array();
if (is_array($_friends) && count($_friends)) {
foreach ($_friends as $friend) {
$friends[] = $friend['uid'];
}
}
// Convert the array of friends into a comma-delimeted string.
$friends = implode(',', $friends);
// Prepare the invitation text that all invited users will receive.
$content =
"<fb:name uid=\"".$user."\" firstnameonly=\"true\" shownetwork=\"false\"/> has started using ".$app_name." and thought it's so cool even you should try it out!\n".
"<fb:req-choice url=\"".$facebook->get_add_url()."\" label=\"Put ".$app_name." on your profile\"/>";
?>
<fb:request-form
action="<? echo $invite_href; ?>"
method="post"
type="<? echo $app_name; ?>"
content="<? echo htmlentities($content,ENT_COMPAT,'UTF-8'); ?>">
<fb:multi-friend-selector
actiontext="Here are your friends who don't have <? echo $app_name; ?> yet. Invite whoever you want -it's free!"
exclude_ids="<? echo $friends; ?>" />
</fb:request-form>
<?PHP
}
?>
[[Image:multi-friend-selector.png]]
Here I included facebook.php file I downloaded from the github .I tried many versions of phpSDK but still the following error is coming
Fatal error: Call to undefined method Facebook::require_frame()
Can anybody suggest which version conatain this function or how to solve this issue. I have lost a lot of time trying to solve this. So respond as soon as possible.
Trikode,
Make sure you are using the most recent version of the php sdk: https://github.com/facebook/facebook-php-sdk. There is a really easy to follow guide here to help you get started: https://developers.facebook.com/docs/reference/php/

Resources