This is my code
class WcfClient {
public $wcfClient = null;
public $user = null;
public function __construct(){
if(isset($_SESSION['APIClient']) && $_SESSION['APIClient'] != null){
$this->wcfClient = $_SESSION['APIClient'];
}
}
public function __destruct(){
}
// Authanticate
private function Authenticate(){
global $_sogh_soapUrl, $_isDebug, $_sogh_header;
$wcargs = array();
$consumerAuthTicket = null;
if($this->wcfClient == null){
$args = array(
'clubname'=>'Wellness Institute at Seven Oaks',
'consumerName'=>'api',
'consumerPassword'=>'api'
);
try{
$wcargs = array(
'soap_version'=>SOAP_1_2
);
if($_isDebug){
$wcargs = array(
'soap_version'=>SOAP_1_2,
'proxy_host'=>"192.168.0.1",
'proxy_port'=>8080
);
}
// Connect to the API with soapclient
$soapAPIClient = new SoapClient($_sogh_soapUrl, $wcargs);
$response = $soapAPIClient->AuthenticateClubConsumer($args);
if(isset($response->AuthenticateClubConsumerResult)){
if(isset($response->AuthenticateClubConsumerResult->IsException) && $response->AuthenticateClubConsumerResult->IsException == true){
// some error occur
$this->wcfClient = null;
$_SESSION['APIClient'] = $this->wcfClient;
} else{
// set consumer ticket
$consumerAuthTicket = $response->AuthenticateClubConsumerResult->Value->AuthTicket;
// $loginData = $responseCode->ReturnValueOfConsumerLoginData;
$headers = array();
$headers[] = new SoapHeader($_sogh_header, "ConsumerAuthTicket", $consumerAuthTicket);
$soapAPIClient->__setSoapHeaders($headers);
// add to session
$this->wcfClient = $soapAPIClient;
$_SESSION['APIClient'] = $this->wcfClient;
}
}
} catch(SoapFault $fault){
$this->error('Fault: ' . $fault->faultcode . ' - ' . $fault->faultstring);
} catch(Exception $e){
$this->error('Error: ' . $e->getMessage());
}
}
return $this->wcfClient;
}
I store the soap client object in $_SESSION['APIClient'], but second times when run some data has been changed in session, I am use this class in drupal 7, I want to save the time using session, because authenticating takes long time.
Please help
Thank in advance
Related
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
To list the files and folders from Azure Files can be done with this code:
function ListFolder($shareName, $path)
{
global $fileRestProxy;
$vMaxResultados = 5000;
$vNextMarker = "";
$listResult = null;
try
{
do
{
$options = new ListDirectoriesAndFilesOptions();
$options->setMaxResults($vMaxResultados);
$options->setMarker($vNextMarker);
$listResult = $fileRestProxy->ListDirectoriesAndFiles($shareName,$path,$options);
$vNextMarker = $listResult->getNextMarker();
} while ($vNextMarker != "");
}
catch (Exception $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
return "ERROR:$code:$error_message";
}
return $listResult;
}
But how is the sintaxis or method to the same with a snapshot from these Share?
This doesn't work:
function ListSnapshotFolder($shareName, $path, $snapshot)
{
global $fileRestProxy;
$vMaxResultados = 5000;
$vNextMarker = "";
$listResult = null;
try
{
do
{
$options = new ListDirectoriesAndFilesOptions();
$options->setMaxResults($vMaxResultados);
$options->setMarker($vNextMarker);
$shareFull = $shareName . "?snapshot=" . $snapshot;
$listResult = $fileRestProxy->ListDirectoriesAndFiles($shareFull,$path,$options);
$vNextMarker = $listResult->getNextMarker();
} while ($vNextMarker != "");
}
catch (Exception $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
return "ERROR:$code:$error_message";
}
return $listResult;
}
Is there any parameter in the $option object to add?
Or maybe the $shareFull must be created in some format?
$shareFull = $shareName . "?snapshot=" . $snapshot;
Thanks in advance.
I believe you have found a bug in the SDK. I looked up the source code here and there's no provision to provide sharesnapshot query string parameter in the options as well as the code does not even handle it.
public function listDirectoriesAndFilesAsync(
$share,
$path = '',
ListDirectoriesAndFilesOptions $options = null
) {
Validate::notNull($share, 'share');
Validate::canCastAsString($share, 'share');
Validate::canCastAsString($path, 'path');
$method = Resources::HTTP_GET;
$headers = array();
$postParams = array();
$queryParams = array();
$path = $this->createPath($share, $path);
if (is_null($options)) {
$options = new ListDirectoriesAndFilesOptions();
}
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_REST_TYPE,
'directory'
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_COMP,
'list'
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_PREFIX_LOWERCASE,
$options->getPrefix()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_MARKER_LOWERCASE,
$options->getNextMarker()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_MAX_RESULTS_LOWERCASE,
$options->getMaxResults()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_TIMEOUT,
$options->getTimeout()
);
$dataSerializer = $this->dataSerializer;
return $this->sendAsync(
$method,
$headers,
$queryParams,
$postParams,
$path,
Resources::STATUS_OK,
Resources::EMPTY_STRING,
$options
)->then(function ($response) use ($dataSerializer) {
$parsed = $dataSerializer->unserialize($response->getBody());
return ListDirectoriesAndFilesResult::create(
$parsed,
Utilities::getLocationFromHeaders($response->getHeaders())
);
}, null);
}
You may want to open up an issue here: https://github.com/Azure/azure-storage-php/issues and bring this to SDK team's attention.
There are 3 queues in redis.
If I insert a data at a same time with different browsers, both requests are accepted.
I get 2 duplicated records. Any helps?
For example, the first request is on the 1st queue.
At the second request, 2nd queue is searched for finding the data.
But the data doesn't exist in the queue.
The second request is inserted on the queue.
Is it understandable?
public function save($evt_no, $type = "redis") {
$name = '';
$res = true;
try{
$headers = getallheaders();
$bodys = $_REQUEST;
$session = $_SESSION;
foreach ($_FILES as $fileKey=>$fileVal) {
if ($fileVal['error'] == 0) {
try {
$uploaded_row = $this->fileL->upload('queueEventParticipant', $fileKey, array() ,'queue');
} catch (\Exception $ex) {
throw $ex;
}
$bodys['file'][_return_numeric($fileKey)] = $uploaded_row;
}
}
$data = array(
'header' => $headers,
'body' => $bodys,
'session' => $session
);
$data['body']['evt_no'] = $evt_no;
$data = json_encode($data);
if($type == "redis"){
$name = $this->attendQueueRedisService->setNewRsvp($data);
} else {
throw new \Exception("No exist");
}
} catch (\Exception $ex){
log_message("error", $ex->getMessage());
throw $ex;
}
if($res){
return $name;
} else {
return "Error";
}
}
class AttendQueueRedisService extends CI_Model {
private $redisClient;
private $redisConfig;
const PREFIX_DONE = 'done_';
const PREFIX_ERROR = 'error_';
public function __construct() {
parent::__construct();
if ($this->load->config('redis', true, true)) {
$this->redisConfig = $this->config->config['redis'];
}
$this->redisClient = new Redis();
$this->redisClient->connect($this->redisConfig['hostname'], $this->redisConfig['port']);
$this->redisClient->auth($this->redisConfig['auth']);
$this->redisClient->select($this->redisConfig['queue']);
}
public function setNewRsvp($data) {
$key = uniqid('rsvp_'.gethostname().'_',true).':redis';
$this->redisClient->set($key, $data, 60 * 30);
return $key;
}
}
So I created a Spreadsheet class that is a combination of a few solutions I found online for accessing Google Sheets API with PHP. It works.
class Spreadsheet {
private $token;
private $spreadsheet;
private $worksheet;
private $spreadsheetid;
private $worksheetid;
private $client_id = '<client id>';
private $service_account_name = '<service_account>'; // email address
private $key_file_location = 'key.p12'; //key.p12
private $client;
private $service;
public function __construct() {
$this->client = new Google_Client();
$this->client->setApplicationName("Sheets API Testing");
$this->service = new Google_Service_Drive($this->client);
$this->authenticate();
}
public function authenticate()
{
if (isset($_SESSION['service_token'])) {
$this->client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($this->key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$this->service_account_name,
array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds'), $key
);
$this->client->setAssertionCredentials($cred);
if ($this->client->getAuth()->isAccessTokenExpired()) {
$this->client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $this->client->getAccessToken();
// Get access token for spreadsheets API calls
$resultArray = json_decode($_SESSION['service_token']);
$this->token = $resultArray->access_token;
}
public function setSpreadsheet($title) {
$this->spreadsheet = $title;
return $this;
}
public function setSpreadsheetId($id) {
$this->spreadsheetid = $id;
return $this;
}
public function setWorksheet($title) {
$this->worksheet = $title;
return $this;
}
public function insert() {
if (!empty($this->token)) {
$url = $this->getPostUrl();
} else {
echo "Authentication Failed";
}
}
public function add($data) {
if(!empty($this->token)) {
$url = $this->getPostUrl();
if(!empty($url)) {
$columnIDs = $this->getColumnIDs();
if($columnIDs) {
$fields = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
foreach($data as $key => $value) {
$key = $this->formatColumnID($key);
if(in_array($key, $columnIDs)) {
$fields .= "<gsx:$key><![CDATA[$value]]></gsx:$key>";
}
}
$fields .= '</entry>';
$headers = [
"Authorization" => "Bearer $this->token",
'Content-Type' => 'application/atom+xml'
];
$method = 'POST';
$req = new Google_Http_Request($url, $method, $headers, $fields);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
var_dump($results);
}
}
}
}
private function getColumnIDs() {
$url = "https://spreadsheets.google.com/feeds/cells/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full?max-row=1";
$headers = array(
"Authorization" => "Bearer $this->token",
"GData-Version: 3.0"
);
$method = "GET";
$req = new Google_Http_Request($url, $method, $headers);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
if($results[2] == 200) {
$columnIDs = array();
$xml = simplexml_load_string($results[0]);
if($xml->entry) {
$columnSize = sizeof($xml->entry);
for($c = 0; $c < $columnSize; ++$c) {
$columnIDs[] = $this->formatColumnID($xml->entry[$c]->content);
}
}
return $columnIDs;
}
return "";
}
private function getPostUrl() {
if (empty($this->spreadsheetid)){
#find the id based on the spreadsheet name
$url = "https://spreadsheets.google.com/feeds/spreadsheets/private/full?title=" . urlencode($this->spreadsheet);
$method = 'GET';
$headers = ["Authorization" => "Bearer $this->token"];
$req = new Google_Http_Request($url, $method, $headers);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
if($results[2] == 200) {
$spreadsheetXml = simplexml_load_string($results[0]);
if($spreadsheetXml->entry) {
$this->spreadsheetid = basename(trim($spreadsheetXml->entry[0]->id));
$url = "https://spreadsheets.google.com/feeds/worksheets/" . $this->spreadsheetid . "/private/full";
if(!empty($this->worksheet)) {
$url .= "?title=" . $this->worksheet;
}
$req = new Google_Http_Request($url, $method, $headers);
$response = $curl->executeRequest($req);
if($response[2] == 200) {
$worksheetXml = simplexml_load_string($response[0]);
if($worksheetXml->entry) {
$this->worksheetid = basename(trim($worksheetXml->entry[0]->id));
}
}
}
}
}
if(!empty($this->spreadsheetid) && !empty($this->worksheetid)) {
return "https://spreadsheets.google.com/feeds/list/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full";
}
return "";
}
private function formatColumnID($val) {
return preg_replace("/[^a-zA-Z0-9.-]/", "", strtolower($val));
}
}
I then use this test php file to add rows to to my spreadsheet:
$Spreadsheet = new Spreadsheet();
$Spreadsheet->
setSpreadsheet("test spreadsheet")->
setWorksheet("Sheet1")->
add(array("name" => "Cell 1", "email" => "Cell 2"));
With this I can delete a row / update a row and append a row. However, the MAIN reason I needed this was to INSERT a row. Has anyone figured out a way to do this? Any language is fine although id prefer a php solution.
You can call an Apps Script stand alone script from PHP using an HTTPS GET or POST request. PHP can make a GET or POST request, and Apps Script can obviously insert the row anywhere using SpreadsheetApp service. You'll probably want to use Content Service also inside of the Apps Script code to get a return confirmation back that the code completed.
You might want to use a POST request for better security. So, again, you can use Apps Script as an intermediary between your PHP and your spreadsheet. The doPost() in the Apps Script file will need an event handler, normally assigned to the letter "e":
doPost(e) {
//Get e and retrieve what the code should do
//Insert the row
};
Also, see this answer:
Stackoverflow - Call a custom GAS function from external URL
I'm trying to figure out why the code below won't persist my $_SESSION['objSession'] object across pages unless i keep the serialize/unserialize in place below. I get tired of manually serializing/unserializing to make object changes in the session and people keep saying i shouldn't have to do it but i do see other complaints about session objects not persisting without it on the web including here on stack... PHP 5.3 Apache 2.2 Windows 2008.
<?php require_once("/php/php_clsSession.php");?>
<?php session_start(); ?>
<?php
// Session Object Create/Log
$objSession = new clsSession;
if ( !(isset($_SESSION['objSession']) )) {
// This line will populate some properties in the obj
// like Session_ID and Create_dt
$objSession->CreateSession(session_id(),$_SERVER);
}
else {
// this code will only run if the session is already
// set
$objSession = unserialize($_SESSION['objSession']);
$objSession->UpdateSession(session_id(),$_SERVER);
}
// Update Session Object
$_SESSION['objSession'] = serialize($objSession);
unset($objSession);
?>
---- clsSession Below this line... you can ignore the db include as the code has the same problem without using the db functionality and i have the db function temporarily commented anyhow....
<?php
// -----------------------------------------------------------------
// Program Type: Class
// Program Name: clsSession
// Program Date: 01/08/2012 Programmer: Tim Wiley
// Description: Standard class for session creation/update
// -----------------------------------------------------------------
class clsSession {
// Properties
public $Session_Id = null;
public $Creation_Dt = null;
public $Action_Dt = null;
public $Session_IP_Address = null;
public $Browser_Type = null;
public $Display_Resolution = null;
public $Is_Https_Ind = null;
public $Is_Logged_In_Ind = 0;
public $User_Key = null;
public $User_Id = null;
public $Email_Address = null;
public $Request_Method = null;
public $Page_Requested = null;
public $Page_Request_Params = null;
public $Page_Action = null;
public $Login_Attempts = 0;
public $Max_Login_Attempts = 3;
private function UpdateSessionClassData (&$xSessionId = null, &$xSessionObj = null, &$xPageAction = "N/A" ) {
$this->Session_Id = &$xSessionId;
$this->Action_Dt = date( 'Y-m-d H:i:s', time( ));
$this->Session_IP_Address = substr(trim(&$xSessionObj['REMOTE_ADDR']),0,24);
$this->Browser_Type = substr(trim(&$xSessionObj['HTTP_USER_AGENT']),0,140);
$this->Request_Method = substr(trim(&$xSessionObj['REQUEST_METHOD']),0,24);
$this->Page_Requested = substr(trim(&$xSessionObj['SCRIPT_NAME']),0,140);
$this->Page_Request_Params = substr(trim(&$xSessionObj['QUERY_STRING']),0,140);
$this->Is_Https_Ind = &$xSessionObj['SERVER_PORT'] == 443 ? 1 : 0;
if (is_null($this->Display_Resolution)) {
require_once('/javascript/js_SaveScreenResolutionInCookie.js');
$this->Display_Resolution = !( IS_NULL( $_COOKIE['users_resolution'] )) ? substr(trim($_COOKIE['users_resolution']),0,16) : "N/A";
}
$this->Page_Action = substr(trim(&$xPageAction),0,32);
}
// Initialize Session objSession for $_SESSION
public function CreateSession($xSessionId = null, &$xSessionObj = null ) {
$this->Creation_Dt = date( 'Y-m-d H:i:s', time( ));
$this->UpdateSessionClassData(&$xSessionId, &$xSessionObj);
// $this->WriteSessionToDb();
}
// Update Session objSession for $_SESSION
public function UpdateSession($xSessionId = null, &$xSessionObj = null, $xPageAction = "N/A" ) {
$this->UpdateSessionClassData(&$xSessionId, &$xSessionObj, &$xPageAction);
// $this->WriteSessionActivityToDb();
}
// Writes the session data to database
public function WriteSessionToDb($xUserType = "Web") {
$objConnect = new clsDb;
$objDb = $objConnect->GetDbConnection($xUserType);
//$objDb = $this->GetDbConnection($xUserType);
$_InsertSQL = new PDOStatement;
$_InsertSQL = $objDb->prepare("INSERT INTO T_SESSION_STATS(" .
"F_ACTION_DT, F_SESSION_ID, F_SESSION_IP_ADDRESS, F_BROWSER_TYPE," .
"F_DISPLAY_RESOLUTION, F_PAGE_REQUESTED, F_PAGE_REQUEST_PARAMS," .
"F_REQUEST_METHOD, F_IS_HTTPS_IND, F_IS_LOGGED_IN_IND, F_USER_KEY)" .
"Values (?,?,?,?,?,?,?,?,?,?,?)");
$_InsertSQL->bindParam(1, $this->Action_Dt );
$_InsertSQL->bindParam(2, $this->Session_Id );
$_InsertSQL->bindParam(3, $this->Session_IP_Address );
$_InsertSQL->bindParam(4, $this->Browser_Type );
$_InsertSQL->bindParam(5, $this->Display_Resolution );
$_InsertSQL->bindParam(6, $this->Page_Requested );
$_InsertSQL->bindParam(7, $this->Page_Request_Params );
$_InsertSQL->bindParam(8, $this->Request_Method );
$_InsertSQL->bindParam(9, $this->Is_Https_Ind );
$_InsertSQL->bindParam(10, $this->Is_Logged_In_Ind );
$_InsertSQL->bindParam(11, $this->User_Key );
try {
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$objDb->beginTransaction();
$_InsertSQL->execute();
$objDb->commit();
unset($objDb);
} catch (Exception $e) {
$objDb->rollBack();
echo "Failed: " . $e->getMessage();
unset($objDb);
unset($objConnect);
}
}
// Writes the session data to database
public function WriteSessionActivityToDb($xUserType = "Web",$xPageAction = "N/A") {
$objConnect = new clsDb;
$objDb = $objConnect->GetDbConnection($xUserType);
//$objDb = $this->GetDbConnection($xUserType);
$_InsertSQL = new PDOStatement;
$_InsertSQL = $objDb->prepare("INSERT INTO T_SESSION_ACTIVITIES(" .
"F_ACTION_DT, F_SESSION_ID, F_SESSION_IP_ADDRESS, " .
"F_PAGE_REQUESTED, F_PAGE_REQUEST_PARAMS," .
"F_REQUEST_METHOD, F_PAGE_ACTION, F_IS_HTTPS_IND, F_IS_LOGGED_IN_IND, F_USER_KEY)" .
"Values (?,?,?,?,?,?,?,?,?,?)");
$_InsertSQL->bindParam(1, $this->Action_Dt );
$_InsertSQL->bindParam(2, $this->Session_Id );
$_InsertSQL->bindParam(3, $this->Session_IP_Address );
$_InsertSQL->bindParam(4, $this->Page_Requested );
$_InsertSQL->bindParam(5, $this->Page_Request_Params );
$_InsertSQL->bindParam(6, $this->Request_Method );
$_InsertSQL->bindParam(7, substr(trim($xPageAction),0,32));
$_InsertSQL->bindParam(8, $this->Is_Https_Ind );
$_InsertSQL->bindParam(9, $this->Is_Logged_In_Ind );
$_InsertSQL->bindParam(10, $this->User_Key );
try {
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$objDb->beginTransaction();
$_InsertSQL->execute();
$objDb->commit();
unset($objDb);
unset($objConnect);
} catch (Exception $e) {
$objDb->rollBack();
unset($objDb);
echo "Failed: " . $e->getMessage();
}
}
}
?>
The issue seems to be in your clsSession class. This is using &. Since the session object is serialized these references aren't stored correctly. Try removing these (i.e. change UpdateSessionClassData and UpdateSession to remove the & from parameters) and see if this sorts the issue.
to start, put session_start(); before require_once and add var_dump($_SESSION) for debug.