How to get Citrix's Goto Meeting Access Token - php

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;
}
}

Related

database is not updating the values after successful transaction through payment gateway

My website's framework is in CodeIgniter. I have integrated instamojo payment gateway in it. The query inserting the payment id but after successful payment not updating the column value of status to 1 from 0,
This is the block code of paymentcontroller.php
public static function userDataUpdate($trx)
{
$general = getGeneral();
$data = Deposit::where('trx', $trx)->first();
if ($data->status == 0) {
$data->status = 1;
$data->save();
$user = User::find($data->user_id);
$wallet = $user->wallet;
$wallet->balance += $data->amount;
$wallet->save();
$transaction = new Transaction();
$transaction->user_id = $data->user_id;
$transaction->amount = $data->amount;
$transaction->post_balance = $wallet->balance;
$transaction->charge = $data->charge;
$transaction->trx_type = '+';
$transaction->details = 'Deposited via ' . $data->gatewayCurrency()->name;
$transaction->trx = $data->trx;
$transaction->save();
$adminNotification = new AdminNotification();
$adminNotification->user_id = $user->id;
$adminNotification->title = 'Deposit succeeded via '.$data->gatewayCurrency()->name;
$adminNotification->click_url = urlPath('admin.deposit.successful');
$adminNotification->save();
notify($user, 'DEPOSIT_COMPLETE', [
'method_name' => $data->gatewayCurrency()->name,
'method_currency' => $data->method_currency,
'method_amount' => showAmount($data->final_amo),
'amount' => showAmount($data->amount),
'charge' => showAmount($data->charge),
'currency' => $general->cur_text,
'rate' => showAmount($data->rate),
'trx' => $data->trx,
'post_balance' => showAmount($wallet->balance)
]);
}
}
This is the code of processcontroller.php
<?php
namespace App\Http\Controllers\Gateway\Instamojo;
use App\Models\Deposit;
use App\Http\Controllers\Gateway\PaymentController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ProcessController extends Controller
{
/*
* Instamojo Gateway
*/
public static function process($deposit)
{
$basic = getGeneral();
$instaMojoAcc = json_decode($deposit->gatewayCurrency()->gateway_parameter);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://test.instamojo.com/api/1.1/payment-requests/');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
"X-Api-Key:$instaMojoAcc->api_key",
"X-Auth-Token:$instaMojoAcc->auth_token"
)
);
$payload = array(
'purpose' => 'Payment to ' . $basic->sitename,
'amount' => round($deposit->final_amo,2),
'buyer_name' => $deposit->user->username,
'redirect_url' => route('user.deposit.history'),
'webhook' => route('ipn.'.$deposit->gateway->alias),
'email' => $deposit->user->email,
'btc_wallet' => $deposit->trx,
'send_email' => true,
'allow_repeated_payments' => false
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
$response = curl_exec($ch);
curl_close($ch);
$res = json_decode($response);
if (#$res->success) {
if(!#$res->payment_request->id){
$send['error'] = true;
$send['message'] = "Response not given from API. Please re-check the API credentials.";
}else{
$deposit->btc_wallet = $res->payment_request->id;
$deposit->save();
$send['redirect'] = true;
$send['redirect_url'] = $res->payment_request->longurl;
$send['btc_wallet'] = $deposit->trx;
}
} else {
$send['error'] = true;
$send['message'] = "Credentials mismatch. Please contact with admin";
}
return json_encode($send);
}
public function ipn(Request $request)
{
//$this->customLog($request->all(),'Instamojo',true);
$deposit = Deposit::where('btc_wallet', $_POST['payment_request_id'])->orderBy('id', 'DESC')->first();
$instaMojoAcc = json_decode($deposit->gatewayCurrency()->gateway_parameter);
$deposit->detail = $request->all();
$deposit->save();
$imData = $_POST;
$macSent = $imData['mac'];
unset($imData['mac']);
ksort($imData, SORT_STRING | SORT_FLAG_CASE);
$mac = hash_hmac("sha1", implode("|", $imData), $instaMojoAcc->salt);
if ($macSent == $mac && $imData['status'] == "Credit" && $deposit->status == '0') {
PaymentController::userDataUpdate($deposit->trx);
}
}
}
I am unable to find out why the query is not updating the status of the transaction in mysqli.

JWT Server Authentication Signature validation failed for BOX in PHP

I'm facing the issue with validation of JWT Signature in PHP.
Here is my code
// Create token header as a JSON string
$header = ["alg" => "RS256",
"typ" => "JWT",
"kid" => "gnkp02u2"];
$header = json_encode((object) $header);
// Create token payload as a JSON string
$payload = [
"typ" => "jwt",
"kid" => "gnkp02u2",
"iss" => "op63g1amchcxy456oei2tkfk1lg4dbxy",
"aud" => "https://api.box.com/oauth2/token",
"jti" => "4f1g23a12aa854rtyuil",
"exp" => time() + 30,
"sub" => "23527187",
"box_sub_type" => "enterprise"];
$payload = json_encode((object) $payload);
// Encode Header to Base64Url String
$base64UrlHeader = str_replace(["+", "/", "="], ["-", "_", ""],
base64_encode($header));
// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(["+", "/", "="], ["-", "_", ""],
base64_encode($payload));
$headerPayload = $base64UrlHeader . "." . $base64UrlPayload;
//$headerPayload = base64_encode($header) . "." . base64_encode($payload);
// Create Signature Hash
$privateKey = "file://private.key";
try{
$privateKeyResource = openssl_get_privatekey($privateKey,
"73bed4ee2b994f5fdf0ddef660d8f935");
$result = openssl_sign($headerPayload, $signature, $privateKeyResource, OPENSSL_ALGO_SHA256);
if ($result === false)
{
var_dump($result);
throw new RuntimeException("Failed to generate signature: ".implode("\n", getOpenSSLErrors()));
}
$signatureEncoded = base64_encode($signature);
$jwt = "$base64UrlHeader.$base64UrlPayload.$signatureEncoded";
}
catch(Exception $e){
print_r($e->getMessage());
}
print_r( $jwt );`
And it generates
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Imdua3AwMnUyIn0.eyJ0eXAiOiJqd3QiLCJraWQiOiJnbmtwMDJ1MiIsImlzcyI6Im9wNjNnMWFtY2hjeHk0NTZvZWkydGtmazFsZzRkYnh5IiwiYXVkIjoiaHR0cHM6XC9cL2FwaS5ib3guY29tXC9vYXV0aDJcL3Rva2VuIiwianRpIjoiNGYxZzIzYTEyYWE4NTRydHl1aWwiLCJleHAiOjE1MjIwODI5OTUsInN1YiI6IjIzNTI3MTg3IiwiYm94X3N1Yl90eXBlIjoiZW50ZXJwcmlzZSJ9.JMH1sXHrAsT9dURJF/5sOgl2k+qFX/wiqwER4RZwdtxLkLDXDJTzFGZuLPW8JMKqdzntc9hIdc/RHQOla2mi4s1WiGEj/9T1gBPWhjTd4kiZgEenLsZUuLFG77wlzdNPQnm3jON7kM08EfQZU+YYhGDF6JVJ2yH31zkJZqucdbg9Ne43OYPMKEmfa1bKJ3/QmLZXHIEgTYGhh78RsbzViJq3wCqWtUOmksDxCz7/400ZDrmQRH1JIEJW1W6A1oAjPEJVSTniw6a60VVTDXW3WUI0TN68CG5PuNzTXEJcBgnfr1J4yVWeat4rArEyOFsLoyOgBSIu0IHcMRo/V4Md4w==
And I'm using this assertion in curl like this
$ curl https://api.box.com/oauth2/token -d 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=op63g1amchcxy456oei2tkfk1lg4dbxy&client_secret=R7MGxLa7dAZfz5YbXMMPf6a6m8OcYZ2K&assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Imdua3AwMnUyIn0.eyJ0eXAiOiJqd3QiLCJraWQiOiJnbmtwMDJ1MiIsImlzcyI6Im9wNjNnMWFtY2hjeHk0NTZvZWkydGtmazFsZzRkYnh5IiwiYXVkIjoiaHR0cHM6XC9cL2FwaS5ib3guY29tXC9vYXV0aDJcL3Rva2VuIiwianRpIjoiNGYxZzIzYTEyYWE4NTRydHl1aWwiLCJleHAiOjE1MjIwODI5OTUsInN1YiI6IjIzNTI3MTg3IiwiYm94X3N1Yl90eXBlIjoiZW50ZXJwcmlzZSJ9.JMH1sXHrAsT9dURJF/5sOgl2k+qFX/wiqwER4RZwdtxLkLDXDJTzFGZuLPW8JMKqdzntc9hIdc/RHQOla2mi4s1WiGEj/9T1gBPWhjTd4kiZgEenLsZUuLFG77wlzdNPQnm3jON7kM08EfQZU+YYhGDF6JVJ2yH31zkJZqucdbg9Ne43OYPMKEmfa1bKJ3/QmLZXHIEgTYGhh78RsbzViJq3wCqWtUOmksDxCz7/400ZDrmQRH1JIEJW1W6A1oAjPEJVSTniw6a60VVTDXW3WUI0TN68CG5PuNzTXEJcBgnfr1J4yVWeat4rArEyOFsLoyOgBSIu0IHcMRo/V4Md4w==' -X POST
And in response I'm getting this error
{"error":"invalid_grant","error_description":"Signature verification error. The public key identified by \"kid\" must correspond to the private key used for signing."}
Even kid is given and correct
I don't know what I'm doing wrong
I've solved Box JWT Token issue by using https://github.com/firebase/php-jwt repository, and this is working fine.
use \Firebase\JWT\JWT;
class BoxApi
{
public $authorize_url = 'https://account.box.com/api/oauth2/authorize';
public $token_url = 'https://api.box.com/oauth2/token';
public $api_url = 'https://api.box.com/2.0';
public $upload_url = 'https://upload.box.com/api/2.0';
public $access_token;
public $filename;
public $passPhrase;
public $clientId;
public $clientSecret;
public $accessType;
public $accessTypeId;
public $publicKeyId;
public function __construct($filename, $passPhrase, $clientId, $clientSecret, $accessType = "enterprise", $accessTypeId, $publicKeyId)
{
$this->filename = $filename;
$this->passPhrase = $passPhrase;
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->accessType = $accessType;
$this->accessTypeId = $accessTypeId;
$this->publicKeyId = $publicKeyId;
self::getAccessToken();
}
/* Get AccessToken by JWT*/
public function getAccessToken()
{
$private_key_file = $this->filename;
$fp = fopen ($private_key_file, "r");
if (!$fp)
{
die("Unable to open file");
}
$raw_key_data = fread ($fp, filesize ($private_key_file));
fclose ($fp);
$privateKey = openssl_get_privatekey($raw_key_data , $this->passPhrase);
define("FIREBASE_PRIVATE_KEY", $privateKey);
$token = array(
"iss" => $this->clientId,
"aud" => "https://api.box.com/oauth2/token",
"jti" => sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
),
"exp" => time() + 30,
"sub" => $this->accessTypeId,
"box_sub_type" => $this->accessType
);
$jwt = JWT::encode($token, FIREBASE_PRIVATE_KEY, 'RS256', $this->publicKeyId);
$params = 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=' . $this->clientId . '&client_secret=' . $this->clientSecret . '&assertion=' . $jwt;
$token = json_decode(self::httpClient("POST", $this->token_url, $params), true);
print "<pre>";
print_r($token);
print "</pre>";
$this->access_token = $token["access_token"];
}
/* Sets the required before biulding the query */
private function set_opts(array $opts)
{
if (!array_key_exists('access_token', $opts)) {
$opts['access_token'] = $this->access_token;
}
return $opts;
}
/* Builds the URL for the call */
private function build_url($api_func, array $opts = array(), $url = null)
{
print "build uri";
$opts = $this->set_opts($opts);
if (isset($url)) {
$base = $url . $api_func . '?';
} else {
$base = $this->api_url . $api_func . '?';
}
$query_string = http_build_query($opts);
$base = $base . $query_string;
return $base;
}
/* Uploads a file */
public function put_file($filename, $parent_id)
{
$file = defined('PHP_MAJOR_VERSION') && PHP_MAJOR_VERSION >= 5 ? new CurlFile(realpath($filename)) : '#/' . realpath($filename);
$url = $this->build_url('/files/content', array(), $this->upload_url);
$params = array('filename' => $file, 'name' => basename($filename), 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->httpClient("post", $url, $params), true);
}
/* Create a new folder */
public function create_folder($name, $parent_id)
{
$url = $this->build_url("/folders");
$params = array('name' => $name, 'parent' => array('id' => $parent_id));
return json_decode($this->httpClient("post", $url, json_encode($params)), true);
}
/* Modifies the folder details as per the api */
public function update_folder($folder, array $params)
{
$url = $this->build_url("/folders/$folder");
return json_decode($this->httpClient("put", $url, $params), true);
}
/* Shares a folder */
public function share_folder($folder, array $params)
{
$url = $this->build_url("/folders/$folder");
return json_decode($this->httpClient("put", $url, $params), true);
}
/* Shares a file */
public function share_file($file, array $params)
{
$url = $this->build_url("/files/$file");
return json_decode($this->httpClient("put", $url, $params), true);
}
/* Curl Api calls */
private static function httpClient($method, $url, $params = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (strcasecmp($method, "POST") == 0) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
} elseif (strcasecmp($method, "PUT") == 0) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
} elseif (strcasecmp($method, "DELETE") == 0) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
?>

WordPress - Issues with referencing custom PHP class in functions.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');

Call Sharepoint WebService with PHP SoapClient

I extended the PHP SoapClient to use it with NTLM Sharepoint Authentication:
class NTLMSoapClient extends SoapClient {
function __doRequest($request, $location, $action, $version) {
$headers = array(
'Method: POST',
'Connection: Keep-Alive',
'User-Agent: PHP-SOAP-CURL',
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "' . $action . '"',
);
$this->__last_request_headers = $headers;
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_USERPWD, $this->user . ':' . $this->password);
$response = curl_exec($ch);
return $response;
}
function __getLastRequestHeaders() {
return implode("n", $this->__last_request_headers) . "n";
}
public final function __call($methodName, array $methodParams) {
/*
* Is soapClient set? This check may look double here but in later
* developments it might help to trace bugs better and it avoids calls
* on wrong classes if $soapClient got set to something not SoapClient.
*/
if (!$this->soapClient instanceof \SoapClient) {
// Is not set
throw new \Exception('Variable soapClient is not a SoapClient class, have: ' . gettype($this->soapClient), 0xFF);
}
// Is it a "SOAP callback"?
if (substr($methodName, 0, 2) == '__') {
// Is SoapClient's method
$returned = call_user_func_array(array($this->soapClient, $methodName), $methodParams);
} else {
// Call it
$returned = $this->soapClient->__call($methodName, $methodParams);
}
// Return any values
return $returned;
}
}
class SPNTLMSoapClient extends NTLMSoapClient {
protected $user = 'xxxxxx';
protected $password = 'xxxxxxx';
}
class NTLMStream {
private $path;
private $mode;
private $options;
private $opened_path;
private $buffer;
private $pos;
public function stream_open($path, $mode, $options, $opened_path) {
echo "[NTLMStream::stream_open] $path , mode=$mode n";
$this->path = $path;
$this->mode = $mode;
$this->options = $options;
$this->opened_path = $opened_path;
$this->createBuffer($path);
return true;
}
public function stream_close() {
echo "[NTLMStream::stream_close] n";
curl_close($this->ch);
}
public function stream_read($count) {
echo "[NTLMStream::stream_read] $count n";
if (strlen($this->buffer) == 0) {
return false;
}
$read = substr($this->buffer, $this->pos, $count);
$this->pos += $count;
return $read;
}
public function stream_write($data) {
echo "[NTLMStream::stream_write] n";
if (strlen($this->buffer) == 0) {
return false;
}
return true;
}
public function stream_eof() {
echo "[NTLMStream::stream_eof] ";
if ($this->pos > strlen($this->buffer)) {
echo "true n";
return true;
}
echo "false n";
return false;
}
/* return the position of the current read pointer */
public function stream_tell() {
echo "[NTLMStream::stream_tell] n";
return $this->pos;
}
public function stream_flush() {
echo "[NTLMStream::stream_flush] n";
$this->buffer = null;
$this->pos = null;
}
public function stream_stat() {
echo "[NTLMStream::stream_stat] n";
$this->createBuffer($this->path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
public function url_stat($path, $flags) {
echo "[NTLMStream::url_stat] n";
$this->createBuffer($path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
/* Create the buffer by requesting the url through cURL */
private function createBuffer($path) {
if ($this->buffer) {
return;
}
echo "[NTLMStream::createBuffer] create buffer from : $pathn";
$this->ch = curl_init($path);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($this->ch, CURLOPT_USERPWD, $this->user . ':' . $this->password);
echo $this->buffer = curl_exec($this->ch);
echo "[NTLMStream::createBuffer] buffer size : " . strlen($this->buffer) . "bytesn";
$this->pos = 0;
}
}
class SPNTLMStream extends NTLMStream {
protected $user = 'xxxxxxx';
protected $password = 'xxxxxxxx';
}
stream_wrapper_unregister('https');
stream_wrapper_register('https', 'SPNTLMStream') or die("Failed to register protocol");
$wsdl = "https://wxxxxxxxxx?WSDL";
$client = new SPNTLMSoapClient($wsdl);
I succesfully call: "print_r($client->__getFunctions())" and get the following:
Array
(
[0] => CopyIntoItemsLocalResponse CopyIntoItemsLocal(CopyIntoItemsLocal $parameters)
[1] => CopyIntoItemsResponse CopyIntoItems(CopyIntoItems $parameters)
[2] => GetItemResponse GetItem(GetItem $parameters)
[3] => CopyIntoItemsLocalResponse CopyIntoItemsLocal(CopyIntoItemsLocal $parameters)
[4] => CopyIntoItemsResponse CopyIntoItems(CopyIntoItems $parameters)
[5] => GetItemResponse GetItem(GetItem $parameters)
)
My Question now is: How do I call these Methods with $client and parameters,
$client->__call('CopyIntoItems', $params) doesnt work
$client->CopyIntoItems($params) doesnt work
I never get any Response.....
Thx in advance....

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

Categories