WordPress - Issues with referencing custom PHP class in functions.php - php

I apologize if this is really dumb/obvious but this is my first experience working with classes in WordPress.
I made a class called SharpSpringService.php inside my custom plugin sharpspring-form. I placed the class within a classes folder within that custom plugin for organization purposes.
I'm referencing the SharpSpringService class within a function in functions.php but am getting an error. When I declare a new instance of SharpSpringService and place the account ID and secret key as parameters, I get a message: "Expected SharpSpring, got string". I also see an Internal Server 500 Error in the Chrome dev consoles that seems to be a result of creating an instance of this class.
I'm not sure why the parameters are expected to be "SharpSpring" as they should be accountID and secretkey.
Here is the SharpSpringService class:
private $authError = false;
private $accountID = null;
private $secretKey = null;
/**
* SharpSpringService constructor.
* #param $accountID SharpSpring Account ID
* #param $secretKey SharpSpring Secret Key
*/
public function __construct($accountID, $secretKey)
{
$this->accountID = $accountID;
$this->secretKey = $secretKey;
}
public function hasAuthError() {
return $this->authError;
}
public function makeCall($method, $params = []) {
$requestID = session_id();
$accountID = $this->accountID;
$secretKey = $this->secretKey;
$data = array(
'method' => $method,
'params' => $params,
'id' => $requestID,
);
$queryString = http_build_query([
'accountID' => $accountID,
'secretKey' => $secretKey
]);
$url = "http://api.sharpspring.com/pubapi/v1/?$queryString";
$data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
));
$result = curl_exec($ch);
curl_close($ch);
$resultObj = json_decode($result);
if ($resultObj->error != null) {
throw new \Exception($result->error);
}
return $resultObj;
}
}
And here is the function in functions.php that is referencing the class:
function get_memberships_callback(){
$newsListID = 550280195;
$listName = "NewsList";
$contactEmail = $_POST['contactemail'];
$sharpSpringService = new SharpSpringService('[redacted]', '[redacted]'); //this is where the code chokes
$return = [];
if($contactEmail != null && $contactEmail !=""){
$lists = $sharpSpringService->makeCall('getListMemberships', [
'emailAddress' => $contactEmail,
]);
if (count($lists) > 0) {
$listArray = json_decode(json_encode($lists), true);
$inNewsList = false;
foreach($listArray as $list){
if($list = $newsListID){
//the user is subscribed to the news list
$inNewsList = true;
$converted_result = ($inNewsList) ? 'true' : 'false';
}
}
}
$return[] = array(
"status" => $converted_result,
"list" => $listName
);
return json_encode($return);
}
else{
return $return;
}
die();
}

For calling numerous files, it is sometimes convenient to define a constant:
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'includes/admin-page.php');
include( MY_PLUGIN_PATH . 'includes/classes.php');

Related

How to send variable value from one function to other function in a different page

I'm new to php oop and I wanted to send the variable value from one function to another in a different page. So, currently I have this one function in one page that I want to send the data to the other function in a different page. Is that even possible perhaps?
Here's the first function in sendData.php
public function main($data) {
$settings = new Settings();
$hash_code = md5('standard' . '10068' . '08f94110d5697a2497511594c31704d0' .'3.00');
$std_post = array(
'apitype'=>'standard', //fix value
'apiid'=>'10068', //your api id from ibill
'apiorderid'=>'OPC0001#00000282', //your order id
'apihashcode'=>$hash_code, //generate hash code as above
'apiamount'=>'3.00', //your customer transaction amount
'apiemail'=>'alif4arsenal97#gmail.com'); //your customer email
$callbackJSON = json_encode($std_post);
$url = 'https://ibill.my/merchant/?ng=callback_api'; //link need to send data
$ch = curl_init($url); // where to post
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $callbackJSON);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = "Cache-Control: no-cache";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$results = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
//echo $results;
$objJSON = json_decode($results); //decode json result
//should return 'SUCCESS'
$callback_status = $objJSON->{'callback_status'}; //callback Status
$message = $objJSON->{'message'}; //callback Message
//Refer on statuspage.php
$std_status_code = $objJSON->{'std_status_code'}; //payment status code
$std_status = $objJSON->{'std_status'}; //payment status
$std_order_id = $objJSON->{'std_order_id'}; //your order id
$std_purchase_code = $objJSON->{'std_purchase_code'}; //ibill transaction id
$std_amount = $objJSON->{'std_amount'}; //transaction amount
$std_datepaid = $objJSON->{'std_datepaid'}; //transaction date time
//Hash code for security
$std_hash_code = $objJSON->{'std_hash_code'}; //Hash code
$hash_code = md5('08f94110d5697a2497511594c31704d0'.'10068'.$std_order_id.$std_amount); //hash code format
$data = [
'callback_status' => $callback_status,
'message' => $message,
'std_status_code' => $std_status_code,
'std_status' => $std_status,
'std_order_id' => $std_order_id,
'std_purchase_code' => $std_purchase_code,
'std_amount' => $std_amount,
'std_datepaid' => $std_datepaid,
'std_hash_code' => $std_hash_code,
'hash_code' => $hash_code
];
processPayment($data);
}
Here's the second function in a different that I wanted the data in the first page to be send to which is test.php
public function processPayment($data)
{
if (!isset($data['std_status_code'])) return false;
if (!isset($data['std_hash_code'])) return false;
$settings = new Settings();
$sale_id = (int) substr($data['std_order_id'], 8);
$sale = Sales::get($sale_id);
if (empty($sale)) return false;
if ($sale['status'] == 1) return $sale;
if ($sale['payment_method'] !== 'ibill' || $sale['status'] != 0) return false;
$sale_uid = $sale['uid'];
$sale_method = $sale['method'];
$paid_amount = bcadd($sale['total_amount'], $sale['handling_charge'], 2);
// Verify the data integrity sent by iBill
$hash = md5($settings->ibill_secret_key . $settings->ibill_merchant_id . $data['std_order_id'] . $data['std_amount']);
$payment_processor_status = -1;
$sale_status = 0;
// Check provided hash and status
if ($hash === $data['std_hash_code'] && $data['std_status_code'] == 00) {
$payment_processor_status = 1;
$sale_status = 1;
}
if ($sale_status === 0) {
if ($data['std_status_code'] != 00) {
$data['std_status'] = '<span style="color: red">' . $data['std_status'] . '</span>';
}
if ($data['std_hash_code'] !== $hash) {
$data['std_hash_code'] = '<span style="color: red">' . $data['std_hash_code'] . '</span>';
}
}
// Prepare updated sale data
$now = new DateTime();
$sale = [
'payment_processor_status' => $payment_processor_status,
'payment_processor_data' => $data,
'payment_time' => $now->format('g:i:s A'),
'payment_date' => $now->format('d-m-Y')
];
Sales::update($sale_id, $sale);
if ($sale_status === 1) {
Sales::confirmSale($sale_id, false);
}
return ['uid' => $sale_uid, 'method' => $sale_method];
}
Those functions are class methods, not only functions.
you can use them (or pass data from one to another) by creating instances of their classes. for example something like this:
class one {
public function f1($data) {
// do something
$instance = new two();
$instance->f2($data);
}
}
class two {
public function f2($data) {
// do something else
}
}
I hope it would work for you.

Fatal error: Uncaught Error: Call to undefined function app_create()

I am trying to use serverPilot API from my website. I have created simple functions like below for sample usage but its giving me error like below
Fatal error: Uncaught Error: Call to undefined function app_create()
I am new in PHP and don't know proper method to declare and use functions. Let me know what I am missing in this? My full PHP code is like below
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createApp'])){
$name = "sampleName";
$name = "hello";
$runtime ="php5.5";
$password = "Test#123";
$domains = array("www.example.com","example2.com");
app_create( $name, $sysuserid, $runtime, $domains = array());
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createDb'])){
$id = 1;
$name = "hello";
$username ="testuser";
$password = "Test#123";
database_create( $id, $name, $username, $password );
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createUser'])){
$id = 1;
$name = "hello";
$password = "Test#123";
sysuser_create( $id, $name, $password = NULL )();
}
class ServerPilot {
// variables
public $apiID = "";
public $apiKey = "";
public $decode;
// constants
const SP_API_ENDPOINT = 'https://api.serverpilot.io/v1/';
const SP_USERAGENT = 'ServerPilot-PHP/1.0';
const SP_HTTP_METHOD_POST = 'post';
const SP_HTTP_METHOD_GET = 'get';
const SP_HTTP_METHOD_DELETE = 'delete';
// error constants
const SP_MISSING_CONFIG = 'Missing config data';
const SP_MISSING_API = 'You must provide API credentials';
const SP_CURL_ERROR = 'Curl error code returned ';
public function __construct( $config = array() ) {
if( empty($config) ) throw new Exception(ServerPilot::SP_MISSING_CONFIG);
if( !isset($config['id']) || !isset($config['key']) ) throw new Exception(ServerPilot::SP_MISSING_API);
$this->apiID = $config['id'];
$this->apiKey = $config['key'];
$this->decode = ( isset($config['decode']) ) ? $config['decode'] : true;
}
public function sysuser_create( $id, $name, $password = NULL ) {
$params = array(
'serverid' => $id,
'name' => $name);
if( $password )
$params['password'] = $password;
return $this->_send_request( 'sysusers', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function app_create( $name, $sysuserid, $runtime, $domains = array() ) {
$params = array(
'name' => $name,
'sysuserid' => $sysuserid,
'runtime' => $runtime);
if( $domains )
$params['domains'] = $domains;
return $this->_send_request( 'apps', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function database_create( $id, $name, $username, $password ) {
$user = new stdClass();
$user->name = $username;
$user->password = $password;
$params = array(
'appid' => $id,
'name' => $name,
'user' => $user);
return $this->_send_request( 'dbs', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
private function _send_request( $url_segs, $params = array(), $http_method = 'get' )
{
// Initialize and configure the request
$req = curl_init( ServerPilot::SP_API_ENDPOINT.$url_segs );
curl_setopt( $req, CURLOPT_USERAGENT, ServerPilot::SP_USERAGENT );
curl_setopt( $req, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $req, CURLOPT_USERPWD, $this->apiID.':'.$this->apiKey );
curl_setopt( $req, CURLOPT_RETURNTRANSFER, TRUE );
// Are we using POST or DELETE? Adjust the request accordingly
if( $http_method == ServerPilot::SP_HTTP_METHOD_POST ) {
curl_setopt( $req, CURLOPT_HTTPHEADER, array('Content-Type: application/json') );
curl_setopt( $req, CURLOPT_POST, TRUE );
curl_setopt( $req, CURLOPT_POSTFIELDS, json_encode($params) );
}
if( $http_method == ServerPilot::SP_HTTP_METHOD_DELETE ) {
curl_setopt( $req, CURLOPT_CUSTOMREQUEST, "DELETE" );
}
// Get the response, clean the request and return the data
$response = curl_exec( $req );
$http_status = curl_getinfo( $req, CURLINFO_HTTP_CODE );
curl_close( $req );
// Everything when fine
if( $http_status == 200 )
{
// Decode JSON by default
if( $this->decode )
return json_decode( $response );
else
return $response;
}
// Some error occurred
$data = json_decode( $response );
// The error was provided by serverpilot
if( property_exists( $data, 'error' ) && property_exists( $data->error, 'message' ) )
throw new ServerPilotException($data->error->message, $http_status);
// No error as provided, pick a default
switch( $http_status )
{
case 400:
throw new ServerPilotException('We couldn\'t understand your request. Typically missing a parameter or header.', $http_status);
break;
case 401:
throw new ServerPilotException('Either no authentication credentials were provided or they are invalid.', $http_status);
break;
case 402:
throw new ServerPilotException('Method is restricted to users on the Coach or Business plan.', $http_status);
break;
case 403:
throw new ServerPilotException('Forbidden.', $http_status);
break;
case 404:
throw new ServerPilotException('You requested a resource that does not exist.', $http_status);
break;
case 409:
throw new ServerPilotException('Typically when trying creating a resource that already exists.', $http_status);
break;
case 500:
throw new ServerPilotException('Something unexpected happened on ServerPilot\'s end.', $http_status);
break;
default:
throw new ServerPilotException('Unknown error.', $http_status);
break;
}
}
}
?>
<html>
<body>
<form action="server.php" method="post">
<input type="submit" name="createApp" value="Create APP" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createDb" value="Create DB" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createUser" value="Create USER" />
</form>
</body>
</html>
Its giving error in all three functions same. Letme know if someone can help me for come out from this issue, I am trying from last two hours and its not working.
Thanks
You can not access class function directly like this.You need to create class object first and then call the function with object variable.
It's better to save class code in a separate file and include it in the above give file at the top to avoid errors.
E.g:
// $config as array, You need it to set in construct method.check construct method.
$config = [
"id" => ENTER_ID,
"key" => ENTER_KEY,
"decode" => true, //Optional you can leave this ,default is true anyway.
];
$ServerPilot_Obj = New ServerPilot($config);
$ServerPilot_Obj->app_create( $name, $sysuserid, $runtime, $domains = array());

PHP Accessing one array from class

I'm trying to access a single value of an array, I can't seem to get it right. This is the code:
$socialCounts = new socialNetworkShareCount(array(
'url' => 'http://facebook.com/',
'facebook' => true,
'buffer' => true,
'pinterest' => true,
'linkedin' => true,
'google' => true
));
print_r($socialCounts->getShareCounts());
Which Returns the following:
{"facebookshares":52132062,"facebooklikes":0,"pinterestshares":243942,"linkedinshares":4708,"googleplusones":0,"buffershares":207477,"total":52588189}
How can I access the vaule of each individual Item? For example, if I'd like to echo the facebook shares value.
And this is the full class if you need:
class socialNetworkShareCount{
public $shareUrl;
public $socialCounts = array();
public $facebookShareCount = 0;
public $facebookLikeCount = 0;
public $twitterShareCount = 0;
public $bufferShareCount = 0;
public $pinterestShareCount = 0;
public $linkedInShareCount = 0;
public $googlePlusOnesCount = 0;
public function __construct($options){
if(is_array($options)){
if(array_key_exists('url', $options) && $options['url'] != ''){
$this->shareUrl = $options['url'];
}else{
die('URL must be set in constructor parameter array!');
}
// Get Facebook Shares and Likes
if(array_key_exists('facebook', $options)){
$this->getFacebookShares();
$this->getFacebookLikes();
}
// Get Twitter Shares
if(array_key_exists('twitter', $options)){
$this->getTwitterShares();
}
// Get Twitter Shares
if(array_key_exists('pinterest', $options)){
$this->getPinterestShares();
}
// Get Twitter Shares
if(array_key_exists('linkedin', $options)){
$this->getLinkedInShares();
}
// Get Twitter Shares
if(array_key_exists('google', $options)){
$this->getGooglePlusOnes();
}
// Get Buffer Shares
if(array_key_exists('buffer', $options)){
$this->getBufferShares();
}
}elseif(is_string($options) && $options != ''){
$this->shareUrl = $options;
// Get all Social Network share counts if they are not set individually in the options
$this->getFacebookShares();
$this->getFacebookLikes();
$this->getTwitterShares();
$this->getPinterestShares();
$this->getLinkedInShares();
$this->getGooglePlusOnes();
$this->getBufferShares();
}else{
die('URL must be set in constructor parameter!');
}
}
public function getShareCounts(){
$totalShares = $this->getTotalShareCount($this->socialCounts);
$this->socialCounts['total'] = $totalShares;
return json_encode($this->socialCounts);
}
public function getTotalShareCount(array $shareCountsArray){
return array_sum($shareCountsArray);
}
public function getFacebookShares(){
$api = file_get_contents( 'http://graph.facebook.com/?id=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->shares) && $count->shares != '0'){
$this->facebookShareCount = $count->shares;
}
$this->socialCounts['facebookshares'] = $this->facebookShareCount;
return $this->facebookShareCount;
}
public function getFacebookLikes(){
$api = file_get_contents( 'http://graph.facebook.com/?id=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->likes) && $count->likes != '0'){
$this->facebookLikeCount = $count->likes;
}
$this->socialCounts['facebooklikes'] = $this->facebookLikeCount;
return $this->facebookLikeCount;
}
public function getTwitterShares(){
$api = file_get_contents( 'https://api.twitter.com/1.1/urls/count.json?url=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->count) && $count->count != '0'){
$this->twitterShareCount = $count->count;
}
$this->socialCounts['twittershares'] = $this->twitterShareCount;
return $this->twitterShareCount;
}
public function getBufferShares(){
$api = file_get_contents( 'https://api.bufferapp.com/1/links/shares.json?url=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->shares) && $count->shares != '0'){
$this->bufferShareCount = $count->shares;
}
$this->socialCounts['buffershares'] = $this->bufferShareCount;
return $this->bufferShareCount;
}
public function getPinterestShares(){
$api = file_get_contents( 'http://api.pinterest.com/v1/urls/count.json?callback%20&url=' . $this->shareUrl );
$body = preg_replace( '/^receiveCount\((.*)\)$/', '\\1', $api );
$count = json_decode( $body );
if(isset($count->count) && $count->count != '0'){
$this->pinterestShareCount = $count->count;
}
$this->socialCounts['pinterestshares'] = $this->pinterestShareCount;
return $this->pinterestShareCount;
}
public function getLinkedInShares(){
$api = file_get_contents( 'https://www.linkedin.com/countserv/count/share?url=' . $this->shareUrl . '&format=json' );
$count = json_decode( $api );
if(isset($count->count) && $count->count != '0'){
$this->linkedInShareCount = $count->count;
}
$this->socialCounts['linkedinshares'] = $this->linkedInShareCount;
return $this->linkedInShareCount;
}
public function getGooglePlusOnes(){
if(function_exists('curl_version')){
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, "https://clients6.google.com/rpc" );
curl_setopt( $curl, CURLOPT_POST, 1 );
curl_setopt( $curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $this->shareUrl . '","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]' );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-type: application/json' ) );
$curl_results = curl_exec( $curl );
curl_close( $curl );
$json = json_decode( $curl_results, true );
$this->googlePlusOnesCount = intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}else{
$content = file_get_contents("https://plusone.google.com/u/0/_/+1/fastbutton?url=".urlencode($_GET['url'])."&count=true");
$doc = new DOMdocument();
libxml_use_internal_errors(true);
$doc->loadHTML($content);
$doc->saveHTML();
$num = $doc->getElementById('aggregateCount')->textContent;
if($num){
$this->googlePlusOnesCount = intval($num);
}
}
$this->socialCounts['googleplusones'] = $this->googlePlusOnesCount;
return $this->googlePlusOnesCount;
}}
According to the class definition, you don't need to invoke getShareCounts(). It looks like that method is perhaps used to provide some lower end API functionality. I don't think it's meant for your use case.
All of the below public variables are accessible and filled in once the constructor has run.
public $facebookShareCount = 0;
public $facebookLikeCount = 0;
public $twitterShareCount = 0;
public $bufferShareCount = 0;
public $pinterestShareCount = 0;
public $linkedInShareCount = 0;
public $googlePlusOnesCount = 0;
So you can access them like so:
$socialCounts = new socialNetworkShareCount(array(
'url' => 'http://facebook.com/',
'facebook' => true,
'buffer' => true,
'pinterest' => true,
'linkedin' => true,
'google' => true
));
print_r($socialCounts->facebookShareCount); // facebook shares
print_r($socialCounts->facebookLikeCount); // facebook likes
mixed json_decode ( string $json [, bool $assoc = false [, int $depth
= 512 [, int $options = 0 ]]] )
Source.
Since your json is an object, json_decode($yourparam) will return an stdClass by default, which will have public members. Since you would like to use an associated array instead, you need to call something like json_decode($yourparam, true), which will return an associated array, since the second parameter is a boolean value determined by your intention whether you want an associated array as result, default value being false.

How to find out what Curl values to enter in WP remote posting script

Found this handy little script that uses Curl and PHP to use the Wordpress XML-RPC function to post directly to my Wordpress blog. I think I have figured out where to enter most information, but there are two values I just can't figure out (not with any amount of Google searching either - so far).
Below I put the entire script, which others may use - provided by http://blog.artooro.com/2012/09/03/wordpress-api-xml-rpc-new-easy-to-use-php-class/
The two values I can't figure out are "ch" and "execute". Not sure if this is a Curl value or a PHP value.
class WordPress {
private $username;
private $password;
private $endpoint;
private $blogid;
private $ch;
public function __construct($username, $password, $endpoint, $blogid = 1) {
$this->myusername = $username;
$this->mypassword = $password;
$this->my-site.com/xmlrpc.php = $endpoint;
$this->1 = $blogid;
$this->ch = curl_init($this->my-site.com/xmlrpc.php);
curl_setopt($this->ch, CURLOPT_HEADER, false);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
}
private function execute($request) {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($this->ch);
$result = xmlrpc_decode($response);
if (is_array($result) && xmlrpc_is_fault($result)) {
throw new Exception($result['faultString'], $result['faultCode']);
}
else {
return $result;
}
}
public function publish_post($title, $content, array $tags, array $categories, $status = 'publish', $date = Null) {
// Set datetime for post
if ($date == Null) {
$post_date = date("Ymd\TH:i:s", time());
}
else {
$post_date = $date;
}
xmlrpc_set_type($post_date, 'datetime');
$params = array(
$this->id,
$this->myusername,
$this->mypassword,
array(
'post_type' => 'post',
'post_status' => $status,
'post_title' => $title,
'post_content' => $content,
'post_date' => $post_date,
'terms_names' => array('category' => $categories, 'post_tag' => $tags)
)
);
$request = xmlrpc_encode_request('wp.newPost', $params);
$response = $this->execute($request);
return $response;
}
}
$this->ch = Curl Handle, its the property that will hold the curl request handle. Its private as it will not be used outside of the class.
$this->execute() = Is the class method that will execute the curl request and return the result. Its private as it will not be used outside of the class.
Both are part of the class and not part of PHP internals.
Also:
I see a couple of problems with the code provided:
$this->my-site.com/xmlrpc.php = $endpoint; should be
$this->endpoint = $endpoint;
$this->1 = $blogid; should be $this->blogid = $blogid;
Plus change references to them properties within the publish_post() method.
Fixed code:
<?php
/*Usage:*/
$wordpress = new WordPress($username, $password, 'my-site.com/xmlrpc.php', 1);
$wordpress->publish_post(...);
class WordPress {
private $username;
private $password;
private $endpoint;
private $blogid;
private $ch;
public function __construct($username, $password, $endpoint, $blogid = 1) {
$this->myusername = $username;
$this->mypassword = $password;
$this->endpoint = $endpoint;
$this->blogid = $blogid;
$this->ch = curl_init($this->endpoint);
curl_setopt($this->ch, CURLOPT_HEADER, false);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
}
private function execute($request) {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($this->ch);
$result = xmlrpc_decode($response);
if (is_array($result) && xmlrpc_is_fault($result)) {
throw new Exception($result['faultString'], $result['faultCode']);
}
else {
return $result;
}
}
public function publish_post($title, $content, array $tags, array $categories, $status = 'publish', $date = Null) {
// Set datetime for post
if ($date == Null) {
$post_date = date("Ymd\TH:i:s", time());
}
else {
$post_date = $date;
}
xmlrpc_set_type($post_date, 'datetime');
$params = array(
$this->blogid,
$this->myusername,
$this->mypassword,
array(
'post_type' => 'post',
'post_status' => $status,
'post_title' => $title,
'post_content' => $content,
'post_date' => $post_date,
'terms_names' => array('category' => $categories, 'post_tag' => $tags)
)
);
$request = xmlrpc_encode_request('wp.newPost', $params);
$response = $this->execute($request);
return $response;
}
}
?>
hope it helps

How to get Citrix's Goto Meeting Access Token

Hi i am trying to get Goto meeting OAuth access token via php curl. but it returns nothing when i make a call. please guide me how i can get it, Code is given below.
$api_key = "123456";
$redirect_url = urlencode("URL");
$webinar_url = "https://api.citrixonline.com/oauth/authorize?client_id=".$api_key."&redirect_uri=".$redirect_url;
function getWebinarData($link)
{
$headers = array(
"HTTP/1.1",
"Content-type: application/json",
"Accept: application/json"
);
$curl = curl_init($link);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //2
$response = curl_exec($curl);
echo "<pre>DATA: ";print_r($response);echo "</pre>";
curl_close($curl);
return $response;
}
/**
* goto api
* Author: Ahad Ali
* Date: valentines day 2013
* Classes Curl, OAuth, GotoTraining
*/
define ("API_KEY", "");
define ("REDIRECT_URL","");
define ("AUTH_AUTOLOGIN_URL","https://developer.citrixonline.com/oauth/g2t/authorize.php");
define ("AUTH_EXCHANGE_URL", "https://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code=<CODE>&client_id=" . API_KEY);
define ("MANAGE_TRAINING_URL","https://api.citrixonline.com/G2T/rest/organizers/<ORGANIZERKEY>/trainings");
class Curl
{
public $result;
public function __construct()
{
}
public function request($url, $data="", $method="get", $headers="")
{
$ch = curl_init();
// this is autologiM USING CURL POST
// avoiding the redirect to gotos site where it asks for email and password and redirects back to the URL with a code
curl_setopt($ch, CURLOPT_URL, $url);
if($method == "post")
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, true);
}
if($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->result = (string) curl_exec($ch);
curl_close($ch);
return $this->result;
}
public function __destruct()
{
}
}
class OAuth
{
public $autologin_url;
public $exchange_url;
public $code;
public $auth_result;
//https://api.citrixonline.com/oauth/authorize?client_id= used this URL to get all the field names
public $login_data = array(
'emailAddress' => '',
'password' => '',
'client_id' => '',
'access_type'=> 'G2T',
'app_name' => '',
'redirect_uri' => '',
'submitted' => 'form_submitted',
);
public function __construct($autologin_url = AUTH_AUTOLOGIN_URL, $exchange_url = AUTH_EXCHANGE_URL, $apikey=API_KEY)
{
$this->autologin_url = $autologin_url;
$this->exchange_url = $exchange_url;
$this->login_data['client_id'] = $apikey;
}
public function authorize()
{
$this->getCode();
$this->exchangeCodeForAccessToken();
}
public function getCode()
{
$curl = new Curl();
$result = $curl->request($this->autologin_url, $this->login_data, "post");
$arr = explode("\n", $result);
foreach($arr as $k=>$v)
{
if(strstr($v,"Location: http:"))
$return_url = $v;
}
$query = trim(parse_url($return_url, PHP_URL_QUERY));// adds one unnecessary _ (underscore) at the end of the query string
$this->code = substr($query, 5, (strlen($query) - 6));//starting from 5 get me ...number of chars
}
function exchangeCodeForAccessToken()
{
$this->exchange_url = str_replace("<CODE>", $this->code, $this->exchange_url);
$curl = new Curl();
$result = $curl->request($this->exchange_url);
$this->auth_result = json_decode($result);
}
public function __destruct()
{
}
}
class GotoTraining extends OAuth
{
public $manage_training_url;
public $training_result;
public $error_list = array("AuthFailure", "AccessDenied", "ExpiredToken", "InternalError", "InvalidRequest", "InvalidMethod", "MissingToken", "NoSuchTraining", "InvalidToken");
public function __construct($url = MANAGE_TRAINING_URL)
{
$this->manage_training_url = $url;
parent::__construct();
}
/**
*Arguement List for goto CreateTraining service
* [name] => Representational State Transfer 101
[description] => The REST-ful way to APIs.
[timeZone] => America/Los_Angeles
[times] => Array
(
[0] => stdClass Object
(
[startDate] => 2011-09-08T18:25:00Z
[endDate] => 2011-09-08T19:25:00Z
)
[1] => stdClass Object
(
[startDate] => 2011-09-09T18:25:00Z
[endDate] => 2011-09-09T19:25:00Z
)
)
[registrationSettings] => stdClass Object
(
[disableWebRegistration] => false
[disableConfirmationEmail] => false
)
[organizers] => Array
(
[0] => 6512477
[1] => 38712
[2] => 9876466
)
*/
public function createTraining($name, $desc, $times)
{
$registrationSettings["disableWebRegistration"] = "false";
$registrationSettings["disableConfirmationEmail"] = "false";
$json["name"] = $name;
$json["description"] = $desc;
$json["timeZone"] = "Australia/Sydney";
$json["times"] = $times;//array for startDate, endDate
$json["registrationSettings"] = $registrationSettings;
$json["organizers"][0] = $this->auth_result->organizer_key;
$this->manage_training_url = str_replace("<ORGANIZERKEY>", $this->auth_result->organizer_key, $this->manage_training_url);
$json = json_encode($json);
//$post_data[] = "Authorization:OAuth oauth_token=" . $this->auth_result->access_token;
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: OAuth oauth_token=' . $this->auth_result->access_token
);
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$curl = new Curl();
$this->training_result = $curl->request($this->manage_training_url, $json, "post", $headers);
$arr = explode("\n", $this->training_result);
$this->webCode = trim($arr[count($arr)-1], '"');
$this->checkError();
return $this->webCode;
}
public function checkError()
{
foreach($this->error_list as $val)
{
if(strstr($this->training_result, $val))
$this->webCode = $val;
}
return 0;
}
}

Categories