I'm trying to access a single value of an array, I can't seem to get it right. This is the code:
$socialCounts = new socialNetworkShareCount(array(
'url' => 'http://facebook.com/',
'facebook' => true,
'buffer' => true,
'pinterest' => true,
'linkedin' => true,
'google' => true
));
print_r($socialCounts->getShareCounts());
Which Returns the following:
{"facebookshares":52132062,"facebooklikes":0,"pinterestshares":243942,"linkedinshares":4708,"googleplusones":0,"buffershares":207477,"total":52588189}
How can I access the vaule of each individual Item? For example, if I'd like to echo the facebook shares value.
And this is the full class if you need:
class socialNetworkShareCount{
public $shareUrl;
public $socialCounts = array();
public $facebookShareCount = 0;
public $facebookLikeCount = 0;
public $twitterShareCount = 0;
public $bufferShareCount = 0;
public $pinterestShareCount = 0;
public $linkedInShareCount = 0;
public $googlePlusOnesCount = 0;
public function __construct($options){
if(is_array($options)){
if(array_key_exists('url', $options) && $options['url'] != ''){
$this->shareUrl = $options['url'];
}else{
die('URL must be set in constructor parameter array!');
}
// Get Facebook Shares and Likes
if(array_key_exists('facebook', $options)){
$this->getFacebookShares();
$this->getFacebookLikes();
}
// Get Twitter Shares
if(array_key_exists('twitter', $options)){
$this->getTwitterShares();
}
// Get Twitter Shares
if(array_key_exists('pinterest', $options)){
$this->getPinterestShares();
}
// Get Twitter Shares
if(array_key_exists('linkedin', $options)){
$this->getLinkedInShares();
}
// Get Twitter Shares
if(array_key_exists('google', $options)){
$this->getGooglePlusOnes();
}
// Get Buffer Shares
if(array_key_exists('buffer', $options)){
$this->getBufferShares();
}
}elseif(is_string($options) && $options != ''){
$this->shareUrl = $options;
// Get all Social Network share counts if they are not set individually in the options
$this->getFacebookShares();
$this->getFacebookLikes();
$this->getTwitterShares();
$this->getPinterestShares();
$this->getLinkedInShares();
$this->getGooglePlusOnes();
$this->getBufferShares();
}else{
die('URL must be set in constructor parameter!');
}
}
public function getShareCounts(){
$totalShares = $this->getTotalShareCount($this->socialCounts);
$this->socialCounts['total'] = $totalShares;
return json_encode($this->socialCounts);
}
public function getTotalShareCount(array $shareCountsArray){
return array_sum($shareCountsArray);
}
public function getFacebookShares(){
$api = file_get_contents( 'http://graph.facebook.com/?id=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->shares) && $count->shares != '0'){
$this->facebookShareCount = $count->shares;
}
$this->socialCounts['facebookshares'] = $this->facebookShareCount;
return $this->facebookShareCount;
}
public function getFacebookLikes(){
$api = file_get_contents( 'http://graph.facebook.com/?id=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->likes) && $count->likes != '0'){
$this->facebookLikeCount = $count->likes;
}
$this->socialCounts['facebooklikes'] = $this->facebookLikeCount;
return $this->facebookLikeCount;
}
public function getTwitterShares(){
$api = file_get_contents( 'https://api.twitter.com/1.1/urls/count.json?url=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->count) && $count->count != '0'){
$this->twitterShareCount = $count->count;
}
$this->socialCounts['twittershares'] = $this->twitterShareCount;
return $this->twitterShareCount;
}
public function getBufferShares(){
$api = file_get_contents( 'https://api.bufferapp.com/1/links/shares.json?url=' . $this->shareUrl );
$count = json_decode( $api );
if(isset($count->shares) && $count->shares != '0'){
$this->bufferShareCount = $count->shares;
}
$this->socialCounts['buffershares'] = $this->bufferShareCount;
return $this->bufferShareCount;
}
public function getPinterestShares(){
$api = file_get_contents( 'http://api.pinterest.com/v1/urls/count.json?callback%20&url=' . $this->shareUrl );
$body = preg_replace( '/^receiveCount\((.*)\)$/', '\\1', $api );
$count = json_decode( $body );
if(isset($count->count) && $count->count != '0'){
$this->pinterestShareCount = $count->count;
}
$this->socialCounts['pinterestshares'] = $this->pinterestShareCount;
return $this->pinterestShareCount;
}
public function getLinkedInShares(){
$api = file_get_contents( 'https://www.linkedin.com/countserv/count/share?url=' . $this->shareUrl . '&format=json' );
$count = json_decode( $api );
if(isset($count->count) && $count->count != '0'){
$this->linkedInShareCount = $count->count;
}
$this->socialCounts['linkedinshares'] = $this->linkedInShareCount;
return $this->linkedInShareCount;
}
public function getGooglePlusOnes(){
if(function_exists('curl_version')){
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, "https://clients6.google.com/rpc" );
curl_setopt( $curl, CURLOPT_POST, 1 );
curl_setopt( $curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $this->shareUrl . '","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]' );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-type: application/json' ) );
$curl_results = curl_exec( $curl );
curl_close( $curl );
$json = json_decode( $curl_results, true );
$this->googlePlusOnesCount = intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}else{
$content = file_get_contents("https://plusone.google.com/u/0/_/+1/fastbutton?url=".urlencode($_GET['url'])."&count=true");
$doc = new DOMdocument();
libxml_use_internal_errors(true);
$doc->loadHTML($content);
$doc->saveHTML();
$num = $doc->getElementById('aggregateCount')->textContent;
if($num){
$this->googlePlusOnesCount = intval($num);
}
}
$this->socialCounts['googleplusones'] = $this->googlePlusOnesCount;
return $this->googlePlusOnesCount;
}}
According to the class definition, you don't need to invoke getShareCounts(). It looks like that method is perhaps used to provide some lower end API functionality. I don't think it's meant for your use case.
All of the below public variables are accessible and filled in once the constructor has run.
public $facebookShareCount = 0;
public $facebookLikeCount = 0;
public $twitterShareCount = 0;
public $bufferShareCount = 0;
public $pinterestShareCount = 0;
public $linkedInShareCount = 0;
public $googlePlusOnesCount = 0;
So you can access them like so:
$socialCounts = new socialNetworkShareCount(array(
'url' => 'http://facebook.com/',
'facebook' => true,
'buffer' => true,
'pinterest' => true,
'linkedin' => true,
'google' => true
));
print_r($socialCounts->facebookShareCount); // facebook shares
print_r($socialCounts->facebookLikeCount); // facebook likes
mixed json_decode ( string $json [, bool $assoc = false [, int $depth
= 512 [, int $options = 0 ]]] )
Source.
Since your json is an object, json_decode($yourparam) will return an stdClass by default, which will have public members. Since you would like to use an associated array instead, you need to call something like json_decode($yourparam, true), which will return an associated array, since the second parameter is a boolean value determined by your intention whether you want an associated array as result, default value being false.
Related
original
I want to emphasize first that it is my first script in PHP, so many things can be improved, but for now I just need it to work!
I created this script in php to get public profile information from the public instagram json file located at https://www.instagram.com/{{username}}/?__a=1
trying it locally, everything works correctly, but hosting it on a website file_get_contents($ url) doesn't work (line 29) , I tried to use CURL to read the file, but it doesn't work anyway, it doesn't read the json file correctly, trying to do an echo of what he reads the instagram logo appears on the site screen.
how can I solve it?
update
I just noticed that if I try to make file_get_contents () of a link of any profile www.instagram.com/USERNAME, it gives me the exact same result, it may be that trying to read www.instagram.com/USERNAME/?__a= 1 instagram notice and redirect me to the profile page?
I've tried htmlentities() on the data I receive through file_get_contents ... tatan .. actually the script reads a strange html page that is NOT found at the address I gave it!
<?php
$commentiPost;
$likePost;
$postData;
$image;
$urlprofilo;
$followers;
$username;
$follow;
$like;
$commenti;
function getMediaByUsername($count) {
global $image;
global $commentiPost;
global $likePost;
global $urlprofilo;
global $followers;
global $username;
global $follow;
global $postData;
global $like;
global $commenti;
$uname = htmlspecialchars($_GET["name"]);
$username = strtolower(str_replace(' ','_',$uname));
$url = "https://www.instagram.com/".$username."/?__a=1";
$userinfo = file_get_contents($url);
$userdata = json_decode($userinfo,true);
$user = $userdata['graphql']['user'];
$iteration_url = $url;
if(!empty($user)){
$followers = $user['edge_followed_by']['count'];
$follow = $user['edge_follow']['count'];
$fullname = $user['full_name'];
$username = $user['username'];
$profilepic = $user['profile_pic_url'];
$profilepic = (explode("/",$profilepic));
$urlprofilo = "https://scontent-frt3-1.cdninstagram.com/v/t51.2885-19/s150x150/$profilepic[6]";
$limit = $count;
$tryNext = true;
$found = 0;
while ($tryNext) {
$tryNext = false;
$remote = file_get_contents( $iteration_url );
$response = $remote;
if ($response === false) {
return false;
}
$data = json_decode($response, true);
if ( $data === null) {
return false;
}
$media = $data['graphql']['user']['edge_owner_to_timeline_media'];
foreach ( $media['edges'] as $index => $node ) {
if ( $found + $index < $limit ) {
if (isset($node['node']['is_video']) && $node['node']['is_video'] == true) {
$type = 'video';
} else {
$type = 'image';
}
$like = $like + $node['node']['edge_liked_by']['count'];
$commenti = $commenti + $node['node']['edge_media_to_comment']['count'];
$image[] = array( "<a href=".$node['node']['display_url'].">
<img src=".$node['node']['display_url']." alt="." />
<h3>Like: </strong>".$node['node']['edge_liked_by']['count']."</strong> Commenti: <strong>".$node['node']['edge_media_to_comment']['count']."</strong></h3>
</a>");
$postData[] = array(" '".gmdate("d-m-Y",$node['node']['taken_at_timestamp'])."',");
$likePost[] = array(" ".$node['node']['edge_liked_by']['count'].",");
$commentiPost[] = array(" ".$node['node']['edge_media_to_comment']['count'].",");
}
}
$found += count($media['edges']);
if ( $media['page_info']['has_next_page'] && $found < $limit ) {
$iteration_url = $url . '&max_id=' . $media['page_info']['end_cursor'];
$tryNext = true;
}
}
} else{
}
}
getMediaByUsername( 12);
if(isset($image))
{
$postTot = count($image);
}
else {
$postTot = 0;
}
if($postTot > 0 and $followers > 0){
$ER = round(((($like + $commenti)/$postTot)/$followers)*100, 1);
}
else {
$ER = 0;
}
?>
I belive that is SSL certificate problem. When you modify your function to:
function url_get_contents ( $url ) {
if ( ! function_exists( 'curl_init' ) ){
die( 'The cURL library is not installed.' );
}
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec( $ch );
if(curl_errno( $ch )) {
die ('Curl error: ' . curl_error($ch));
}
curl_close( $ch );
return $output;
}
Probably you will see as a result: Curl error: SSL certificate problem: unable to get local issuer certificate.
Add that certificate to your system or uncomment lines with options: CURLOPT_SSL_VERIFYHOSTand CURLOPT_SSL_VERIFYHOST.
I'm new to php oop and I wanted to send the variable value from one function to another in a different page. So, currently I have this one function in one page that I want to send the data to the other function in a different page. Is that even possible perhaps?
Here's the first function in sendData.php
public function main($data) {
$settings = new Settings();
$hash_code = md5('standard' . '10068' . '08f94110d5697a2497511594c31704d0' .'3.00');
$std_post = array(
'apitype'=>'standard', //fix value
'apiid'=>'10068', //your api id from ibill
'apiorderid'=>'OPC0001#00000282', //your order id
'apihashcode'=>$hash_code, //generate hash code as above
'apiamount'=>'3.00', //your customer transaction amount
'apiemail'=>'alif4arsenal97#gmail.com'); //your customer email
$callbackJSON = json_encode($std_post);
$url = 'https://ibill.my/merchant/?ng=callback_api'; //link need to send data
$ch = curl_init($url); // where to post
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $callbackJSON);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = "Cache-Control: no-cache";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$results = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
//echo $results;
$objJSON = json_decode($results); //decode json result
//should return 'SUCCESS'
$callback_status = $objJSON->{'callback_status'}; //callback Status
$message = $objJSON->{'message'}; //callback Message
//Refer on statuspage.php
$std_status_code = $objJSON->{'std_status_code'}; //payment status code
$std_status = $objJSON->{'std_status'}; //payment status
$std_order_id = $objJSON->{'std_order_id'}; //your order id
$std_purchase_code = $objJSON->{'std_purchase_code'}; //ibill transaction id
$std_amount = $objJSON->{'std_amount'}; //transaction amount
$std_datepaid = $objJSON->{'std_datepaid'}; //transaction date time
//Hash code for security
$std_hash_code = $objJSON->{'std_hash_code'}; //Hash code
$hash_code = md5('08f94110d5697a2497511594c31704d0'.'10068'.$std_order_id.$std_amount); //hash code format
$data = [
'callback_status' => $callback_status,
'message' => $message,
'std_status_code' => $std_status_code,
'std_status' => $std_status,
'std_order_id' => $std_order_id,
'std_purchase_code' => $std_purchase_code,
'std_amount' => $std_amount,
'std_datepaid' => $std_datepaid,
'std_hash_code' => $std_hash_code,
'hash_code' => $hash_code
];
processPayment($data);
}
Here's the second function in a different that I wanted the data in the first page to be send to which is test.php
public function processPayment($data)
{
if (!isset($data['std_status_code'])) return false;
if (!isset($data['std_hash_code'])) return false;
$settings = new Settings();
$sale_id = (int) substr($data['std_order_id'], 8);
$sale = Sales::get($sale_id);
if (empty($sale)) return false;
if ($sale['status'] == 1) return $sale;
if ($sale['payment_method'] !== 'ibill' || $sale['status'] != 0) return false;
$sale_uid = $sale['uid'];
$sale_method = $sale['method'];
$paid_amount = bcadd($sale['total_amount'], $sale['handling_charge'], 2);
// Verify the data integrity sent by iBill
$hash = md5($settings->ibill_secret_key . $settings->ibill_merchant_id . $data['std_order_id'] . $data['std_amount']);
$payment_processor_status = -1;
$sale_status = 0;
// Check provided hash and status
if ($hash === $data['std_hash_code'] && $data['std_status_code'] == 00) {
$payment_processor_status = 1;
$sale_status = 1;
}
if ($sale_status === 0) {
if ($data['std_status_code'] != 00) {
$data['std_status'] = '<span style="color: red">' . $data['std_status'] . '</span>';
}
if ($data['std_hash_code'] !== $hash) {
$data['std_hash_code'] = '<span style="color: red">' . $data['std_hash_code'] . '</span>';
}
}
// Prepare updated sale data
$now = new DateTime();
$sale = [
'payment_processor_status' => $payment_processor_status,
'payment_processor_data' => $data,
'payment_time' => $now->format('g:i:s A'),
'payment_date' => $now->format('d-m-Y')
];
Sales::update($sale_id, $sale);
if ($sale_status === 1) {
Sales::confirmSale($sale_id, false);
}
return ['uid' => $sale_uid, 'method' => $sale_method];
}
Those functions are class methods, not only functions.
you can use them (or pass data from one to another) by creating instances of their classes. for example something like this:
class one {
public function f1($data) {
// do something
$instance = new two();
$instance->f2($data);
}
}
class two {
public function f2($data) {
// do something else
}
}
I hope it would work for you.
I am trying to use serverPilot API from my website. I have created simple functions like below for sample usage but its giving me error like below
Fatal error: Uncaught Error: Call to undefined function app_create()
I am new in PHP and don't know proper method to declare and use functions. Let me know what I am missing in this? My full PHP code is like below
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createApp'])){
$name = "sampleName";
$name = "hello";
$runtime ="php5.5";
$password = "Test#123";
$domains = array("www.example.com","example2.com");
app_create( $name, $sysuserid, $runtime, $domains = array());
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createDb'])){
$id = 1;
$name = "hello";
$username ="testuser";
$password = "Test#123";
database_create( $id, $name, $username, $password );
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createUser'])){
$id = 1;
$name = "hello";
$password = "Test#123";
sysuser_create( $id, $name, $password = NULL )();
}
class ServerPilot {
// variables
public $apiID = "";
public $apiKey = "";
public $decode;
// constants
const SP_API_ENDPOINT = 'https://api.serverpilot.io/v1/';
const SP_USERAGENT = 'ServerPilot-PHP/1.0';
const SP_HTTP_METHOD_POST = 'post';
const SP_HTTP_METHOD_GET = 'get';
const SP_HTTP_METHOD_DELETE = 'delete';
// error constants
const SP_MISSING_CONFIG = 'Missing config data';
const SP_MISSING_API = 'You must provide API credentials';
const SP_CURL_ERROR = 'Curl error code returned ';
public function __construct( $config = array() ) {
if( empty($config) ) throw new Exception(ServerPilot::SP_MISSING_CONFIG);
if( !isset($config['id']) || !isset($config['key']) ) throw new Exception(ServerPilot::SP_MISSING_API);
$this->apiID = $config['id'];
$this->apiKey = $config['key'];
$this->decode = ( isset($config['decode']) ) ? $config['decode'] : true;
}
public function sysuser_create( $id, $name, $password = NULL ) {
$params = array(
'serverid' => $id,
'name' => $name);
if( $password )
$params['password'] = $password;
return $this->_send_request( 'sysusers', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function app_create( $name, $sysuserid, $runtime, $domains = array() ) {
$params = array(
'name' => $name,
'sysuserid' => $sysuserid,
'runtime' => $runtime);
if( $domains )
$params['domains'] = $domains;
return $this->_send_request( 'apps', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function database_create( $id, $name, $username, $password ) {
$user = new stdClass();
$user->name = $username;
$user->password = $password;
$params = array(
'appid' => $id,
'name' => $name,
'user' => $user);
return $this->_send_request( 'dbs', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
private function _send_request( $url_segs, $params = array(), $http_method = 'get' )
{
// Initialize and configure the request
$req = curl_init( ServerPilot::SP_API_ENDPOINT.$url_segs );
curl_setopt( $req, CURLOPT_USERAGENT, ServerPilot::SP_USERAGENT );
curl_setopt( $req, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $req, CURLOPT_USERPWD, $this->apiID.':'.$this->apiKey );
curl_setopt( $req, CURLOPT_RETURNTRANSFER, TRUE );
// Are we using POST or DELETE? Adjust the request accordingly
if( $http_method == ServerPilot::SP_HTTP_METHOD_POST ) {
curl_setopt( $req, CURLOPT_HTTPHEADER, array('Content-Type: application/json') );
curl_setopt( $req, CURLOPT_POST, TRUE );
curl_setopt( $req, CURLOPT_POSTFIELDS, json_encode($params) );
}
if( $http_method == ServerPilot::SP_HTTP_METHOD_DELETE ) {
curl_setopt( $req, CURLOPT_CUSTOMREQUEST, "DELETE" );
}
// Get the response, clean the request and return the data
$response = curl_exec( $req );
$http_status = curl_getinfo( $req, CURLINFO_HTTP_CODE );
curl_close( $req );
// Everything when fine
if( $http_status == 200 )
{
// Decode JSON by default
if( $this->decode )
return json_decode( $response );
else
return $response;
}
// Some error occurred
$data = json_decode( $response );
// The error was provided by serverpilot
if( property_exists( $data, 'error' ) && property_exists( $data->error, 'message' ) )
throw new ServerPilotException($data->error->message, $http_status);
// No error as provided, pick a default
switch( $http_status )
{
case 400:
throw new ServerPilotException('We couldn\'t understand your request. Typically missing a parameter or header.', $http_status);
break;
case 401:
throw new ServerPilotException('Either no authentication credentials were provided or they are invalid.', $http_status);
break;
case 402:
throw new ServerPilotException('Method is restricted to users on the Coach or Business plan.', $http_status);
break;
case 403:
throw new ServerPilotException('Forbidden.', $http_status);
break;
case 404:
throw new ServerPilotException('You requested a resource that does not exist.', $http_status);
break;
case 409:
throw new ServerPilotException('Typically when trying creating a resource that already exists.', $http_status);
break;
case 500:
throw new ServerPilotException('Something unexpected happened on ServerPilot\'s end.', $http_status);
break;
default:
throw new ServerPilotException('Unknown error.', $http_status);
break;
}
}
}
?>
<html>
<body>
<form action="server.php" method="post">
<input type="submit" name="createApp" value="Create APP" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createDb" value="Create DB" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createUser" value="Create USER" />
</form>
</body>
</html>
Its giving error in all three functions same. Letme know if someone can help me for come out from this issue, I am trying from last two hours and its not working.
Thanks
You can not access class function directly like this.You need to create class object first and then call the function with object variable.
It's better to save class code in a separate file and include it in the above give file at the top to avoid errors.
E.g:
// $config as array, You need it to set in construct method.check construct method.
$config = [
"id" => ENTER_ID,
"key" => ENTER_KEY,
"decode" => true, //Optional you can leave this ,default is true anyway.
];
$ServerPilot_Obj = New ServerPilot($config);
$ServerPilot_Obj->app_create( $name, $sysuserid, $runtime, $domains = array());
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');
i'm writing a script to execute import of a csv using the admin panel: AdminImport.
The script execute a login into the admin panel and post csv with opportune parameters to import the file.
I've founded this class on web:
<?php
class PSRequest {
protected $_eol = "\r\n";
protected $_useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
protected $_cookieFileLocation = './cookie.txt';
protected $_referer = "http://www.google.com";
protected $_url;
protected $_followlocation;
protected $_timeout;
protected $_maxRedirects;
protected $_post = false;
protected $_multipart = false;
protected $_file = false;
protected $_postFields;
protected $_postFile;
protected $_session;
protected $_includeHeader;
protected $_noBody;
protected $_status;
protected $_binaryTransfer;
protected $_file_to_upload = null;
protected $_file_to_upload_size = 0;
protected $_file_name = '';
protected $_file_transfer_codebase = false;
protected $_file_content_type = '';
protected $_boundary = 'boundaryAAAbbb';
public $_webpage;
public $authentication = 0;
public $auth_name = '';
public $auth_pass = '';
protected $ch; // curl handler
public function __construct($url = '', $followlocation = true, $timeOut = 30, $maxRedirecs = 4, $binaryTransfer = false, $includeHeader = true, $noBody = false)
{
$this->_url = $url;
$this->_followlocation = $followlocation;
$this->_timeout = $timeOut;
$this->_maxRedirects = $maxRedirecs;
$this->_noBody = $noBody;
$this->_includeHeader = $includeHeader;
$this->_binaryTransfer = $binaryTransfer;
$this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';
$this->ch = curl_init();
}
public function __destruct() {
curl_close($this->ch);
}
public function useAuth($use){
$this->authentication = 0;
if($use == true) $this->authentication = 1;
}
public function setEndOfLine($chars) {
$this->_eol = $chars;
}
public function setName($name){
$this->auth_name = $name;
}
public function setPass($pass){
$this->auth_pass = $pass;
}
public function setBoundary($boundary) {
$this->_boundary = $boundary;
}
public function setReferer($referer){
$this->_referer = $referer;
}
public function setCookiFileLocation($path)
{
$this->_cookieFileLocation = $path;
}
public function setFileToUpload($filePath, $filename, $contentType='plain/text')
{
$this->setPostMultipart(array('post'=>'true'));
$this->_file = true;
$this->_file_name = $filename;
$this->_file_content_type = $contentType;
//$this->_file_to_upload = fopen($filePath,'r');
$handle = fopen($filePath, "r");
$this->_file_to_upload_size = filesize($filePath);
$this->_file_to_upload = fread($handle, $this->_file_to_upload_size);
fclose($handle);
}
public function setPostMultipart($postFields)
{
$this->_post = true;
$this->_multipart = true;
if (is_array($postFields)) {
$fields_string = $this->multipart_build_query($postFields);
}
else {
$fields_string = $postFields;
}
$this->_postFields = $fields_string;
}
public function setPost($postFields)
{
$this->_post = true;
if (is_array($postFields)) {
$fields_string = http_build_query($postFields);
}
else {
$fields_string = $postFields;
}
$this->_postFields = $fields_string;
}
public function setUserAgent($userAgent)
{
$this->_useragent = $userAgent;
}
public function call($url = null, $header = null)
{
if(is_null($header)) {
if( $this->_multipart == true ) {
$header = array("Content-Type: multipart/form-data; boundary=".$this->_boundary);
} else {
$header = array('Content-Type: application/x-www-form-urlencoded');
}
}
if ($url) {
$this->_url = $url;
}
if (!$url) {
throw new Exception('You should set an URL to call.');
}
curl_setopt($this->ch,CURLOPT_URL,$this->_url);
curl_setopt($this->ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($this->ch,CURLOPT_TIMEOUT,$this->_timeout);
curl_setopt($this->ch,CURLOPT_MAXREDIRS,$this->_maxRedirects);
curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
curl_setopt($this->ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch,CURLOPT_COOKIESESSION, true );
curl_setopt($this->ch,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
curl_setopt($this->ch,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
if ($this->authentication == 1) {
curl_setopt($this->ch, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
}
if ($this->_multipart) {
curl_setopt($this->ch,CURLOPT_POST,true);
if($this->_file) {
$this->_postFields .= $this->add_multipart_build_file('file',$this->_file_name,$this->_file_content_type);
$this->_postFields .= "--".$this->_eol;
curl_setopt($this->ch, CURLOPT_INFILESIZE, $this->_file_to_upload_size);
curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, 1);
}
} else if ($this->_post) {
curl_setopt($this->ch,CURLOPT_POST,true);
}
curl_setopt($this->ch,CURLOPT_POSTFIELDS,$this->_postFields);
if ($this->_includeHeader) {
curl_setopt($this->ch,CURLOPT_HEADER,true);
}
if ($this->_noBody) {
curl_setopt($this->ch,CURLOPT_NOBODY,true);
}
/* if ($this->_file_to_upload_size > 0 && !is_null($this->_file_to_upload)) {
curl_setopt($this->ch, CURLOPT_READFUNCTION, 'uploadFileCall');
} */
curl_setopt($this->ch,CURLOPT_USERAGENT,$this->_useragent);
curl_setopt($this->ch,CURLOPT_REFERER,$this->_referer);
$this->_webpage = curl_exec( $this->ch );
$this->_status = curl_getinfo( $this->ch, CURLINFO_HTTP_CODE );
return $this->_webpage;
}
public function getHttpStatus()
{
return $this->_status;
}
public function __tostring(){
return $this->_webpage;
}
/*function uploadFileCall($ch, $data){
return fread($this->_file_to_upload, $this->_file_to_upload_size);
}*/
function multipart_build_query($fields){
$retval = '';
foreach($fields as $key => $value){
$retval .= "--".$this->_boundary.$this->_eol."Content-Disposition: form-data; name=\"".$key."\"".$this->_eol.$this->_eol.$value.$this->_eol;
}
//$retval .= "--". $this->_boundary ."--".$this->_eol;
$retval .= "--". $this->_boundary .$this->_eol;
return $retval;
}
function add_multipart_build_file($key,$filename='file.csv',$contentType ="application/csv") {
$retval = '';
$retval .= "Content-Disposition: form-data; name=\"$key\"; filename=\"$filename\"".$this->_eol;
$retval .= "Content-Type: $contentType ".$this->_eol.$this->_eol;
if($this->_file_transfer_codebase == true) {
$retval .= 'Content-Transfer-Encoding: base64'.$this->_eol.$this->_eol;
$retval .= chunk_split(base64_encode($this->_file_to_upload));
} else {
$retval .= $this->_file_to_upload;
}
$retval .= "--". $this->_boundary; // ."--".$this->_eol;
return $retval;
}
}
?>
This is the main script:
$request = new PSRequest();
$request->setCookiFileLocation( __DIR__ . '/PScookie.txt' );
debug( "Login..." );
$request->setPost( array( "email" => $adminLoginEmail, "passwd" => $adminLoginPass, "submitLogin" => "Connexion" ) ); // you must be a super admin
$request->call( $adminUrl . "index.php?controller=AdminLogin" );
$response = $request->_webpage;
preg_match( "/&token=([a-z0-9]+)/", $response, $matches );
// $token = Tools::getAdminTokenLite( 'AdminImport' );
$token = $matches[ 1 ];
debug( "Token: ".$token );
$csvname = $upload_dir . 'prestashop_products.csv';
// Send POST datas just like the admin form would do it, those datas depends on what you want to do : check the import admin page.
$request->setPost(array(
"controller" => "AdminImport",
"token" => $token,
"skip" => 1,
"csv" => $csvname,
"convert" => '',
"regenerate" => '',
"entity" => 1, //1 is for products import
"iso_lang" => "it",
"truncate" => 0,
"forceIDs" => 1,
"match_ref" => 1,
"separator" => ";",
"multiple_value_separator" => ",",
"import" => 1,
"type_value" => array( 1 => 'active', 2 => 'reference', 3 => 'name', 4 => 'category', 5 => 'price_tex', 6 => 'supplier', 7 => 'weight', 8 => 'quantity', 9 => 'description' )
)
);
debug( "call AdminImport and POST datas..." );
$request->call( $adminUrl."index.php?controller=AdminImport&token=".$token );
The script initially works: i can get the admin panel and i succesfully get token!!
but when i POST data, the request fails due to 'token invalid'!!
But the token is ok!!
I've tryed to use the function:
Tools::getAdminTokenLite( 'AdminImport' )
the token is different to the token i get from page, but also not work!!
I think problem regardling php sessions but i don't know hot to resolve it!!
someone can help me?