I am trying to but the prints from this php code into seperate html div's so I can customize them with css. I got a css file made and it shows but everything is printed out into one div called body class=" hasGoogleVoiceExt".
<?php
class Bot {
public $botHost = '127.0.0.1';
public $botPort = 8087;
public $botId = NULL;
public $token = NULL;
public function __construct($botHost = '127.0.0.1', $botPort = 8087, $botId = NULL) {
$this->botHost = $botHost;
$this->botPort = $botPort;
if ($botId == NULL) {
$botId = $this->DefaultBot();
}
$this->botId = $botId;
}
public function DefaultBot() {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/botId',
CURLOPT_RETURNTRANSFER => 1
));
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data, TRUE);
return $json['defaultBotId'];
}
public function Login($username, $password) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/bot/login',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POSTFIELDS => json_encode(array('username' => $username, 'password' => $password, 'botId' => $this->botId)),
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
));
$data = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 200) return NULL;
$this->token = json_decode($data, TRUE)['token'];
}
public function GetInstances() {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/bot/instances',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Authorization: bearer '.$this->token)
));
$data = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 200) return NULL;
$json = json_decode($data, TRUE);
return $json;
}
public function GetInstanceStatus($instanceId) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/bot/i/'.$instanceId.'/status',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Authorization: bearer '.$this->token)
));
$data = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 200) return NULL;
$json = json_decode($data, TRUE);
return $json;
}
}
$bot = new Bot('127.0.0.1', 8087);
$bot->Login('admin', 'foobar');
$instances = $bot->GetInstances();
for ($i = 0; $i < count($instances); $i++) {
$info = $bot->GetInstanceStatus($instances[$i]['uuid']);
if ($info['currentTrack'] != NULL && $info['playing']) {
printf("%s is playing %s by %s\n", $instances[$i]['nick'], $info['currentTrack']['title'], $info['currentTrack']['artist']);
} else {
printf("%s is not playing anything right now\n", $instances[$i]['nick']);
}
echo '<link href="botcss/styles.css" rel="stylesheet" type="text/css" />';
}
I'm currently testing it out here http://theunlighted.com/nowplaying.php
First things first: Your <link [...]> needs to be output before the for() loop.
Secondly, to output divs in a way (that I think you're meaning to do) is simple:
for($i = 0; $i < 123; $i++) {
echo '<div class="foo foo_'.$i.'">';
// do other output here.
echo '</div>';
}
Related
after user fill form of his or her information it create some sessions that i need kill all sessions in callback page but it dont work by destroy sessions or unset sessions.
after fill information page we have 3 pages as bellow.
payment.php
<?php session_start();
require_once('variables.php');
require_once('../includes/config.php');
$stmt = $db->prepare('SELECT * FROM order_main WHERE name = :name and phone=:phone');
if($stmt->execute(array(':name' => $_SESSION['post-data']['name'], ':phone' => $_SESSION['post-data']
['phone'] ) ));
while($row = $stmt->fetch()){
//if($code == $row['code']){
//if(!empty($_POST['code'])){
$_SESSION['order_id'] = $row['order_id'];
//}
// }
}
$order_id = $_SESSION['order_id'];
$amount = $_SESSION['total'];
echo $_SESSION['order_id'];
$_SESSION['order_id']=3;
echo $_SESSION['post-data']['name'];
echo $_SESSION['post-data']['order_desc'];
$name = $_SESSION['post-data']['name'];
$phone = $_SESSION['post-data']['phone'];
$order_desc = $_SESSION['post-data']['order_desc'];
$params = array(
'order_id' => $order_id ,
'amount' => 10000,
'phone' => $phone,
'name' => $name,
'desc' => $order_desc,
'callback' => URL_CALLBACK,
);
idpay_payment_create($params);
/**
* #param array $params
* #return bool
*/
function idpay_payment_create($params) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_PAYMENT);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) || empty($result->link)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
//.Redirect to payment form
header('Location:' . $result->link);
}
variables.php
<?php session_start();
define('URL_CALLBACK', 'http://www.siteaddress.org/blog/php-simple-master/callback.php');
define('URL_PAYMENT', 'https://api.idpay.ir/v1.1/payment');
define('URL_INQUIRY', 'https://api.idpay.ir/v1.1/payment/inquiry');
define('URL_VERIFY', 'https://api.idpay.ir/v1.1/payment/verify');
define('APIKEY', 'xxxxx...');
define('SANDBOX', 1);
callback.php(i want destroy some or all sessions here but cant)
<?php session_start();
require_once('variables.php');
require_once('config.php');
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$response = $_POST;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$response = $_GET;
}
if (empty($response['status']) ||
empty($response['id']) ||
empty($response['track_id']) ||
empty($response['order_id'])) {
return FALSE;
}
if ($response['status'] != 10) {
print idpay_payment_get_message($response['status']);
}
// if $response['id'] was not in the database return FALSE
$inquiry = idpay_payment_get_inquiry($response);
if ($inquiry) {
$verify = idpay_payment_verify($response);
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_get_inquiry($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_INQUIRY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
if ($result->status == 10) {
return TRUE;
}
print idpay_payment_get_message($result->status);
return FALSE;
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_verify($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_VERIFY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
print idpay_payment_get_message($result->status);
//print '<pre>';
//print_r($result);
//print '</pre>';
$stmt = $db->prepare('UPDATE order_main SET track_id = :track_id, id = :id, order_date=:date
WHERE order_id = :order_id ') ;
$stmt->execute(array(
':track_id' => $_GET['track_id'],
':id' => $_GET['id'],
':date' => $_GET['date'],
':order_id' => $_GET['order_id']
));
}
/**
* #param int $status
* #return string
*/
function idpay_payment_get_message($status) {
switch ($status) {
case 1:
return 'پرداخت انجام نشده است';
case 2:
return 'پرداخت ناموفق بوده است';
case 3:
return 'خطا رخ داده است';
case 10:
return 'در انتظار تایید پرداخت';
case 100:
return 'پرداخت تایید شده است لطفا منتظر بمانید';
case 101:
return 'پرداخت قبلاً تایید شده است';
default:
return 'Error handeling';
}
}
unset ($_SESSION['post-data']['name']);
unset ($_SESSION['post-data']['phone']);
if($_GET['order_desc']){
unset ($_SESSION['post-data']['order_desc']);
}
unset ($_SESSION['order_id']);
unset ($_SESSION['shopping_cart']);
session_start();
session_destroy();
session_commit();
just add session_destroy($_SESSION["your_session]); at the end of your code and same for session_commit
I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.
Hi I am sending the push notification using below code. I've a problem in this code.
<?php
class GCMPushMessage
{
var $url = 'http://android.googleapis.com/gcm/send';
var $serverApiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
var $devices = array();
function setDevices($deviceIds)
{
if (is_array($deviceIds)) {
$this->devices = $deviceIds;
} else {
$this->devices = array(
$deviceIds
);
}
}
function send($message)
{
if (!is_array($this->devices) || count($this->devices) == 0) {
$this->error("No devices set");
}
if (strlen($this->serverApiKey) < 8) {
$this->error("Server API Key not set");
}
$fields = array(
'registration_ids' => $this->devices,
'data' => array(
"msg" => $message
)
);
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
$this->StripResponseFromGCM(json_decode($result));
// Close connection
curl_close($ch);
return $result;
}
function error($msg)
{
echo "Android send notification failed with error:";
echo "\t" . $msg;
exit(1);
}
function StripResponseFromGCM($response)
{
//canonicalID's are the
if ($response->failure == 0 && $response->canonical_ids == 0)
return;
for ($i = 0; $i < sizeof($response->results); $i++) {
if (isset($response->results[$i]->registration_id)) { //if new registrationID is sent as canonicalID
//update this registrationID in the database
} else if ($response->results[$i]->error == "Unavailable") {
// user with index == $i is unavailable
} else if ($response->results[$i]->error == "InvalidRegistration") {
// user with index == $i has InvalidRegistration ID
} else if ($response->results[$i]->error == "NotRegistered") {
// user with index == $i is not registered
}
}
}
}
$msg = array(
'data' => array(
'msg' => 'just a simple message'
)
);
require_once('connection.php');
$sql = mysql_query("select gcmid from gcmid");
$new_array = mysql_fetch_array($sql);
print_r($new_array);
$obj = new GCMPushMessage();
$obj->setDevices($new_array);
$obj->send($msg);
?>
If i put a single id in setDevices method then it is working fine but if i
fetching the gcm ids from database and passing it to method setDevices then the code is not working.It suppose to send push notification to devices but it is not working.
Can anyone help with the following
I'm trying to make a JSON request to a RESTful API. The code below is kindly shared by Wes Furlong
The code seems to be able to decode to JSON fine but sends as a URL encoded string
<?php
function rest_helper($url, $params = null, $verb = 'GET', $format = 'json')
{
$cparams = array(
'http' => array(
'method' => $verb,
'ignore_errors' => true
)
);
if ($params !== null) {
$params = http_build_query($params);
if ($verb == 'POST') {
$cparams['http']['content'] = $params;
} else {
$url .= '?' . $params;
}
}
$context = stream_context_create($cparams);
$fp = fopen($url, 'rb', false, $context);
if (!$fp) {
$res = false;
} else {
// If you're trying to troubleshoot problems, try uncommenting the
// next two lines; it will show you the HTTP response headers across
// all the redirects:
// $meta = stream_get_meta_data($fp);
// var_dump($meta['wrapper_data']);
$res = stream_get_contents($fp);
}
if ($res === false) {
throw new Exception("$verb $url failed: $php_errormsg");
}
switch ($format) {
case 'json':
$r = json_decode($res);
if ($r === null) {
throw new Exception("failed to decode $res as json");
}
return $r;
case 'xml':
$r = simplexml_load_string($res);
if ($r === null) {
throw new Exception("failed to decode $res as xml");
}
return $r;
}
return $res;
}
I need to be able to:
Add a content type of application/json
Convert params to JSON
Can't use curl in this environment
The main thing is the content type -- currently defaults to urlencoded
Any tips or ideas appreciated - Thanks
Latest attempt
function restHelper($url, $params = null, $verb = 'GET', $format = 'json'){
$cparams = array(
'http' => array(
'method' => $verb,
'ignore_errors' => true,
'header' =>"Content-type: application/json \r\n"
)
);
if ($params !== 'None') {
$jparams = json_encode($params);
if ($verb == 'POST') {
$cparams['http']['content'] = $jparams;
} elseif ($verb =='PUT') {
$cparams['http']['content'] = $jparams;
} else {
$params = http_build_query($params);
$url .= '?' . $params;
}
}
Still not working -- API tests fine from REST IDE Seems to be from how the content type is working for JSON
In the end found a way of including CURL in scriptcase.
Here is what worked (prototype)
(Thanks Lorna Jane http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl)
Thanks everyone that looked at this
$service_url = 'http://dev.eventplus.co.nz/api/logon';
$ch = curl_init($service_url);
$data = '[
{
"Header": {
"Username": "testapi#teamprema.co.nz",
"SessionId": "123"
}
},
{
"Config": {}
},
{
"Params": {"Query": {"Password": "test12345"}}
}
]';
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$response = curl_exec($ch);
if ($response === false) {
$info = curl_getinfo($ch);
curl_close($ch);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($ch);
print $response;
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;
}
}