Skip to content

Instantly share code, notes, and snippets.

@jaketoolson
Created October 31, 2012 16:39
Show Gist options
  • Save jaketoolson/3988151 to your computer and use it in GitHub Desktop.
Save jaketoolson/3988151 to your computer and use it in GitHub Desktop.
PHP Sample code4
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Derived from ASP.NET Setup
*
* The library contains login, logout, xml helpers, and sessionchecking functions and no other non-authentication methods should be here.
* Other methods needing to be added here should just extend this library for tidyness sake otherwise containing all license service methods
* within this library would be overwhelming.
*
* This library interacts with a remote licensing service through SOAP which brokers or interacts with Salesforce as
* all the data we are retrieving and storing resides on the salesforce.com servers. Because of this, it should expected for
* page loads to take a few milliseconds longer than a regular site interacting with a local database.
*
* The SOAPObject holds the required SOAP Headers as per the licensing service and Salesforce. This object is stored by reference in the
* session for additional referencing.
*
*
* @author jake
*/
class License_service
{
protected $ci;
protected $errors = array();
protected $messages;
// holds the SoapClient object
protected $objLicense;
// holds the SoapHeaders object
protected $objLicenseHeaders;
private $sessionExists = '';
// IMPORTANT: ?WSDL must be in the URL string
public $licenseURL = 'somesite?WSDL';
// License Service namespace
public $nameSpace = 'LicenseNameSpace###';
// required headers for SOAP requests
protected $headerBody = array(
'KID' => '###',
'PW' => '###',
'UN' => '###',
'Username' => '###',
'Password' => '###',
'Hardware' => '###',
'ServerUrl' => '',
'SessionID' => ''
);
protected $xmlWrapper_open = '<DataSet xmlns="http://Service">';
protected $xmlWrapper_close = '</DataSet>';
// user account details
public $strCompany = '';
public $bIsGod = false;
public $strURL = '';
public $strSessionId = '';
public $strUserId = '';
public $strAccountId = '';
public $strUsername = '';
public $strRegion = '';
public $bIsManager = null;
public $strHardwareId = '###';
public $licenseError = null;
public function __construct()
{
$this->ci =& get_instance();
$this->ci->load->model('ls_model');
}
/**
* If the session already exists, retrieve the
*
* @return void
*/
public function buildSession()
{
if($this->_sessionExists())
{
// Replace current ServerURL and SessionID with those already stored in Session
$this->$headerBody['ServerUrl'] = $this->ci->session->userdata('ServerUrl');
$this->$headerBody['SessionID'] = $this->ci->session->userdata('SessionID');
$this->objLicense =& $this->ci->session->userdata('licenseSessionObject');
}
else
{
$this->buildSoapHeaders();
}
}
/**
* All License Server functions accessed via SOAP require valid Headers.
* The header information is built and stored below.
*
* SOAP first connects and is returned a SOAP License Server session id
* and url. This is then appended to the SOAP headers completing the required headers.
*
* the SOAP license server object is stored to the session and the class.
*
* @return void
*/
public function buildSoapHeaders()
{
// need to initialize a session on the SOAP/salesforce end
if ( ! $this->_sessionExists())
{
$client = new SoapClient($this->licenseURL);
$header = new SoapHeader($this->nameSpace, 'AuthHeader', $this->headerBody);
$client->__setSoapHeaders($header);
$result = $client->InitializeSession();
$this->headerBody['ServerUrl'] = $result->strURL;
$this->headerBody['SessionID'] = $result->strSessionID;
$this->ci->session->set_userdata('ServerUrl', $result->strURL);
$this->ci->session->set_userdata('SessionID', $result->strSessionID);
$header = new SoapHeader($this->nameSpace, 'AuthHeader', $this->headerBody);
$client->__setSoapHeaders($header);
// push the SoapClient Object to a variable by reference
$this->objLicense =& $client;
// save object to session
$this->ci->session->set_userdata('licenseSessionObject', $this->objLicense);
return;
}
// by reference
$this->objLicense =& $this->ci->session->userdata('licenseSessionObject');
return;
// TODO: Need pretty error_handlers or loggers
//var_dump($client->__getLastRequest());
//var_dump($client->__getLastRequestHeaders());
//var_dump($exception);
//exit;
}
/**
* Password must be base64_encrypted
*
* @return boolean
*/
public function processWebsiteLogin($userEmail = '', $password = '')
{
$this->buildSession();
// pass array with username and encrypted password
// to license server 'getUserInfo' function.
$userinfo = array(
'oError' => '',
'strUserEmail' => $userEmail,
'strPassword' => base64_encode($password),
'strUserId' => '',
'strCompanyId' => '',
'strUserName' => '',
'strCompany' => '',
'bIsManager' => ''
);
$result = $this->objLicense->getUserInfo($userinfo);
// userEmail doesn't exist, or nothing found do not process login.
if ($result->GetUserInfoResult === false)
{
//$logout = $this->objLicense->LogoutSession($userinfo);
$this->processLogout();
$this->ci->session->set_flashdata('message', 'An error occured, please try again');
return false;
}
else
{
// Retrieve LatestMaintenanceDate info.
$userinfoDate = array(
'oError' => '',
'strCompanyId' => $result->strCompanyId
);
$dateResult = $this->objLicense->LatestMaintenanceDate($userinfoDate);
// TODO: create error/statuscode handler static.
if ($dateResult->oError->StatusCode == 0)
{
$maintainenceDate = $dateResult->LatestMaintenanceDateResult;
}
else
{
$maintainenceData = 'none';
}
// store user details to session array called 'licenseSession'
$sessionData = array(
'strCompany' => $result->strCompany,
'strCompanyId' => $result->strCompanyId,
'bIsManager' => $result->bIsManager,
'strUserId' => $result->strUserId,
'strUserName' => $result->strUserName,
'strNickName' => (isset ($result->strNickName) ? $result->strNickName : ''),
'maintDate' => $maintainenceDate
);
$this->ci->session->set_userdata('licenseSession', $sessionData);
return true;
}
}
/**
* Destroy all session data, include local session and soap License server session.
*
* @return boolean
*/
public function processLogout()
{
$this->buildSession();
// logout of SOAP license server
$logout = $this->objLicense->LogoutSession();
// remove session userdata
$this->ci->session->unset_userdata('licenseSession');
$this->ci->session->unset_userdata('licenseSessionObject');
$this->ci->session->unset_userdata('ServerUrl');
$this->ci->session->unset_userdata('SessionID');
// destroy session completely
$this->ci->session->sess_destroy();
$this->objLicense = null;
//$this->set_message('logout_successful');
return true;
}
/**
* Wraps XML roots with parent root.
* $xml param must be string.
*
* @param string $xml
* @return string
*/
private function _xmlWrapper($xml = '')
{
if ( ! empty($xml))
{
return $this->xmlWrapper_open.$xml.$this->xmlWrapper_close;
}
}
public function _checkLoggedIn()
{
return (bool) $this->ci->session->userdata('licenseSession');
}
/**
* Even if there is a valid PHP session or cookie, this doesn't mean the SOAP session still exists
* or is valid, so check if the session object exists and the SessionID property exists within the object.
*
* @return boolean
*/
private function _sessionExists()
{
$check = $this->ci->session->userdata('licenseSessionObject');
if (@property_exists($check, 'SessionID'))
{
return true;
}
return false;
}
}
/* End of file License_service.php */
/* Location: ./application/libraries/License_service.php */
// test
public function getProducts($returnType = 'obj')
{
$issueInfo = array(
'oError' => '',
'strRegion' => ''
);
$results = $this->objLicense->GetProducts($issueInfo);
if ( $results->oError->StatusCode <> 0)
{
echo $results->oError->Error;
}
else
{
// http://stackoverflow.com/questions/6838274/why-wont-simplexml-convert-this-xml-to-something-usable
// http://blog.sherifmansour.com/?p=302
$xmlString = $this->_xmlWrapper($results->GetProductsResult->any);
$xmlString = simplexml_load_string($xmlString);
$elements = $xmlString->children('urn:schemas-microsoft-com:xml-diffgram-v1')->children();
if ($returnType == 'array')
{
// convert Object to Array
// TODO: Build this out as a function.
$json = json_encode($elements);
$array = json_decode($json,TRUE);
return $array;
}
else
{
return $elements;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment