php : System.NullPointerException: Attempt to de-reference a null object - php

Please help me to sort out this problem
I am getting this error.
[faultstring] => System.NullPointerException: Attempt to de-reference a null object
I am using custom object integration for Sales force.
require_once ('soapclient/SforcePartnerClient.php');
require_once ('soapclient/SforceHeaderOptions.php');
try {
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("soapclient/partnerwsdl-sb.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// Define constants for the web service. We'll use these later
$parsedURL = parse_url($mySforceConnection->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", 'WebToLeadServices');
define ("_WS_WSDL_", 'soapclient/WebToLeadServices-SB-V1.1.xml');
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
// SOAP Client for Web Service
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $mySforceConnection->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
$sObject = new stdclass();
$sObject->fullName = 'Sunil';
$sObject->country = 'India';
$sObject->budget = '1';
$sObject->type = 'Contact';
$sObject->dialingCode = '91';
$sObject->emailAddress = "XXXX";
$sObject->mobileNumber = "XXXXXXXX";
$sObject->source = "google";
$sObject->projectInterested = "Project";
$sObject->capturePoint = "XXXX.php";
$sObject->IPAddress = "XXXX";
$sObject->webbannerSource = "google";
$sObject->webbannerSize = "twitter";
$createResponse = $client->createLeadFromWeb(array($sObject));
} catch (Exception $e) {
echo '<pre>';
print_r($e);
echo '</pre>';
}
?>
</pre>

I have got the solution for it
We need to pass the variable like this with required field.
and its working
$lead = new StdClass();
$lead->fullName = 'sunil';
$lead->mobileNumber = "1234567896";
$lead->emailAddress = "sunil#example.in";
$lead->source = "DIGITAL MARKETING";
$leadData = array('wl'=>$lead);
$response = $client->createLeadfromWeb($leadData);

Related

how to use dreamscape api in nodejs for check domain name

I have already work this in php. Here is my working code:
$request = array(
'DomainNames' => $domain_names
);
$response = dreamScapeAPI('DomainCheck', $request);
$available = false;
$alt_domains = array(); // Alternative to user's expected domain names
if (!is_soap_fault($response)) {
// Successfully checked the availability of the domains
if (isset($response->APIResponse->AvailabilityList)) {
$availabilityList = $response->APIResponse->AvailabilityList;
foreach ($availabilityList as $list) {
if ($list->Available){
if ($domain == $list->Item) {
$available = true; // user prefered domain found
}
else {
$alt_domains[] = $list->Item;
}
}
}
}
else {
$error = $response->APIResponse->Errors;
foreach ($error as $e) {
$api_error = $e->Message;
//echo $e->Item . ' - ' . $e->Message . '<br />';
}
}
}
function dreamScapeAPI($method, $data = null) {
$reseller_api_soap_client = "";
$soap_location = 'http://soap.secureapi.com.au/API-2.1';
$wsdl_location = 'http://soap.secureapi.com.au/wsdl/API-2.1.wsdl';
$authenticate = array();
$authenticate['AuthenticateRequest'] = array();
$authenticate['AuthenticateRequest']['ResellerID'] = '**';
$authenticate['AuthenticateRequest']['APIKey'] = '**';
//convert $authenticate to a soap variable
$authenticate['AuthenticateRequest'] = new SoapVar($authenticate['AuthenticateRequest'], SOAP_ENC_OBJECT);
$authenticate = new SoapVar($authenticate, SOAP_ENC_OBJECT);
$header = new SoapHeader($soap_location, 'Authenticate', $authenticate, false);
$reseller_api_soap_client = new SoapClient($wsdl_location, array('soap_version' => SOAP_1_2, 'cache_wsdl' => WSDL_CACHE_NONE));
$reseller_api_soap_client->__setSoapHeaders(array($header));
$prepared_data = $data != null ? array($data) : array();
try {
$response = $reseller_api_soap_client->__soapCall($method, $prepared_data);
} catch (SoapFault $response) { }
return $response;
}
I tried with this : https://github.com/dan-power/node-dreamscape
But domain search can not work properly. Mainly, I want it on nodejs using nodejs dreamscape api but this method is not available on nodejs.
Here is my working demo: click here

How to read body of message send by stomp

I'm trying to create a json that I wish to send from one producer to another, which later needs to break it down and work with it.
So I am using activemq, and stomp, since I am programming in php.
I have the following program for my producer:
<?php
namespace Stomp;
require __DIR__ . '/../vendor/autoload.php';
use Stomp\Client;
use Stomp\StatefulStomp;
use Stomp\Network\Connection;
use Stomp\Transport\Message;
header('Content-Type: application/json');
//namespace buttoncall\Model;
$provider=''; //colocar provider
$data1= array(
'provider' => $provider
);
(...)
$data=array($data1,$data2, $data3, $data4);
$json = json_encode($data, true);
$destination = '/queue/nexmo';
$messages = 1;
$size = 1024;
$DATA = "calls";
//$body = $data;
$body = $json;
for($i=0; $i< $size; $i++) {
$body .= $DATA[ $i % 26];
}
try {
$connection = new Connection('tcp://192.168.64.2:61613');
$con1 = new StatefulStomp(new Client($connection));
$con1->send($destination, new Message($body));
echo "Message sent $body \n" ;
$con1->send($destination, new Message("SHUTDOWN"));
} catch(StompException $e) {
echo $e->getMessage();
}
}
}
And then the following consumer:
<?php
//Nexmo
namespace Stomp;
require __DIR__ . '/../vendor/autoload.php';
include 'generate_jwt.php';
use Stomp\Client;
use Stomp\StatefulStomp;
use Stomp\Network\Connection;
use Stomp\Transport\Message;
$user = getenv("ACTIVEMQ_USER");
if( !$user ) $user = "admin";
$password = getenv("ACTIVEMQ_PASSWORD");
if( !$password ) $password = "admin";
/*$host = getenv("ACTIVEMQ_HOST");
if( !$host ) $host = "localhost";
$port = getenv("ACTIVEMQ_PORT");
if( !$port ) $port = 61613; */
$destination = '/queue/nexmo';
try {
$connection = new Connection('tcp://192.168.64.2:61613');
$stomp = new StatefulStomp(new Client($connection));
$stomp->subscribe($destination);
echo "Waiting for messages...\n";
while(true) {
$frame = $stomp->read();
echo "message received";
$json = $frame->$body;
//echo($stomp);
//echo($frame);
//echo($body);
echo $json ;
}
} catch(StompException $e) {
echo $e->getMessage();
}
I've tried several combinations to print the body, but nothing seems to work... They both comunicate, and I can see them in the ActiveMQ broker, but I can't extract the body...
Any clues?
Thank you in advance
I figured it out, just had:
$frame = $stomp->read();
$body = $frame->getBody();
echo "message received $body \n";
There is a function for it, in the Stomp library.

having php fatal error Function name must be a string in C:\wamp\www\drupal-7.42\sites\all\modules\form_fun\form_fun.cake.inc on line 78

I am trying to send a curl request to moodle using drupal.But each tiem i run this code i get an error message that function name must be a string.I have tried everything but nothing is working.Can anybody please help me?
function form_fun_cake_submit(&$form, &$form_state) {
$serverUrl=' http://localhost/moodle/my/webservice/rest/server.php?wstoken=d90b5d90db13711d12df525366f15db1';
$functionName = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'Uk3#0d5w';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = '';
$user1->lang = 'en';
$user1->timezone = 'Australia/Sydney';
$user1->mailformat = 0;
$user1->description = '';
$user1->city = '';
$user1->country = 'AU'; //list of abrevations is in yourmoodle/lang/en/countries
$preferencename1 = 'auth_forcepasswordchange';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'true')
);
$users = array($user1);
$params = array('users' => $users);
/// REST CALL
$rest_format = 'json';
//$server_url = $domain_name . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $function_name;
$server_url = 'localhost/moodle/my' . '/webservice/rest/server.php'. '?wstoken=' . '15bd45a3dab2958b7e8fc237b14f76cd' .'&wsfunction='. $functionName;
dpm($server_url);
require_once('curl.inc');
$curl = new curl;
$rest_format = ($rest_format == 'json') ? '&moodlewsrestformat=' . $rest_format : '';
$resp =$curl($server_url . $rest_format, $params); //This is my line no 78
dpm($rest_format);
$respRc = json_decode($resp, true);
dpm($resp);
echo '</br>************************** Server Response createUser()**************************</br></br>';
echo $server_url . '</br></br>';
var_dump($resp);
}
Line 78 replace $curl(...) with new curl(..), your object instancing is incorrect. What is telling the php log is that you are using a variable as function name aka $curl (nothing to do with $functionName wich might have generated an error later with curl not on compile if it was wrong).
$resp = new curl($server_url . $rest_format, $params);

PHP create User in moodle via Webservice

I want so connect an external website with a moodle-system. I've already set up the webService and created a token to get access.
I've followed http://www.rumours.co.nz/manuals/using_moodle_web_services.htm set up but in contrast i wanted to realise the connection via REST as in https://github.com/moodlehq/sample-ws-clients/find/master
My approach is to have a moodle class which will handle the data exchange. In first place i just wanted to try to create some new hard coded Users via the webService but it fails with the Moodle-Response:
"invalidrecord Can not find data record in database table external_functions. "
Which seems to me as if i the call was successfully but moodle has a problem to find the "core_user_create_users" function. I've checked the local moodle Database and in the table external_functions is an entry for "core_user_create_users" so i'm kind of confused where moodle doesn't know what to do.
Thats my class:
require_once (DOCUMENT_ROOT.'/tcm/api/moodle/curl.php');
class Moodle {
private $token;
private $domainName; // 'local.moodle.dev';
private $serverUrl;
public function __construct($token, $domainName) {
$this->token = $token;
$this->domainName = $domainName;
$this->serverUrl = $this->domainName . '/webservice/rest/server.php' . '?wstoken=' . $this->token;
echo "initialize Service: $this->serverUrl </br>";
}
public function createUser() {
$functionName = 'core_user_create_users';
/// PARAMETERS - NEED TO BE CHANGED IF YOU CALL A DIFFERENT FUNCTION
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'testpassword1';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = 'testidnumber1';
$user1->lang = 'en';
$user1->theme = 'standard';
$user1->timezone = '-12.5';
$user1->mailformat = 0;
$user1->description = 'Hello World!';
$user1->city = 'testcity1';
$user1->country = 'au';
$preferencename1 = 'preference1';
$preferencename2 = 'preference2';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'preferencevalue1'),
array('type' => $preferencename2, 'value' => 'preferencevalue2'));
$user2 = new stdClass();
$user2->username = 'testusername2';
$user2->password = 'testpassword2';
$user2->firstname = 'testfirstname2';
$user2->lastname = 'testlastname2';
$user2->email = 'testemail2#moodle.com';
$user2->timezone = 'Pacific/Port_Moresby';
$users = array($user1, $user2);
$params = array('users' => $users);
/// REST CALL
$serverurl = $this->serverUrl . '&wsfunction=' . $functionName;
require_once (DOCUMENT_ROOT.'/tcm/api/moodle/curl.php');
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = "json";
$resp = $curl->post($serverurl . $restformat, $params);
//print_r($resp);
echo '</br>*************Server Response*************</br>';
var_dump($resp);
}
}
I'm using the curl class from the same github-project which i posted above - moodle is linkng to it in their Documentation..
docs.moodle.org/dev/Creating_a_web_service_client
The entry point of my call is hardcoded right now:
<?php
include_once (DOCUMENT_ROOT.'/tcm/api/moodle/moodle.php');
//entry point of code
if (isset($_POST)){
//token and domain would be in $_POST
$bla = new Moodle('0b5a1e98061c5f7fb70fc3b42af6bfc4', 'local.moodle.dev');
$bla->createUser();
}
Does anyone know how to solve the "invalidrecord Can not find data record in database table external_functions" error or has a different approach/suggestion how i can create my users remotely??
Thanks in advance
I got it finally working with the following code:
class Moodle {
private $token; //'0b5a1e98061c5f7fb70fc3b42af6bfc4';
private $domainName; // 'http://local.moodle.dev';
private $serverUrl;
public $error;
public function __construct($token, $domainName) {
$this->token = $token;
$this->domainName = $domainName;
$this->serverUrl = $this->domainName . '/webservice/rest/server.php' . '?wstoken=' . $this->token;
echo "initialize Service: $this->serverUrl </br>";
}
public function createUser() {
$functionName = 'core_user_create_users';
$user1 = new stdClass();
$user1->username = 'testusername1';
$user1->password = 'Uk3#0d5w';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = '';
$user1->lang = 'en';
$user1->timezone = 'Australia/Sydney';
$user1->mailformat = 0;
$user1->description = '';
$user1->city = '';
$user1->country = 'AU'; //list of abrevations is in yourmoodle/lang/en/countries
$preferencename1 = 'auth_forcepasswordchange';
$user1->preferences = array(
array('type' => $preferencename1, 'value' => 'true')
);
$users = array($user1);
$params = array('users' => $users);
/// REST CALL
$restformat = "json";
$serverurl = $this->serverUrl . '&wsfunction=' . $functionName. '&moodlewsrestformat=' . $restformat;
require_once (DOCUMENT_ROOT . '/tcm/api/moodle/curl.php');
$curl = new curl();
$resp = $curl->post($serverurl, $params);
echo '</br>************************** Server Response createUser()**************************</br></br>';
echo $serverurl . '</br></br>';
var_dump($resp);
}
}
Info:
For all moodle beginners.. Activating the moodle Debug messages helps a bit. You'll receive an additional error information in the response returned form the server.
Moodle -> Site Administration -> Development -> Debugging -> Debug Messages
Select: DEVELOPER:extra Moodle debug messages for developers

Google BigQuery - Automating a Cron Job

Using PHP, I am able to run BigQuery manually but I need BigQuery to run as an automatic cron job (without Gmail login). How would I accomplish this? Thanks.
You need to create a service account in the developer console, than you will be able to use from code. Here is a code that we have in our cron files.
properly creates a Google_Client using https://github.com/google/google-api-php-client
runs a job async
displays the running job ID and status
You need to have:
service account created (something like ...#developer.gserviceaccount.com)
your key file (.p12)
service_token_file_location (writable path to store the JSON from the handshake, it will be valid for 1h)
code sample:
function getGoogleClient($data = null) {
global $service_token_file_location, $key_file_location, $service_account_name;
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$old_service_token = null;
$service_token = #file_get_contents($service_token_file_location);
$client->setAccessToken($service_token);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, array(
'https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/devstorage.full_control'
), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
$service_token = $client->getAccessToken();
}
return $client;
}
$client = getGoogleClient();
$bq = new Google_Service_Bigquery($client);
/**
* #see https://developers.google.com/bigquery/docs/reference/v2/jobs#resource
*/
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$config->setDryRun(false);
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId(DATASET_ID);
$destinationTable->setProjectId(PROJECT_ID);
$destinationTable->setTableId('table1');
$queryConfig->setDestinationTable($destinationTable);
$sql = "select * from publicdata:samples.github_timeline limit 10";
$queryConfig->setQuery($sql);
try {
// print_r($job);
// exit;
$job = $bq->jobs->insert(PROJECT_ID, $job);
$status = new Google_Service_Bigquery_JobStatus();
$status = $job->getStatus();
// print_r($status);
if ($status->count() != 0) {
$err_res = $status->getErrorResult();
die($err_res->getMessage());
}
} catch (Google_Service_Exception $e) {
echo $e->getMessage();
exit;
}
//print_r($job);
$jr = $job->getJobReference();
//var_dump($jr);
$jobId = $jr['jobId'];
if ($status)
$state = $status['state'];
echo 'JOBID:' . $jobId . " ";
echo 'STATUS:' . $state;
You can grab the results with:
$res = $bq->jobs->getQueryResults(PROJECT_ID, $_GET['jobId'], array('timeoutMs' => 1000));
if (!$res->jobComplete) {
echo "Job not yet complete";
exit;
}
echo "<p>Total rows: " . $res->totalRows . "</p>\r\n";
//see the results made it as an object ok
//print_r($res);
$rows = $res->getRows();
$r = new Google_Service_Bigquery_TableRow();
$a = array();
foreach ($rows as $r) {
$r = $r->getF();
$temp = array();
foreach ($r as $v) {
$temp[] = $v->v;
}
$a[] = $temp;
}
print_r($a);
You can see here the classes that you can use for your other BigQuery calls. When you read the file, please know that file is being generated from other sources, hence it looks strange for PHP, and you need to learn reading it in order to be able to use the methods from it.
https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php
like:
Google_Service_Bigquery_TableRow
Also check out the questions tagged with [php] and [google-bigquery]
https://stackoverflow.com/questions/tagged/google-bigquery+php

Categories