We have several GPS installed in different units and I am trying to retrieve the messages using the Wialon's Remote API but i am getting this error, can someone please help me? Thanks a lot!:
{"error":4, "reason":"VALIDATE_PARAMS_ERROR: {itemId: long, timeFrom: uint, timeTo: uint, flags: uint, flagsMask: uint, loadCount: uint}"}
Below is my script:
<?php
include('wialon.php');
$wialon_api = new Wialon();
$token = '{token here}';
$result = $wialon_api->login($token);
$json = json_decode($result, true);
if(!isset($json['error'])){
echo $wialon_api->messages_load_interval('{"itemId":24611387,"lastTime":1073741831,"lastCount":1,"flags":0,"flagMask":0,"loadCount":1}');
$wialon_api->logout();
} else {
echo WialonError::error($json['error']);
}
?>
Here is the Wialon Class which i downloaded from their site:
<?php
/* Classes for working with Wialon RemoteApi using PHP
*
* License:
* The MIT License (MIT)
*
* Copyright:
* 2002-2015 Gurtam, http://gurtam.com
*/
/** Wialon RemoteApi wrapper Class
*/
class Wialon{
/// PROPERTIES
private $sid = null;
private $base_api_url = '';
private $default_params = array();
/// METHODS
/** constructor */
function __construct($scheme = 'https', $host = 'hst-api.wialon.com', $port = '', $sid = '', $extra_params = array()) {
$this->sid = '';
$this->default_params = array_replace(array(), (array)$extra_params);
$this->base_api_url = sprintf('%s://%s%s/wialon/ajax.html?', $scheme, $host, mb_strlen($port)>0?':'.$port:'');
}
/** sid setter */
function set_sid($sid){
$this->sid = $sid;
}
/** sid getter */
function get_sid(){
return $this->sid;
}
/** update extra parameters */
public function update_extra_params($extra_params){
$this->default_params = array_replace($this->default_params, $extra_params);
}
/** RemoteAPI request performer
* action - RemoteAPI command name
* args - JSON string with request parameters
*/
public function call($action, $args){
$url = $this->base_api_url;
if (stripos($action, 'unit_group') === 0) {
$svc = $action;
$svc[mb_strlen('unit_group')] = '/';
} else {
$svc = preg_replace('\'_\'', '/', $action, 1);
}
$params = array(
'svc'=> $svc,
'params'=> $args,
'sid'=> $this->sid
);
$all_params = array_replace($this->default_params , $params);
$str = '';
foreach ($all_params as $k => $v) {
if(mb_strlen($str)>0)
$str .= '&';
$str .= $k.'='.urlencode(is_object($v) || is_array($v) ? json_encode($v) : $v);
}
/* cUrl magic */
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $str
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if($result === FALSE)
$result = '{"error":-1,"message":'.curl_error($ch).'}';
curl_close($ch);
return $result;
}
/** Login
* user - wialon username
* password - password
* return - server response
*/
public function login($token) {
$data = array(
'token' => urlencode($token),
);
$result = $this->token_login(json_encode($data));
$json_result = json_decode($result, true);
if(isset($json_result['eid'])) {
$this->sid = $json_result['eid'];
}
return $result;
}
/** Logout
* return - server responce
*/
public function logout() {
$result = $this->core_logout();
$json_result = json_decode($result, true);
if($json_result && $json_result['error']==0)
$this->sid = '';
return $result;
}
/** Unknonwn methods hadler */
public function __call($name, $args) {
return $this->call($name, count($args) === 0 ? '{}' : $args[0]);
}
}
/** Wialon errorCode to textMessage converter
*/
class WialonError{
/// PROPERTIES
/** list of error messages with codes */
public static $errors = array(
1 => 'Invalid session',
2 => 'Invalid service',
3 => 'Invalid result',
4 => 'Invalid input',
5 => 'Error performing request',
6 => 'Unknow error',
7 => 'Access denied',
8 => 'Invalid user name or password',
9 => 'Authorization server is unavailable, please try again later',
1001 => 'No message for selected interval',
1002 => 'Item with such unique property already exists',
1003 => 'Only one request of given time is allowed at the moment'
);
/// METHODS
/** error message generator */
public static function error($code = '', $text = ''){
$code = intval($code);
if ( isset(self::$errors[$code]) )
$text = self::$errors[$code].' '.$text;
$message = sprintf('%d: %s', $code, $text);
return sprintf('WialonError( %s )', $message);
}
}
?>
Related
I want to run my PHP file without any error but each time I faced some problem. I explained my problem below.
Could any one can give me any suggestion so that I can solve it with a better way!
Thanks all who participate here.
PHP Warning: curl_setopt(): supplied resource is not a valid cURL handle resource in p_detail.php on line 170
PHP Warning: curl_setopt(): supplied resource is not a valid cURL handle resource in p_detail.php on line 171
PHP Warning: curl_setopt(): supplied resource is not a valid cURL handle resource in p_detail.php on line 172
Here is my php file:
$banggoodAPI = new BanggoodAPI();
//Product Detail
$params = [
'product_id'=>1588753,
];
$banggoodAPI->setParams($params);
$result = $banggoodAPI->getProductDetail();
echo '<pre>';
var_dump($result);
class BanggoodAPI {
private $__apiKey = '***';
private $__apiSecret = '**********';
private $__domain = 'https://affapi.banggood.com/';
private $__accessToken = '';
private $__task = '' ;
private $__method = 'GET';
private $__params = array();
private $__lang = 'en-GB';
private $__currency = 'USD';
private $__waitingTaskInfo = array();
private $__ch = null;
private $__curlExpireTime = 10;
/**
* #desc Construct
* #access public
*/
public function __construct(){
$this->__ch = curl_init();
}
/**
* #desc product/detail
* #access public
*/
public function getProductDetail() {
$this->__task = 'product/detail';
$this->__method = 'GET';
$result = $this->__doRequest();
return $result;
}
/**
* #desc set params
* #access public
*/
public function setParams(Array $params) {
if (!empty($params)) {
$this->__params = $params;
}
}
/**
* #desc get access_token
* #access private
*/
private function __getAccessToken($useCache = true) {
//if access_token is empty, send request to get accessToken
if (empty($this->__accessToken)) {
if (!empty($this->__task)) {
$this->__waitingTaskInfo = array(
'task' => $this->__task,
'method' => $this->__method,
'params' => $this->__params,
);
}
$this->__task = 'getAccessToken';
$rand=rand();
$time=time();
$this->__params = [
'api_key' => $this->__apiKey,
'noncestr' => $rand,
'timestamp' => $time,
];
$preArr = array_merge($this->__params, ['api_secret' => $this->__apiSecret]);
ksort($preArr);
$signature=http_build_query($preArr);
$this->__params['signature']=md5($signature);
$this->__method = 'GET';
$result = $this->__doRequest();
if ($result['code'] == 200) {
$this->__accessToken = $result['result']['access_token'];
//resend request
if (!empty($this->__waitingTaskInfo)) {
$this->__task = $this->__waitingTaskInfo['task'];
$this->__params = $this->__waitingTaskInfo['params'];
$this->__method = $this->__waitingTaskInfo['method'];
$this->__waitingTaskInfo = array();
return $this->__doRequest();
}
} else {
$this->__requestError($result);
}
}
}
/**
* #desc handle request error
* #access private
*/
private function __requestError($error) {
var_dump($error);
exit;
}
/**
* #desc send api request
* #access private
*/
private function __doRequest() {
if (empty($this->__params)) {
$this->__requestError(array('params is empty'));
}
if ($this->__task != 'getAccessToken') {
if (empty($this->__accessToken)) {
$this->__getAccessToken();
}
//头部信息
$header = array(
'access-token:'.$this->__accessToken,
);
if (empty($this->__params['lang']))
$this->__params['lang'] = $this->__lang;
if (empty($this->__params['currency']))
$this->__params['currency'] = $this->__currency;
}
$apiUrl = $this->__domain . $this->__task;
if ($this->__method == 'GET') {
$quote = '?';
foreach ($this->__params as $k => $v) {
$apiUrl .= $quote . $k .'='. $v;
$quote = '&';
}
$preStr = http_build_query($this->__params);
}
curl_setopt($this->__ch, CURLOPT_URL, $apiUrl ); //170 line
curl_setopt($this->__ch, CURLOPT_HEADER, 0); //171 line
curl_setopt($this->__ch, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT']); //172 line
curl_setopt($this->__ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->__ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->__ch, CURLOPT_SSL_VERIFYPEER, false);
if ($this->__method == 'POST') {
curl_setopt($this->__ch, CURLOPT_POST, 1 );
curl_setopt($this->__ch, CURLOPT_POSTFIELDS, http_build_query($this->__params));
}
if ($this->__curlExpireTime > 0) {
curl_setopt($this->__ch, CURLOPT_TIMEOUT, $this->__curlExpireTime);
}
if ($header){
curl_setopt($this->__ch, CURLOPT_HTTPHEADER, $header);
}
$result = curl_exec($this->__ch);
if($error=curl_error($this->__ch)){
die($error);
}
curl_close($this->__ch);
$result = json_decode($result, true);
return $result;
}
}
?>
I want to run my PHP file without any error but each time I faced some problem. I explained my problem below.
Could any one can give me any suggestion so that I can solve it with a better way!
Thanks all who participate here.
You are "closing" your curl handle after every request (curl_close($this->__ch);), but only "initializing" it ($this->__ch = curl_init();) once in the constructor.
Once it's been "closed", you can't re-use it for another request. Since you're setting all the options for each request anyway, you probably want to run curl_init() for every request, at the start of the __doRequest method.
I am trying to pull data from API, and getting this error. I have searched same file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known
but did't understand how to fix
file_get_contents(): php_network_getaddresses: getaddrinfo failed:
Name or service not known
Here is my code
<?php namespace AdClass;
use stdClass;
class AdInfo{
private $domain;
private $widget_id;
private $api_key;
private $pub_id;
public function __construct($domain, $widget_id, $api_key, $pub_id)
{
$this->domain = $domain;
$this->widget_id = $widget_id;
$this->api_key = $api_key;
$this->pub_id = $pub_id;
}
public function getDomain()
{
return $this->domain;
}
public function getWidgetId()
{
return $this->widget_id;
}
public function getApiKey()
{
return $this->api_key;
}
public function getPubId()
{
return $this->pub_id;
}
public function getAdContent()
{
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.revcontent.com/api/v1',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'api_key' => $this->api_key,
'pub_id' => $this->pub_id,
'widget_id' => $this->widget_id,
'domain' => $this->domain,
'format' => 'json',
'sponsored_offset' => '0',
'internal_count' => '3',
'internal_offset' => '2'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
}
?>
index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include(dirname(__FILE__).'/AdClass/AdInfo.php');
$domain = "realtimepolitics.com";
$widget_id = XXXX;
$api_key = "XXXXXX";
$pub_id = XXXX;
$adobj = new AdClass\AdInfo($domain, $widget_id, $api_key, $pub_id);
$response = $adobj->getAdContent();
echo "<pre>";
print_r($response);
Issue Fixed with cURL request:
<?php namespace AdClass;
use stdClass;
class AdInfo{
private $domain;
private $widget_id;
private $api_key;
private $pub_id;
private $sponsored_offset;
private $sponsored_count;
private $internal_offset;
private $internal_count;
public function __construct($domain,$widget_id,$sponsored_count=1,$internal_offset=1, $sponsored_offset=0,$internal_count=3)
{
$this->domain = $domain;
$this->widget_id = $widget_id;
$this->api_key = "XXXX";
$this->pub_id = xxxx;
$this->sponsored_offset =$sponsored_offset;
$this->sponsored_count = $sponsored_count;
$this->internal_offset = $internal_offset;
$this->internal_count = $internal_count;
}
public function getAdContent()
{
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://trends.revcontent.com/api/v1/?api_key='.$this->api_key.'&pub_id='.$this->pub_id.'&widget_id='.$this->widget_id.'&domain='.$this->domain.'&format=json&sponsored_count='.$this->sponsored_count.'&sponsored_offset='.$this->sponsored_offset.'&internal_count='.$this->internal_count.'&internal_offset='.$this->internal_offset ,
CURLOPT_USERAGENT => 'cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
}
?>
Main.php
<?php namespace MainApi;
include(dirname(__FILE__).'/../AdClass/AdInfo.php');
use AdClass\AdInfo;
class Main{
private $adObj;
public function __construct($domain,$widget_id,$sponsored_count,$internal_offset, $sponsored_offset,$internal_count)
{
$this->domain = $domain;
$this->widget_id = $widget_id;
$this->sponsored_offset =$sponsored_offset;
$this->sponsored_count = $sponsored_count;
$this->internal_offset = $internal_offset;
$this->internal_count = $internal_count;
$this->adObj = new AdInfo($this->domain,$this->widget_id,$this->sponsored_count,$this->internal_offset, $this->sponsored_offset,$this->internal_count);
}
function getResponse()
{
$response = $this->adObj->getAdContent();
return $response;
}
}
getAds.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include (dirname(__FILE__) . '/MainApi/Main.php');
$domain = "realtimepolitics.com";
$widget_id = $_GET['widget_id']; //97862
$weight = $_GET['w'];
$height = $_GET['h'];
$sponsored_count = 2;
$internal_offset = 2;
$sponsored_offset = 0;
$internal_count = 3;
$main = new MainApi\Main($domain, $widget_id, $sponsored_count, $internal_offset, $sponsored_offset, $internal_count);
$response = $main->getResponse();
$ads_data = json_decode($response);
print_r($ads_data);
I am working on a payment gateway payfort, here I want to pass my dynamic price public $amount = 7150.00; by Url request, but it's not working.
I am new on OOPS so please any one help me.
Static value are working fine.
confirm-order.php
<?php include('header.php') ?>
<?php
$data = $_REQUEST;
$itemname = $data['startfrom'].' - '. $data['stopto'].', Distance : '. $data['distance'].' Km , Duration : '.$data['duration'].' Minutes';
require_once 'PayfortIntegration.php';
$objFort = new PayfortIntegration();
$amount = $objFort->amount;
$currency = $objFort->currency;
$totalAmount = $data['amount'];
$paymentMethod = $_REQUEST['payment_method'];
$objFort->itemName = $itemname;
$objFort->customerEmail = 'abc#gmail.com';
?>
<section class="nav">
<ul>
<li class="lead" >Payment Method</li>
<li class="lead active" > Pay</li>
<li class="lead" > Done</li>
</ul>
</section>
<section class="confirmation">
<label>Confirm Your Order</label>
</section>
<section class="order-info">
<ul class="items">
<span>
<i class="icon icon-bag"></i>
<label class="lead" for="">Your Booking</label>
</span>
<li><?php echo $objFort->itemName ?></li>
</ul>
<ul>
<li>
<div class="v-seperator"></div>
</li>
</ul>
<ul class="price">
<span>
<i class="icon icon-tag"></i>
<label class="lead" for="">price</label>
</span>
<li><span class="curreny">AED</span> <?php echo sprintf("%.2f",$totalAmount);?> </li>
</ul>
<ul class="items">
<span>
<i class="icon icon-bag"></i>
<label class="lead" for="">Payment Method</label>
</span>
<li><?php echo $objFort->getPaymentOptionName($paymentMethod) ?></li>
</ul>
</section>
<?php if($paymentMethod == 'cc_merchantpage') ://merchant page iframe method ?>
<section class="merchant-page-iframe">
<?php
$merchantPageData = $objFort->getMerchantPageData();
$postData = $merchantPageData['params'];
$gatewayUrl = $merchantPageData['url'];
?>
<p>Test card: 4005550000000001<br/>05/17<br/>123</p>
<div class="cc-iframe-display">
<div id="div-pf-iframe" style="display:none">
<div class="pf-iframe-container">
<div class="pf-iframe" id="pf_iframe_content">
</div>
</div>
</div>
</div>
</section>
<?php endif; ?>
<div class="h-seperator"></div>
<section class="actions">
<a class="back" id="btn_back" href="index.php">Back</a>
</section>
<script type="text/javascript" src="vendors/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/checkout.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var paymentMethod = '<?php echo $paymentMethod?>';
//load merchant page iframe
if(paymentMethod == 'cc_merchantpage') {
getPaymentPage(paymentMethod);
}
});
</script>
<?php include('footer.php') ?>
and configuration file is:
PayfortIntegration.php
<?php
/**
* #copyright Copyright PayFort 2012-2016
*
*/
class PayfortIntegration
{
public $gatewayHost = 'https://checkout.payfort.com/';
public $gatewaySandboxHost = 'https://sbcheckout.payfort.com/';
public $language = 'en';
/**
* #var string your Merchant Identifier account (mid)
*/
public $merchantIdentifier = 'XXXXXXXXXXXXXX';
/**
* #var string your access code
*/
public $accessCode = 'XXXXXXXXXXX';
/**
* #var string SHA Request passphrase
*/
public $SHARequestPhrase = 'XXXXXXXXX';
/**
* #var string SHA Response passphrase
*/
public $SHAResponsePhrase = 'XXXXXXXXXX';
/**
* #var string SHA Type (Hash Algorith)
* expected Values ("sha1", "sha256", "sha512")
*/
public $SHAType = 'sha256';
/**
* #var string command
* expected Values ("AUTHORIZATION", "PURCHASE")
*/
public $command = 'AUTHORIZATION';
/**
* #var decimal order amount
*/
public $amount = 7150.00;
/**
* #var string order currency
*/
public $currency = 'AED';
/**
* #var string item name
*/
public $itemName = 'Apple iPhone 6s Plus';
/**
* #var string you can change it to your email
*/
public $customerEmail = 'shiv#srapsware.com';
/**
* #var boolean for live account change it to false
*/
public $sandboxMode = true;
/**
* #var string project root folder
* change it if the project is not on root folder.
*/
public $projectUrlPath = '/pay';
public function __construct()
{
}
public function processRequest($paymentMethod)
{
if ($paymentMethod == 'cc_merchantpage' || $paymentMethod == 'cc_merchantpage2') {
$merchantPageData = $this->getMerchantPageData();
$postData = $merchantPageData['params'];
$gatewayUrl = $merchantPageData['url'];
}
else{
$data = $this->getRedirectionData($paymentMethod);
$postData = $data['params'];
$gatewayUrl = $data['url'];
}
$form = $this->getPaymentForm($gatewayUrl, $postData);
echo json_encode(array('form' => $form, 'url' => $gatewayUrl, 'params' => $postData, 'paymentMethod' => $paymentMethod));
exit;
}
public function getRedirectionData($paymentMethod) {
$merchantReference = $this->generateMerchantReference();
if ($this->sandboxMode) {
$gatewayUrl = $this->gatewaySandboxHost . 'FortAPI/paymentPage';
}
else {
$gatewayUrl = $this->gatewayHost . 'FortAPI/paymentPage';
}
if ($paymentMethod == 'sadad') {
$this->currency = 'SAR';
}
$postData = array(
'amount' => $this->convertFortAmount($this->amount, $this->currency),
'currency' => strtoupper($this->currency),
'merchant_identifier' => $this->merchantIdentifier,
'access_code' => $this->accessCode,
'merchant_reference' => $merchantReference,
'customer_email' => 'test#payfort.com',
//'customer_name' => trim($order_info['b_firstname'].' '.$order_info['b_lastname']),
'command' => $this->command,
'language' => $this->language,
'return_url' => $this->getUrl('route.php?r=processResponse'),
);
if ($paymentMethod == 'sadad') {
$postData['payment_option'] = 'SADAD';
}
elseif ($paymentMethod == 'naps') {
$postData['payment_option'] = 'NAPS';
$postData['order_description'] = $this->itemName;
}
elseif ($paymentMethod == 'installments') {
$postData['installments'] = 'STANDALONE';
$postData['command'] = 'PURCHASE';
}
$postData['signature'] = $this->calculateSignature($postData, 'request');
$debugMsg = "Fort Redirect Request Parameters \n".print_r($postData, 1);
$this->log($debugMsg);
return array('url' => $gatewayUrl, 'params' => $postData);
}
public function getMerchantPageData()
{
$merchantReference = $this->generateMerchantReference();
$returnUrl = $this->getUrl('route.php?r=merchantPageReturn');
if(isset($_GET['3ds']) && $_GET['3ds'] == 'no') {
$returnUrl = $this->getUrl('route.php?r=merchantPageReturn&3ds=no');
}
$iframeParams = array(
'merchant_identifier' => $this->merchantIdentifier,
'access_code' => $this->accessCode,
'merchant_reference' => $merchantReference,
'service_command' => 'TOKENIZATION',
'language' => $this->language,
'return_url' => $returnUrl,
);
$iframeParams['signature'] = $this->calculateSignature($iframeParams, 'request');
if ($this->sandboxMode) {
$gatewayUrl = $this->gatewaySandboxHost . 'FortAPI/paymentPage';
}
else {
$gatewayUrl = $this->gatewayHost . 'FortAPI/paymentPage';
}
$debugMsg = "Fort Merchant Page Request Parameters \n".print_r($iframeParams, 1);
$this->log($debugMsg);
return array('url' => $gatewayUrl, 'params' => $iframeParams);
}
public function getPaymentForm($gatewayUrl, $postData)
{
$form = '<form style="display:none" name="payfort_payment_form" id="payfort_payment_form" method="post" action="' . $gatewayUrl . '">';
foreach ($postData as $k => $v) {
$form .= '<input type="hidden" name="' . $k . '" value="' . $v . '">';
}
$form .= '<input type="submit" id="submit">';
return $form;
}
public function processResponse()
{
$fortParams = array_merge($_GET, $_POST);
$debugMsg = "Fort Redirect Response Parameters \n".print_r($fortParams, 1);
$this->log($debugMsg);
$reason = '';
$response_code = '';
$success = true;
if(empty($fortParams)) {
$success = false;
$reason = "Invalid Response Parameters";
$debugMsg = $reason;
$this->log($debugMsg);
}
else{
//validate payfort response
$params = $fortParams;
$responseSignature = $fortParams['signature'];
$merchantReference = $params['merchant_reference'];
unset($params['r']);
unset($params['signature']);
unset($params['integration_type']);
$calculatedSignature = $this->calculateSignature($params, 'response');
$success = true;
$reason = '';
if ($responseSignature != $calculatedSignature) {
$success = false;
$reason = 'Invalid signature.';
$debugMsg = sprintf('Invalid Signature. Calculated Signature: %1s, Response Signature: %2s', $responseSignature, $calculatedSignature);
$this->log($debugMsg);
}
else {
$response_code = $params['response_code'];
$response_message = $params['response_message'];
$status = $params['status'];
if (substr($response_code, 2) != '000') {
$success = false;
$reason = $response_message;
$debugMsg = $reason;
$this->log($debugMsg);
}
}
}
if(!$success) {
$p = $params;
$p['error_msg'] = $reason;
$return_url = $this->getUrl('error.php?'.http_build_query($p));
}
else{
$return_url = $this->getUrl('success.php?'.http_build_query($params));
}
echo "<html><body onLoad=\"javascript: window.top.location.href='" . $return_url . "'\"></body></html>";
exit;
}
public function processMerchantPageResponse()
{
$fortParams = array_merge($_GET, $_POST);
$debugMsg = "Fort Merchant Page Response Parameters \n".print_r($fortParams, 1);
$this->log($debugMsg);
$reason = '';
$response_code = '';
$success = true;
if(empty($fortParams)) {
$success = false;
$reason = "Invalid Response Parameters";
$debugMsg = $reason;
$this->log($debugMsg);
}
else{
//validate payfort response
$params = $fortParams;
$responseSignature = $fortParams['signature'];
unset($params['r']);
unset($params['signature']);
unset($params['integration_type']);
unset($params['3ds']);
$merchantReference = $params['merchant_reference'];
$calculatedSignature = $this->calculateSignature($params, 'response');
$success = true;
$reason = '';
if ($responseSignature != $calculatedSignature) {
$success = false;
$reason = 'Invalid signature.';
$debugMsg = sprintf('Invalid Signature. Calculated Signature: %1s, Response Signature: %2s', $responseSignature, $calculatedSignature);
$this->log($debugMsg);
}
else {
$response_code = $params['response_code'];
$response_message = $params['response_message'];
$status = $params['status'];
if (substr($response_code, 2) != '000') {
$success = false;
$reason = $response_message;
$debugMsg = $reason;
$this->log($debugMsg);
}
else {
$success = true;
$host2HostParams = $this->merchantPageNotifyFort($fortParams);
$debugMsg = "Fort Merchant Page Host2Hots Response Parameters \n".print_r($fortParams, 1);
$this->log($debugMsg);
if (!$host2HostParams) {
$success = false;
$reason = 'Invalid response parameters.';
$debugMsg = $reason;
$this->log($debugMsg);
}
else {
$params = $host2HostParams;
$responseSignature = $host2HostParams['signature'];
$merchantReference = $params['merchant_reference'];
unset($params['r']);
unset($params['signature']);
unset($params['integration_type']);
$calculatedSignature = $this->calculateSignature($params, 'response');
if ($responseSignature != $calculatedSignature) {
$success = false;
$reason = 'Invalid signature.';
$debugMsg = sprintf('Invalid Signature. Calculated Signature: %1s, Response Signature: %2s', $responseSignature, $calculatedSignature);
$this->log($debugMsg);
}
else {
$response_code = $params['response_code'];
if ($response_code == '20064' && isset($params['3ds_url'])) {
$success = true;
$debugMsg = 'Redirect to 3DS URL : '.$params['3ds_url'];
$this->log($debugMsg);
echo "<html><body onLoad=\"javascript: window.top.location.href='" . $params['3ds_url'] . "'\"></body></html>";
exit;
//header('location:'.$params['3ds_url']);
}
else {
if (substr($response_code, 2) != '000') {
$success = false;
$reason = $host2HostParams['response_message'];
$debugMsg = $reason;
$this->log($debugMsg);
}
}
}
}
}
}
if(!$success) {
$p = $params;
$p['error_msg'] = $reason;
$return_url = $this->getUrl('error.php?'.http_build_query($p));
}
else{
$return_url = $this->getUrl('success.php?'.http_build_query($params));
}
echo "<html><body onLoad=\"javascript: window.top.location.href='" . $return_url . "'\"></body></html>";
exit;
}
}
public function merchantPageNotifyFort($fortParams)
{
//send host to host
if ($this->sandboxMode) {
$gatewayUrl = $this->gatewaySandboxHost . 'FortAPI/paymentPage';
}
else {
$gatewayUrl = $this->gatewayHost . 'FortAPI/paymentPage';
}
$postData = array(
'merchant_reference' => $fortParams['merchant_reference'],
'access_code' => $this->accessCode,
'command' => $this->command,
'merchant_identifier' => $this->merchantIdentifier,
'customer_ip' => $_SERVER['REMOTE_ADDR'],
'amount' => $this->convertFortAmount($this->amount, $this->currency),
'currency' => strtoupper($this->currency),
'customer_email' => $this->customerEmail,
'customer_name' => 'John Doe',
'token_name' => $fortParams['token_name'],
'language' => $this->language,
'return_url' => $this->getUrl('route.php?r=processResponse'),
);
if(isset($fortParams['3ds']) && $fortParams['3ds'] == 'no') {
$postData['check_3ds'] = 'NO';
}
//calculate request signature
$signature = $this->calculateSignature($postData, 'request');
$postData['signature'] = $signature;
$debugMsg = "Fort Host2Host Request Parameters \n".print_r($postData, 1);
$this->log($debugMsg);
if ($this->sandboxMode) {
$gatewayUrl = 'https://sbpaymentservices.payfort.com/FortAPI/paymentApi';
}
else {
$gatewayUrl = 'https://paymentservices.payfort.com/FortAPI/paymentApi';
}
$array_result = $this->callApi($postData, $gatewayUrl);
$debugMsg = "Fort Host2Host Response Parameters \n".print_r($array_result, 1);
$this->log($debugMsg);
return $array_result;
}
/**
* Send host to host request to the Fort
* #param array $postData
* #param string $gatewayUrl
* #return mixed
*/
public function callApi($postData, $gatewayUrl)
{
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
$useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0";
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=UTF-8',
//'Accept: application/json, application/*+json',
//'Connection:keep-alive'
));
curl_setopt($ch, CURLOPT_URL, $gatewayUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_ENCODING, "compress, gzip");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); // The number of seconds to wait while trying to connect
//curl_setopt($ch, CURLOPT_TIMEOUT, Yii::app()->params['apiCallTimeout']); // timeout in seconds
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$response = curl_exec($ch);
//$response_data = array();
//parse_str($response, $response_data);
curl_close($ch);
$array_result = json_decode($response, true);
if (!$response || empty($array_result)) {
return false;
}
return $array_result;
}
/**
* calculate fort signature
* #param array $arrData
* #param string $signType request or response
* #return string fort signature
*/
public function calculateSignature($arrData, $signType = 'request')
{
$shaString = '';
ksort($arrData);
foreach ($arrData as $k => $v) {
$shaString .= "$k=$v";
}
if ($signType == 'request') {
$shaString = $this->SHARequestPhrase . $shaString . $this->SHARequestPhrase;
}
else {
$shaString = $this->SHAResponsePhrase . $shaString . $this->SHAResponsePhrase;
}
$signature = hash($this->SHAType, $shaString);
return $signature;
}
/**
* Convert Amount with dicemal points
* #param decimal $amount
* #param string $currencyCode
* #return decimal
*/
public function convertFortAmount($amount, $currencyCode)
{
$new_amount = 0;
$total = $amount;
$decimalPoints = $this->getCurrencyDecimalPoints($currencyCode);
$new_amount = round($total, $decimalPoints) * (pow(10, $decimalPoints));
return $new_amount;
}
public function castAmountFromFort($amount, $currencyCode)
{
$decimalPoints = $this->getCurrencyDecimalPoints($currencyCode);
//return $amount / (pow(10, $decimalPoints));
$new_amount = round($amount, $decimalPoints) / (pow(10, $decimalPoints));
return $new_amount;
}
/**
*
* #param string $currency
* #param integer
*/
public function getCurrencyDecimalPoints($currency)
{
$decimalPoint = 2;
$arrCurrencies = array(
'JOD' => 3,
'KWD' => 3,
'OMR' => 3,
'TND' => 3,
'BHD' => 3,
'LYD' => 3,
'IQD' => 3,
);
if (isset($arrCurrencies[$currency])) {
$decimalPoint = $arrCurrencies[$currency];
}
return $decimalPoint;
}
public function getUrl($path)
{
$url = 'http://' . $_SERVER['HTTP_HOST'] . $this->projectUrlPath .'/'. $path;
return $url;
}
public function generateMerchantReference()
{
return rand(0, 9999999999);
}
/**
* Log the error on the disk
*/
public function log($messages) {
$messages = "========================================================\n\n".$messages."\n\n";
$file = __DIR__.'/trace.log';
if (filesize($file) > 907200) {
$fp = fopen($file, "r+");
ftruncate($fp, 0);
fclose($fp);
}
$myfile = fopen($file, "a+");
fwrite($myfile, $messages);
fclose($myfile);
}
/**
*
* #param type $po payment option
* #return string payment option name
*/
function getPaymentOptionName($po) {
switch($po) {
case 'creditcard' : return 'Credit Cards';
case 'cc_merchantpage' : return 'Credit Cards (Merchant Page)';
case 'installments' : return 'Installments';
case 'sadad' : return 'SADAD';
case 'naps' : return 'NAPS';
default : return '';
}
}
}
?>
To access (read, modify) an instance variable (which $amount is), you have to use $this->amount from within a method.
For example.
$this->amount = 1000.00
This is not the same as:
$amount = 1000.00
It would be a very good idea to find a book on OOP, and review the top 10 list from owasp.org for security best practices. Specifically, your code needs to be validating user input as strictly as possible before using it in redirects or sending it on to other services. Also, it looks like you may have posted some access credentials so you might want to change those.
I have problem with a WebService function for moodle callen "mod_scorm_insert_scorm_tracks"
This function is used for inserting track information (i.e. star time) of a user in his SCORM progress.
Part of the estructure of this function is
scoid= int
attempt= int
tracks[0][element]= string
tracks[0][value]= string
NEW
PHP structe has to look like this
[tracks] =>
Array
(
[0] =>
Array
(
[element] => string
[value] => string
)
)
I have used one of the examples they had in his website everything was fine until I got this error
<b>Notice</b>: Array to string conversion in <b>C:\xampp\htdocs\otros\PHP-REST\curl.php</b> on line <b>247</b><br />
<?xml version="1.0" encoding="UTF-8" ?>
<EXCEPTION class="invalid_parameter_exception">
<ERRORCODE>invalidparameter</ERRORCODE>
<MESSAGE>Invalid parameter value detected</MESSAGE>
<DEBUGINFO>tracks => Invalid parameter value detected: Only arrays accepted. The bad value is: 'Array'</DEBUGINFO>
</EXCEPTION>
And the problem seems to be here:
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array(
array(
array(
'element' => 'x.start.time',
'value' => '1473102672'
),
),
array(
array(
'element' => 'x.start.time',
'value' => '1473102680'
),
),
);
I tried in many ways
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array('element' => 'x.start.time','value' => '1473102672');
or
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array(array ('element' => 'x.start.time','value' => '1473102672'));
And still getting the same message, I'm pretty that is problema with my wyntax but I have tried in many ways and still not working I hope yo can help me.
Complete Code:
/// SETUP - NEED TO BE CHANGED
$token = '481bf3d85a7eb539e37eabc88feccb3c';
$domainname = 'http://localhost/moodle';
//$functionname = 'mod_scorm_launch_sco';
$functionname = 'mod_scorm_insert_scorm_tracks';
//$functionname ='mod_scorm_view_scorm';
// REST RETURNED VALUES FORMAT
$restformat = 'xml'; //Also possible in Moodle 2.2 and later: 'json'
//Setting it to 'json' will fail all calls on earlier Moodle version
$item1 = new stdClass();
$item1->scoid = '2';
$item1->attempt = '1';
$item1->tracks = array(
array(
array(
'element' => 'x.start.time',
'value' => 1473102672
),
),
array(
array(
'element' => 'x.start.time',
'value' => 1473102680
),
),
);
$params = $item1;
/// REST CALL
header('Content-Type: text/plain');
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
require_once('./curl.php');
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
print_r($resp);
curl.php
<?php
/**
* cURL class
*
* This is a wrapper class for curl, it is quite easy to use:
* <code>
* $c = new curl;
* // enable cache
* $c = new curl(array('cache'=>true));
* // enable cookie
* $c = new curl(array('cookie'=>true));
* // enable proxy
* $c = new curl(array('proxy'=>true));
*
* // HTTP GET Method
* $html = $c->get('http://example.com');
* // HTTP POST Method
* $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
* // HTTP PUT Method
* $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
* </code>
*
* #author Dongsheng Cai <dongsheng#moodle.com> - https://github.com/dongsheng/cURL
* #license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
class curl {
/** #var bool */
public $cache = false;
public $proxy = false;
/** #var array */
public $response = array();
public $header = array();
/** #var string */
public $info;
public $error;
/** #var array */
private $options;
/** #var string */
private $proxy_host = '';
private $proxy_auth = '';
private $proxy_type = '';
/** #var bool */
private $debug = false;
private $cookie = false;
private $count = 0;
/**
* #param array $options
*/
public function __construct($options = array()){
if (!function_exists('curl_init')) {
$this->error = 'cURL module must be enabled!';
trigger_error($this->error, E_USER_ERROR);
return false;
}
// the options of curl should be init here.
$this->resetopt();
if (!empty($options['debug'])) {
$this->debug = true;
}
if(!empty($options['cookie'])) {
if($options['cookie'] === true) {
$this->cookie = 'curl_cookie.txt';
} else {
$this->cookie = $options['cookie'];
}
}
if (!empty($options['cache'])) {
if (class_exists('curl_cache')) {
$this->cache = new curl_cache();
}
}
}
/**
* Resets the CURL options that have already been set
*/
public function resetopt(){
$this->options = array();
$this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
// True to include the header in the output
$this->options['CURLOPT_HEADER'] = 0;
// True to Exclude the body from the output
$this->options['CURLOPT_NOBODY'] = 0;
// TRUE to follow any "Location: " header that the server
// sends as part of the HTTP header (note this is recursive,
// PHP will follow as many "Location: " headers that it is sent,
// unless CURLOPT_MAXREDIRS is set).
//$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
$this->options['CURLOPT_MAXREDIRS'] = 10;
$this->options['CURLOPT_ENCODING'] = '';
// TRUE to return the transfer as a string of the return
// value of curl_exec() instead of outputting it out directly.
$this->options['CURLOPT_RETURNTRANSFER'] = 1;
$this->options['CURLOPT_BINARYTRANSFER'] = 0;
$this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
$this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
$this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
}
/**
* Reset Cookie
*/
public function resetcookie() {
if (!empty($this->cookie)) {
if (is_file($this->cookie)) {
$fp = fopen($this->cookie, 'w');
if (!empty($fp)) {
fwrite($fp, '');
fclose($fp);
}
}
}
}
/**
* Set curl options
*
* #param array $options If array is null, this function will
* reset the options to default value.
*
*/
public function setopt($options = array()) {
if (is_array($options)) {
foreach($options as $name => $val){
if (stripos($name, 'CURLOPT_') === false) {
$name = strtoupper('CURLOPT_'.$name);
}
$this->options[$name] = $val;
}
}
}
/**
* Reset http method
*
*/
public function cleanopt(){
unset($this->options['CURLOPT_HTTPGET']);
unset($this->options['CURLOPT_POST']);
unset($this->options['CURLOPT_POSTFIELDS']);
unset($this->options['CURLOPT_PUT']);
unset($this->options['CURLOPT_INFILE']);
unset($this->options['CURLOPT_INFILESIZE']);
unset($this->options['CURLOPT_CUSTOMREQUEST']);
}
/**
* Set HTTP Request Header
*
* #param array $headers
*
*/
public function setHeader($header) {
if (is_array($header)){
foreach ($header as $v) {
$this->setHeader($v);
}
} else {
$this->header[] = $header;
}
}
/**
* Set HTTP Response Header
*
*/
public function getResponse(){
return $this->response;
}
/**
* private callback function
* Formatting HTTP Response Header
*
* #param mixed $ch Apparently not used
* #param string $header
* #return int The strlen of the header
*/
private function formatHeader($ch, $header)
{
$this->count++;
if (strlen($header) > 2) {
list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
$key = rtrim($key, ':');
if (!empty($this->response[$key])) {
if (is_array($this->response[$key])){
$this->response[$key][] = $value;
} else {
$tmp = $this->response[$key];
$this->response[$key] = array();
$this->response[$key][] = $tmp;
$this->response[$key][] = $value;
}
} else {
$this->response[$key] = $value;
}
}
return strlen($header);
}
/**
* Set options for individual curl instance
*
* #param object $curl A curl handle
* #param array $options
* #return object The curl handle
*/
private function apply_opt($curl, $options) {
// Clean up
$this->cleanopt();
// set cookie
if (!empty($this->cookie) || !empty($options['cookie'])) {
$this->setopt(array('cookiejar'=>$this->cookie,
'cookiefile'=>$this->cookie
));
}
// set proxy
if (!empty($this->proxy) || !empty($options['proxy'])) {
$this->setopt($this->proxy);
}
$this->setopt($options);
// reset before set options
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
// set headers
if (empty($this->header)){
$this->setHeader(array(
'User-Agent: MoodleBot/1.0',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Connection: keep-alive'
));
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
if ($this->debug){
echo '<h1>Options</h1>';
var_dump($this->options);
echo '<h1>Header</h1>';
var_dump($this->header);
}
// set options
foreach($this->options as $name => $val) {
if (is_string($name)) {
$name = constant(strtoupper($name));
}
curl_setopt($curl, $name, $val);
}
return $curl;
}
/**
* Download multiple files in parallel
*
* Calls {#link multi()} with specific download headers
*
* <code>
* $c = new curl;
* $c->download(array(
* array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
* array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
* ));
* </code>
*
* #param array $requests An array of files to request
* #param array $options An array of options to set
* #return array An array of results
*/
public function download($requests, $options = array()) {
$options['CURLOPT_BINARYTRANSFER'] = 1;
$options['RETURNTRANSFER'] = false;
return $this->multi($requests, $options);
}
/*
* Mulit HTTP Requests
* This function could run multi-requests in parallel.
*
* #param array $requests An array of files to request
* #param array $options An array of options to set
* #return array An array of results
*/
protected function multi($requests, $options = array()) {
$count = count($requests);
$handles = array();
$results = array();
$main = curl_multi_init();
for ($i = 0; $i < $count; $i++) {
$url = $requests[$i];
foreach($url as $n=>$v){
$options[$n] = $url[$n];
}
$handles[$i] = curl_init($url['url']);
$this->apply_opt($handles[$i], $options);
curl_multi_add_handle($main, $handles[$i]);
}
$running = 0;
do {
curl_multi_exec($main, $running);
} while($running > 0);
for ($i = 0; $i < $count; $i++) {
if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
$results[] = true;
} else {
$results[] = curl_multi_getcontent($handles[$i]);
}
curl_multi_remove_handle($main, $handles[$i]);
}
curl_multi_close($main);
return $results;
}
/**
* Single HTTP Request
*
* #param string $url The URL to request
* #param array $options
* #return bool
*/
protected function request($url, $options = array()){
// create curl instance
$curl = curl_init($url);
$options['url'] = $url;
$this->apply_opt($curl, $options);
if ($this->cache && $ret = $this->cache->get($this->options)) {
return $ret;
} else {
$ret = curl_exec($curl);
if ($this->cache) {
$this->cache->set($this->options, $ret);
}
}
$this->info = curl_getinfo($curl);
$this->error = curl_error($curl);
if ($this->debug){
echo '<h1>Return Data</h1>';
var_dump($ret);
echo '<h1>Info</h1>';
var_dump($this->info);
echo '<h1>Error</h1>';
var_dump($this->error);
}
curl_close($curl);
if (empty($this->error)){
return $ret;
} else {
return $this->error;
// exception is not ajax friendly
//throw new moodle_exception($this->error, 'curl');
}
}
/**
* HTTP HEAD method
*
* #see request()
*
* #param string $url
* #param array $options
* #return bool
*/
public function head($url, $options = array()){
$options['CURLOPT_HTTPGET'] = 0;
$options['CURLOPT_HEADER'] = 1;
$options['CURLOPT_NOBODY'] = 1;
return $this->request($url, $options);
}
/**
* Recursive function formating an array in POST parameter
* #param array $arraydata - the array that we are going to format and add into &$data array
* #param string $currentdata - a row of the final postdata array at instant T
* when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
* #param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
*/
function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
foreach ($arraydata as $k=>$v) {
$newcurrentdata = $currentdata;
if (is_object($v)) {
$v = (array) $v;
}
if (is_array($v)) { //the value is an array, call the function recursively
$newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
$this->format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
} else { //add the POST parameter to the $data array
$data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
}
}
}
/**
* Transform a PHP array into POST parameter
* (see the recursive function format_array_postdata_for_curlcall)
* #param array $postdata
* #return array containing all POST parameters (1 row = 1 POST parameter)
*/
function format_postdata_for_curlcall($postdata) {
if (is_object($postdata)) {
$postdata = (array) $postdata;
}
$data = array();
foreach ($postdata as $k=>$v) {
if (is_object($v)) {
$v = (array) $v;
}
if (is_array($v)) {
$currentdata = urlencode($k);
$this->format_array_postdata_for_curlcall($v, $currentdata, $data);
} else {
$data[] = urlencode($k).'='.urlencode($v);
}
}
$convertedpostdata = implode('&', $data);
return $convertedpostdata;
}
/**
* HTTP POST method
*
* #param string $url
* #param array|string $params
* #param array $options
* #return bool
*/
public function post($url, $params = '', $options = array()){
$options['CURLOPT_POST'] = 1;
if (is_array($params)) {
$params = $this->format_postdata_for_curlcall($params);
}
$options['CURLOPT_POSTFIELDS'] = $params;
return $this->request($url, $options);
}
/**
* HTTP GET method
*
* #param string $url
* #param array $params
* #param array $options
* #return bool
*/
public function get($url, $params = array(), $options = array()){
$options['CURLOPT_HTTPGET'] = 1;
if (!empty($params)){
$url .= (stripos($url, '?') !== false) ? '&' : '?';
$url .= http_build_query($params, '', '&');
}
return $this->request($url, $options);
}
/**
* HTTP PUT method
*
* #param string $url
* #param array $params
* #param array $options
* #return bool
*/
public function put($url, $params = array(), $options = array()){
$file = $params['file'];
if (!is_file($file)){
return null;
}
$fp = fopen($file, 'r');
$size = filesize($file);
$options['CURLOPT_PUT'] = 1;
$options['CURLOPT_INFILESIZE'] = $size;
$options['CURLOPT_INFILE'] = $fp;
if (!isset($this->options['CURLOPT_USERPWD'])){
$this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply#moodle.org'));
}
$ret = $this->request($url, $options);
fclose($fp);
return $ret;
}
/**
* HTTP DELETE method
*
* #param string $url
* #param array $params
* #param array $options
* #return bool
*/
public function delete($url, $param = array(), $options = array()){
$options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
if (!isset($options['CURLOPT_USERPWD'])) {
$options['CURLOPT_USERPWD'] = 'anonymous: noreply#moodle.org';
}
$ret = $this->request($url, $options);
return $ret;
}
/**
* HTTP TRACE method
*
* #param string $url
* #param array $options
* #return bool
*/
public function trace($url, $options = array()){
$options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
$ret = $this->request($url, $options);
return $ret;
}
/**
* HTTP OPTIONS method
*
* #param string $url
* #param array $options
* #return bool
*/
public function options($url, $options = array()){
$options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
$ret = $this->request($url, $options);
return $ret;
}
public function get_info() {
return $this->info;
}
}
/**
* This class is used by cURL class, use case:
*
* <code>
*
* $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
* $ret = $c->get('http://www.google.com');
* </code>
*
* #package core
* #subpackage file
* #copyright 1999 onwards Martin Dougiamas {#link http://moodle.com}
* #license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class curl_cache {
/** #var string */
public $dir = '';
/**
*
* #param string #module which module is using curl_cache
*
*/
function __construct() {
$this->dir = '/tmp/';
if (!file_exists($this->dir)) {
mkdir($this->dir, 0700, true);
}
$this->ttl = 1200;
}
/**
* Get cached value
*
* #param mixed $param
* #return bool|string
*/
public function get($param){
$this->cleanup($this->ttl);
$filename = 'u_'.md5(serialize($param));
if(file_exists($this->dir.$filename)) {
$lasttime = filemtime($this->dir.$filename);
if(time()-$lasttime > $this->ttl)
{
return false;
} else {
$fp = fopen($this->dir.$filename, 'r');
$size = filesize($this->dir.$filename);
$content = fread($fp, $size);
return unserialize($content);
}
}
return false;
}
/**
* Set cache value
*
* #param mixed $param
* #param mixed $val
*/
public function set($param, $val){
$filename = 'u_'.md5(serialize($param));
$fp = fopen($this->dir.$filename, 'w');
fwrite($fp, serialize($val));
fclose($fp);
}
/**
* Remove cache files
*
* #param int $expire The number os seconds before expiry
*/
public function cleanup($expire){
if($dir = opendir($this->dir)){
while (false !== ($file = readdir($dir))) {
if(!is_dir($file) && $file != '.' && $file != '..') {
$lasttime = #filemtime($this->dir.$file);
if(time() - $lasttime > $expire){
#unlink($this->dir.$file);
}
}
}
}
}
/**
* delete current user's cache file
*
*/
public function refresh(){
if($dir = opendir($this->dir)){
while (false !== ($file = readdir($dir))) {
if(!is_dir($file) && $file != '.' && $file != '..') {
if(strpos($file, 'u_')!==false){
#unlink($this->dir.$file);
}
}
}
}
}
}
Thanks!
Well after some research I finally took plan B
I wrote tracks in a different variable:
$tracks = array();
$tracks[] = array(
'element' => 'cmi.core.lesson_status',
'value' => 'completed'
);
And I followed curl.php array set option:
$arrayName = array('' => , );
Then when I inserted scoid and attemps as single variables in the array:
$params = array('scoid' => '2', 'attempt' => '1', 'tracks' => $tracks);
and boala!the record is on my table:
Can someone please help. I am getting a fatal error on the following PHP script.
I am getting an error "unidentified method Pass::_createpass()" whick relates to the second last line of the code below.
<?php
$engine = Pass::start('xxxxxxxxxxxxxxxx');
$pass = $engine->createPassFromTemplate(xxxxxxxxxxxxxx);
$engine->redirectToPass($pass);
if (!function_exists('curl_init')) {
throw new Exception('Pass needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Pass needs the JSON PHP extension.');
}
$engine = Pass::start($appKey);
$values = array(
'first' => 'John',
'last' => 'Platinum',
);
$images = array(
'thumbnail' => 'image1.jpg'
);
$pass = $engine->createPassFromTemplate(5688667418918912, $values, $images);
$passData = $engine->downloadPass($pass);
$engine->redirectToPass($pass);
class Pass
{
private $_appKey = null;
private $_endpoint = 'https://pass.center/api/v1';
private $_debug = false;
private static $_instance = null;
private static $_imageTypes = array('icon', 'logo', 'strip', 'thumbnail', 'background', 'footer');
const VERSION = '0.5';
const USER_AGENT = 'PassSDK-PHP/0.5';
public function __construct($appKey = null, $endpoint = null, $debug = false)
{
if (is_null($appKey)) {
throw new Exception('App Key required');
}
$this->_appKey = $appKey;
if ($endpoint !== null) {
$this->_endpoint = $endpoint;
}
$this->_debug = $debug;
}
public static function start($appKey = null, $endpoint = null, $debug = false)
{
if (self::$_instance == null) {
self::$_instance = new self($appKey, $endpoint, $debug);
}
return self::$_instance;
}
public function createPassFromTemplate($templateId, $values = array(), $images = array())
{
$resource = sprintf("https://xxxxxxx/api/v1/templates/names/Test/pass", $templateId);
return $this->_createPass($resource, $values, $images);
}
}
I hope someone can help me as I am not familiar with Functions PHP.
Thanks All
Rob
The function createPass is missing.
You need something like this:
/**
* Prepares the values and image for the pass and creates it
*
* #param string $resource Resource URL for the pass creation
* #param array $values Values
* #param array $images Images
* #return object Pass
*/
private function _createPass($resource, $values, $images)
{
$multipart = count($images) > 0;
if ($multipart) {
$content = array();
foreach ($images as $imageType => $image) {
$this->_addImage($image, $imageType, $content, $imageType);
}
var_dump($content);
// Write json to file for curl
$jsonPath = array_search('uri', #array_flip(stream_get_meta_data(tmpfile())));
file_put_contents($jsonPath, json_encode($values));
$content['values'] = sprintf('#%s;type=application/json', $jsonPath);
} else {
$content = $values;
}
return $this->_restCall('POST', $resource, $content, $multipart);
}
..And full script here