lib/PPConnectionManager.php 0000666 00000001534 13436755715 0011704 0 ustar 00 setHttpTimeout( $config["http.ConnectionTimeOut"] );
}
if(isset( $config["http.Proxy"] )) {
$httpConfig->setHttpProxy($config["http.Proxy"] );
}
if(isset( $config["http.Retry"] )) {
$retry = $config["http.Retry"];
$httpConfig->setHttpRetryCount($retry ) ;
}
return new PPHttpConnection($httpConfig, $config);
}
}
lib/PPHttpConfig.php 0000666 00000007150 13436755715 0010357 0 ustar 00 3,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 60, // maximum number of seconds to allow cURL functions to execute
CURLOPT_USERAGENT => 'PayPal-PHP-SDK',
CURLOPT_HTTPHEADER => array(),
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => 1
);
const HEADER_SEPARATOR = ';';
const HTTP_GET = 'GET';
const HTTP_POST = 'POST';
private $headers = array();
private $curlOptions;
private $url;
private $method;
/***
* Number of times to retry a failed HTTP call
*/
private $retryCount;
/**
*
* @param string $url
* @param string $method HTTP method (GET, POST etc) defaults to POST
*/
public function __construct($url=null, $method=self::HTTP_POST) {
$this->url = $url;
$this->method = $method;
$this->curlOptions = self::$DEFAULT_CURL_OPTS;
}
public function getUrl() {
return $this->url;
}
public function getMethod() {
return $this->method;
}
public function getHeaders() {
return $this->headers;
}
public function getHeader($name) {
if(array_key_exists($name, $this->headers)) {
return $this->headers[$name];
}
return NULL;
}
public function setUrl($url) {
$this->url = $url;
}
public function setHeaders(array $headers) {
$this->headers = $headers;
}
public function addHeader($name, $value, $overWrite=true) {
if(!array_key_exists($name, $this->headers) || $overWrite) {
$this->headers[$name] = $value;
} else {
$this->headers[$name] = $this->headers[$name] . self::HEADER_SEPARATOR . $value;
}
}
public function removeHeader($name) {
unset($this->headers[$name]);
}
public function getCurlOptions() {
return $this->curlOptions;
}
public function addCurlOption($name, $value) {
$this->curlOptions[$name] = $value;
}
public function setCurlOptions($options) {
$this->curlOptions = $options;
}
/**
* Set ssl parameters for certificate based client authentication
*
* @param string $certPath - path to client certificate file (PEM formatted file)
*/
public function setSSLCert($certPath, $passPhrase=NULL) {
$this->curlOptions[CURLOPT_SSLCERT] = realpath($certPath);
if(isset($passPhrase) && trim($passPhrase) != "") {
$this->curlOptions[CURLOPT_SSLCERTPASSWD] = $passPhrase;
}
}
/**
* Set connection timeout in seconds
* @param integer $timeout
*/
public function setHttpTimeout($timeout) {
$this->curlOptions[CURLOPT_CONNECTTIMEOUT] = $timeout;
}
/**
* Set HTTP proxy information
* @param string $proxy
* @throws PPConfigurationException
*/
public function setHttpProxy($proxy) {
$urlParts = parse_url($proxy);
if($urlParts == false || !array_key_exists("host", $urlParts))
throw new PPConfigurationException("Invalid proxy configuration ".$proxy);
$this->curlOptions[CURLOPT_PROXY] = $urlParts["host"];
if(isset($urlParts["port"]))
$this->curlOptions[CURLOPT_PROXY] .= ":" . $urlParts["port"];
if(isset($urlParts["user"]))
$this->curlOptions[CURLOPT_PROXYUSERPWD] = $urlParts["user"] . ":" . $urlParts["pass"];
}
/**
* @param integer $retry
*/
public function setHttpRetryCount($retryCount) {
$this->retryCount = $retryCount;
}
public function getHttpRetryCount() {
return $this->retryCount;
}
/**
* Sets the User-Agent string on the HTTP request
* @param string $userAgentString
*/
public function setUserAgent($userAgentString) {
$this->curlOptions[CURLOPT_USERAGENT] = $userAgentString;
}
}
lib/PPHttpConnection.php 0000666 00000006560 13436755715 0011255 0 ustar 00 httpConfig = $httpConfig;
$this->logger = new PPLoggingManager(__CLASS__, $config);
}
private function getHttpHeaders() {
$ret = array();
foreach($this->httpConfig->getHeaders() as $k=>$v) {
$ret[] = "$k: $v";
}
return $ret;
}
/**
* Executes an HTTP request
*
* @param string $data query string OR POST content as a string
* @throws PPConnectionException
*/
public function execute($data) {
$this->logger->fine("Connecting to " . $this->httpConfig->getUrl());
$this->logger->fine("Payload " . $data);
$ch = curl_init($this->httpConfig->getUrl());
curl_setopt_array($ch, $this->httpConfig->getCurlOptions());
curl_setopt($ch, CURLOPT_URL, $this->httpConfig->getUrl());
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHttpHeaders());
switch($this->httpConfig->getMethod()) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;
}
if($this->httpConfig->getMethod() != NULL) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->httpConfig->getMethod());
}
foreach($this->getHttpHeaders() as $header) {
//TODO: Strip out credentials and other secure info when logging.
$this->logger->info("Adding header $header");
}
$result = curl_exec($ch);
if (curl_errno($ch) == 60) {
$this->logger->info("Invalid or no certificate authority found - Retrying using bundled CA certs file");
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/cacert.pem');
$result = curl_exec($ch);
}
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$retries = 0;
if(in_array($httpStatus, self::$retryCodes) && $this->httpConfig->getHttpRetryCount() != null) {
$this->logger->info("Got $httpStatus response from server. Retrying");
do {
$result = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
} while (in_array($httpStatus, self::$retryCodes) && (++$retries < $this->httpConfig->getHttpRetryCount()) );
}
if ( curl_errno($ch) ) {
$ex = new PPConnectionException($this->httpConfig->getUrl(), curl_error($ch), curl_errno($ch));
curl_close($ch);
throw $ex;
}
curl_close($ch);
if(in_array($httpStatus, self::$retryCodes)) {
$ex = new PPConnectionException($this->httpConfig->getUrl() ,
"Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}. Retried $retries times.");
$ex->setData($result);
throw $ex;
} else if($httpStatus < 200 || $httpStatus >=300) {
$ex = new PPConnectionException($this->httpConfig->getUrl() ,
"Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}.");
$ex->setData($result);
throw $ex;
}
return $result;
}
}
lib/transport/PPRestCall.php 0000666 00000002220 13436755715 0012050 0 ustar 00 apiContext = $apiContext;
$this->logger = new PPLoggingManager(__CLASS__, $apiContext->getConfig());
}
/**
* @param array $handlers array of handlers
* @param string $path Resource path relative to base service endpoint
* @param string $method HTTP method - one of GET, POST, PUT, DELETE, PATCH etc
* @param string $data Request payload
* @param array $headers HTTP headers
*/
public function execute($handlers, $path, $method, $data='', $headers=array()) {
$config = $this->apiContext->getConfig();
$httpConfig = new PPHttpConfig(null, $method);
$httpConfig->setHeaders($headers +
array(
'Content-Type' => 'application/json'
)
);
foreach($handlers as $handler) {
$handler->handle($httpConfig, $data, array('path' => $path, 'apiContext' => $this->apiContext));
}
$connection = new PPHttpConnection($httpConfig, $config);
$response = $connection->execute($data);
$this->logger->fine($response);
return $response;
}
}
lib/PPUtils.php 0000666 00000016223 13436755715 0007413 0 ustar 00 $v) {
preg_match($pattern, $k, $matches);
if (count($matches) > 0) {
return true;
}
}
return false;
}
/**
* Get the local IP address. The client address is a required
* request parameter for some API calls
*/
public static function getLocalIPAddress()
{
if (array_key_exists("SERVER_ADDR", $_SERVER)) {
// SERVER_ADDR is available only if we are running the CGI SAPI
return $_SERVER['SERVER_ADDR'];
} else {
if (function_exists("gethostname")) {
// gethostname is available only in PHP >= v5.3
return gethostbyname(gethostname());
} else {
// fallback if nothing works
return "127.0.0.1";
}
}
}
/**
* Convert xml string to an intermediate nested array
* representation that can be iterated
*
* @param string $xmlInput XML string to convert
*/
public static function xmlToArray($xmlInput)
{
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML($xmlInput);
$results = $doc->getElementsByTagName("Body");
if($results->length > 0 ){
$node = $results->item(0);
return PPUtils::xmlNodeToArray($node);
} else {
throw new Exception("Unrecognized response payload ");
}
}
/**
* Convert a DOM node to an intermediate nested array
* representation that can be iterated
*
* @param DOMNode $node DOM node to convert
*/
private static function xmlNodeToArray($node)
{
$result = array();
$children = $node->childNodes;
if(!empty($children))
{
for($i = 0; $i < (int)$children->length; $i++)
{
$child = $children->item($i);
if($child !== null)
{
if($child->childNodes->item(0) instanceof \DOMText )
{
$result[$i]['name'] = $child->nodeName;
$result[$i]['text'] = $child->childNodes->item(0)->nodeValue;
if($child->hasAttributes()) {
foreach($child->attributes as $k => $v) {
if($v->namespaceURI != 'http://www.w3.org/2001/XMLSchema-instance') {
$result[$i]['attributes'][$v->name] = $v->value;
}
}
}
}
else if(!in_array($child->nodeName, $result))
{
$result[$i]['name'] = $child->nodeName;
$result[$i]['children'] = PPUtils::xmlNodeToArray($child);
if($child->hasAttributes())
{
$attrs = $child->attributes;
foreach($attrs as $k => $v)
{
if($v->namespaceURI != 'http://www.w3.org/2001/XMLSchema-instance')
{
$result[$i]['attributes'][$v->name] = $v->value;
}
}
}
}
}
}
}
return $result;
}
/**
* Escapes invalid xml characters
*
* @param $textContent = xml data to be escaped
* @return string
*/
public static function escapeInvalidXmlCharsRegex($textContent)
{
return htmlspecialchars($textContent, (1 | 2), 'UTF-8', false);
}
/**
* Filter an array based on keys that match given prefix
*
* @param array $map
* @param string $keyPrefix
* @return array
*/
public static function filterKeyPrefix(array $map, $keyPrefix)
{
$filtered = array();
foreach ($map as $key => $val) {
if (($pos = stripos($key, $keyPrefix)) !== 0) {
continue;
}
$filtered[substr_replace($key, '', 0, strlen($keyPrefix))] = $val;
}
return $filtered;
}
/**
* @var array|ReflectionProperty[]
*/
private static $propertiesRefl = array();
/**
* @var array|string[]
*/
private static $propertiesType = array();
/**
* Get property annotations for a certain property in a class
*
* @param string $class
* @param string $propertyName
* @throws RuntimeException
* @return string
*/
public static function propertyAnnotations($class, $propertyName)
{
$class = is_object($class) ? get_class($class) : $class;
if (!class_exists('ReflectionProperty')) {
throw new RuntimeException("Property type of " . $class . "::{$propertyName} cannot be resolved");
}
if ($annotations =& self::$propertiesType[$class][$propertyName]) {
return $annotations;
}
if (!($refl =& self::$propertiesRefl[$class][$propertyName])) {
$refl = new ReflectionProperty($class, $propertyName);
}
// todo: smarter regexp
if (!preg_match_all('~\@([^\s@\(]+)[\t ]*(?:\(?([^\n@]+)\)?)?~i', $refl->getDocComment(), $annots, PREG_PATTERN_ORDER)) {
return NULL;
}
foreach ($annots[1] as $i => $annot) {
$annotations[strtolower($annot)] = empty($annots[2][$i]) ? TRUE : rtrim($annots[2][$i], " \t\n\r)");
}
return $annotations;
}
/**
* Determine if a property in a given class is a
* attribute type.
*
* @param string $class
* @param string $propertyName
* @return string
*/
public static function isAttributeProperty($class, $propertyName) {
if (($annotations = self::propertyAnnotations($class, $propertyName))) {
return array_key_exists('attribute', $annotations);
}
return FALSE;
}
/**
* Determine if a property in a given class is a
* collection type.
*
* @param string $class
* @param string $propertyName
* @return string
*/
public static function isPropertyArray($class, $propertyName) {
if (($annotations = self::propertyAnnotations($class, $propertyName))) {
if (isset($annotations['var']) && substr($annotations['var'], -2) === '[]') {
return TRUE;
} elseif (isset($annotations['array'])) {
return TRUE;
}
}
return FALSE;
}
/**
* Get data type of a property in a given class
*
* @param string $class
* @param string $propertyName
* @throws RuntimeException
* @return string
*/
public static function propertyType($class, $propertyName)
{
if (($annotations = self::propertyAnnotations($class, $propertyName)) && isset($annotations['var'])) {
if (substr($annotations['var'], -2) === '[]') {
return substr($annotations['var'], 0, -2);
}
return $annotations['var'];
}
return 'string';
}
/**
*
* @param object $object
* @return array
*/
public static function objectProperties($object)
{
$props = array();
foreach (get_object_vars($object) as $property => $default) {
$annotations = self::propertyAnnotations($object, $property);
if (isset($annotations['name'])) {
$props[strtolower($annotations['name'])] = $property;
}
$props[strtolower($property)] = $property;
}
return $props;
}
/**
* Convert all array keys to lowercase
*
* @param array $array
* @return array
*/
public static function lowerKeys(array $array)
{
$ret = array();
foreach ($array as $key => $value) {
$ret[strtolower($key)] = $value;
}
return $ret;
}
}
lib/PPConfigManager.php 0000666 00000005061 13436755715 0011011 0 ustar 00 "30",
"http.Retry" => "5",
);
/**
* @var PPConfigManager
*/
private static $instance;
private function __construct(){
if(defined('PP_CONFIG_PATH')) {
$configFile = constant('PP_CONFIG_PATH') . '/sdk_config.ini';
} else {
$configFile = implode(DIRECTORY_SEPARATOR,
array(dirname(__FILE__), "..", "config", "sdk_config.ini"));
}
$this->load($configFile);
}
// create singleton object for PPConfigManager
public static function getInstance()
{
if ( !isset(self::$instance) ) {
self::$instance = new PPConfigManager();
}
return self::$instance;
}
//used to load the file
private function load($fileName) {
$this->config = @parse_ini_file($fileName);
if($this->config == NULL || count($this->config) == 0) {
throw new PPConfigurationException("Config file $fileName not found","303");
}
}
/**
* simple getter for configuration params
* If an exact match for key is not found,
* does a "contains" search on the key
*/
public function get($searchKey){
if(array_key_exists($searchKey, $this->config))
{
return $this->config[$searchKey];
}
else {
$arr = array();
foreach ($this->config as $k => $v){
if(strstr($k, $searchKey)){
$arr[$k] = $v;
}
}
return $arr;
}
}
/**
* Utility method for handling account configuration
* return config key corresponding to the API userId passed in
*
* If $userId is null, returns config keys corresponding to
* all configured accounts
*/
public function getIniPrefix($userId = null) {
if($userId == null) {
$arr = array();
foreach ($this->config as $key => $value) {
$pos = strpos($key, '.');
if(strstr($key, "acct")){
$arr[] = substr($key, 0, $pos);
}
}
return array_unique($arr);
} else {
$iniPrefix = array_search($userId, $this->config);
$pos = strpos($iniPrefix, '.');
$acct = substr($iniPrefix, 0, $pos);
return $acct;
}
}
/**
* returns the config file hashmap
*
*/
private function getConfigHashmap()
{
return $this->config;
}
/**
* use the default configuration if it is not passed in hashmap
*/
public static function getConfigWithDefaults($config=null)
{
return array_merge(PPConfigManager::$defaults,
($config != null) ? $config : PPConfigManager::getInstance()->getConfigHashmap());
}
}
lib/exceptions/PPMissingCredentialException.php 0000666 00000000522 13436755715 0015752 0 ustar 00 getLine().' in '.$this->getFile()
.': '.$this->getMessage().'';
return $errorMsg;
}
} lib/exceptions/PPInvalidCredentialException.php 0000666 00000000522 13436755715 0015727 0 ustar 00 getLine().' in '.$this->getFile()
.': '.$this->getMessage().'';
return $errorMsg;
}
} lib/exceptions/PPConfigurationException.php 0000666 00000000234 13436755715 0015155 0 ustar 00 getLine().' in '.$this->getFile()
.': '.$this->getMessage().'';
return $errorMsg;
}
} lib/exceptions/PPConnectionException.php 0000666 00000001060 13436755715 0014443 0 ustar 00 url = $url;
}
public function setData($data) {
$this->data = $data;
}
public function getData() {
return $this->data;
}
public function getUrl() {
return $this->url;
}
} lib/PPAPIService.php 0000666 00000004531 13436755715 0010244 0 ustar 00 apiContext = $apiContext;
$this->serviceName = $serviceName;
$this->port = $port;
$this->logger = new PPLoggingManager(__CLASS__, $this->apiContext->getConfig());
$this->handlers = $handlers;
$this->serviceBinding = $serviceBinding;
}
public function setServiceName($serviceName) {
$this->serviceName = $serviceName;
}
/**
* Register additional handlers to run before
* executing this call
*
* @param IPPHandler $handler
*/
public function addHandler($handler) {
$this->handlers[] = $handler;
}
/**
* Execute an api call
*
* @param string $apiMethod Name of the API operation (such as 'Pay')
* @param PPRequest $params Request object
* @return array containing request and response
*/
public function makeRequest($apiMethod, $request) {
$this->apiMethod = $apiMethod;
$httpConfig = new PPHttpConfig(null, PPHttpConfig::HTTP_POST);
if($this->apiContext->getHttpHeaders() != null) {
$httpConfig->setHeaders($this->apiContext->getHttpHeaders());
}
$this->runHandlers($httpConfig, $request);
// Serialize request object to a string according to the binding configuration
$formatter = FormatterFactory::factory($this->serviceBinding);
$payload = $formatter->toString($request);
// Execute HTTP call
$connection = PPConnectionManager::getInstance()->getConnection($httpConfig, $this->apiContext->getConfig());
$this->logger->info("Request: $payload");
$response = $connection->execute($payload);
$this->logger->info("Response: $response");
return array('request' => $payload, 'response' => $response);
}
private function runHandlers($httpConfig, $request) {
$options = $this->getOptions();
foreach($this->handlers as $handlerClass) {
$handlerClass->handle($httpConfig, $request, $options);
}
}
private function getOptions()
{
return array(
'port' => $this->port,
'serviceName' => $this->serviceName,
'serviceBinding' => $this->serviceBinding,
'config' => $this->apiContext->getConfig(),
'apiMethod' => $this->apiMethod,
'apiContext' => $this->apiContext
);
}
}
lib/PPBaseService.php 0000666 00000003072 13436755715 0010504 0 ustar 00 lastRequest;
}
public function getLastResponse() {
return $this->lastResponse;
}
public function getServiceName() {
return $this->serviceName;
}
public function __construct($serviceName, $serviceBinding, $config=null) {
$this->serviceName = $serviceName;
$this->serviceBinding = $serviceBinding;
$this->config = $config;
}
/**
*
* @param string $method - API method to call
* @param object $requestObject Request object
* @param apiContext $apiContext object containing credential and SOAP headers
* @param mixed $apiUserName - Optional API credential - can either be
* a username configured in sdk_config.ini or a ICredential object created dynamically
*/
public function call($port, $method, $requestObject, $apiContext, $handlers) {
if($apiContext == null)
{
$apiContext = new PPApiContext(PPConfigManager::getConfigWithDefaults($this->config));
}
if($apiContext->getConfig() == null )
{
$apiContext->setConfig(PPConfigManager::getConfigWithDefaults($this->config));
}
$service = new PPAPIService($port, $this->serviceName,
$this->serviceBinding, $apiContext, $handlers);
$ret = $service->makeRequest($method, new PPRequest($requestObject, $this->serviceBinding));
$this->lastRequest = $ret['request'];
$this->lastResponse = $ret['response'];
return $this->lastResponse;
}
}
lib/PPConstants.php 0000666 00000002026 13436755715 0010263 0 ustar 00 loggerName = $loggerName;
$config = PPConfigManager::getConfigWithDefaults($config);
$this->isLoggingEnabled = (array_key_exists('log.LogEnabled', $config) && $config['log.LogEnabled'] == '1');
if($this->isLoggingEnabled) {
$this->loggerFile = ($config['log.FileName']) ? $config['log.FileName'] : ini_get('error_log');
$loggingLevel = strtoupper($config['log.LogLevel']);
$this->loggingLevel = (isset($loggingLevel) && defined("PPLoggingLevel::$loggingLevel")) ? constant("PPLoggingLevel::$loggingLevel") : PPLoggingManager::DEFAULT_LOGGING_LEVEL;
}
}
private function log($message, $level=PPLoggingLevel::INFO) {
if($this->isLoggingEnabled && ($level <= $this->loggingLevel)) {
error_log( $this->loggerName . ": $message\n", 3, $this->loggerFile);
}
}
public function error($message) {
$this->log($message, PPLoggingLevel::ERROR);
}
public function warning($message) {
$this->log($message, PPLoggingLevel::WARN);
}
public function info($message) {
$this->log($message, PPLoggingLevel::INFO);
}
public function fine($message) {
$this->log($message, PPLoggingLevel::FINE);
}
}
lib/PPMessage.php 0000666 00000007167 13436755715 0007706 0 ustar 00 $defaultValue) {
if (($propertyValue = $this->{$property}) === NULL || $propertyValue == NULL) {
continue;
}
if (is_object($propertyValue)) {
$nvp[] = $propertyValue->toNVPString($prefix . $property . '.'); // prefix
} elseif (is_array($defaultValue) || is_array($propertyValue)) {
foreach (array_values($propertyValue) as $i => $item) {
if (!is_object($item)){
$nvp[] = $prefix . $property . "($i)" . '=' . urlencode($item);
}else{
$nvp[] = $item->toNVPString($prefix . $property . "($i).");
}
}
} else {
// Handle classes with attributes
if($property == 'value' && ($anno = PPUtils::propertyAnnotations($this, $property)) != NULL && isset($anno['value']) ) {
$nvpKey = substr($prefix, 0, -1); // Remove the ending '.'
} else {
$nvpKey = $prefix . $property ;
}
$nvp[] = $nvpKey . '=' . urlencode($propertyValue);
}
}
return implode('&', $nvp);
}
/**
* @param array $map
* @param string $prefix
*/
public function init(array $map = array(), $prefix = '')
{
if (empty($map)) {
return;
}
$map = PPUtils::lowerKeys($map);
foreach (get_object_vars($this) as $property => $defaultValue) {
if (array_key_exists($propKey = strtolower($prefix . $property), $map) &&
$this->isBuiltInType(($type = PPUtils::propertyType($this, $property)))){
$type = PPUtils::propertyType($this, $property);
$this->{$property} = urldecode($map[$propKey]);
continue; // string
} elseif (!$filtered = PPUtils::filterKeyPrefix($map, $propKey)) {
continue; // NULL
}
if (!$this->isBuiltInType($type = PPUtils::propertyType($this, $property), false) && !class_exists($type)) {
trigger_error("Class $type not found.", E_USER_NOTICE);
continue; // just ignore
}
if (is_array($defaultValue) || PPUtils::isPropertyArray($this, $property)) { // array of objects
if($this->isBuiltInType($type)) { // Array of simple types
foreach($filtered as $key => $value) {
$this->{$property}[trim($key, "()")] = urldecode($value);
}
} else { // Array of complex objects
$delim = '.';
for ($i = 0; $itemValues = PPUtils::filterKeyPrefix($filtered, "($i)") ;$i++) {
$this->{$property}[$i] = $item = new $type();
$item->init(PPUtils::filterKeyPrefix($itemValues, "."));
if(array_key_exists("", $itemValues)) {
$item->value = urldecode($itemValues[""]);
}
}
// Handle cases where we have a list of objects
// with just the value present and all attributes values are null
foreach($filtered as $key => $value) {
$idx = trim($key, "()");
if(is_numeric($idx) && (is_null($this->{$property}) || !array_key_exists($idx, $this->{$property})) ) {
$this->{$property}[$idx] = new $type;
$this->{$property}[$idx]->value = urldecode($value);
}
}
}
} else { // one object
$this->{$property} = new $type();
$this->{$property}->init(PPUtils::filterKeyPrefix($filtered, '.')); // unprefix
if(array_key_exists("", $filtered)) {
$this->{$property}->value = urldecode($filtered[""]);
}
}
}
}
private function isBuiltInType($typeName) {
static $types = array('string', 'int', 'integer', 'bool', 'boolean', 'float', 'decimal', 'long', 'datetime', 'double');
return in_array(strtolower($typeName), $types);
}
}
lib/handlers/PPAuthenticationHandler.php 0000666 00000002537 13436755715 0014373 0 ustar 00 getCredential();
if(isset($credential)) {
$thirdPartyAuth = $credential->getThirdPartyAuthorization();
if($thirdPartyAuth && $thirdPartyAuth instanceof PPTokenAuthorization) {
$authSignature = AuthSignature::generateFullAuthString($credential->getUsername(), $credential->getPassword(), $thirdPartyAuth->getAccessToken(), $thirdPartyAuth->getTokenSecret(), $httpConfig->getMethod(), $httpConfig->getUrl());
if(isset($options['port']) &&
($options['port'] == 'PayPalAPI' || $options['port'] == 'PayPalAPIAA')) {
$httpConfig->addHeader('X-PP-AUTHORIZATION', $authSignature);
}
else {
$httpConfig->addHeader('X-PAYPAL-AUTHORIZATION', $authSignature);
}
}
if($credential instanceof PPSignatureCredential) {
$handler = new PPSignatureAuthHandler($credential);
} else if($credential instanceof PPCertificateCredential) {
$handler = new PPCertificateAuthHandler($credential);
} else {
throw new PPInvalidCredentialException();
}
$handler->handle($httpConfig, $request, $options);
}
}
}
lib/handlers/PPOpenIdHandler.php 0000666 00000002742 13436755715 0012570 0 ustar 00 getConfig();
$httpConfig->setUrl(
rtrim(trim($this->_getEndpoint($config)), '/') .
(isset($options['path']) ? $options['path'] : '')
);
if(!array_key_exists("Authorization", $httpConfig->getHeaders())) {
$auth = base64_encode($config['acct1.ClientId'] . ':' . $config['acct1.ClientSecret']);
$httpConfig->addHeader("Authorization", "Basic $auth");
}
if(!array_key_exists("User-Agent", $httpConfig->getHeaders())) {
$httpConfig->addHeader("User-Agent", PPUserAgent::getValue(self::$sdkName, self::$sdkVersion));
}
}
private function _getEndpoint($config) {
if (isset($config['openid.EndPoint'])) {
return $config['openid.EndPoint'];
} else if (isset($config['service.EndPoint'])) {
return $config['service.EndPoint'];
} else if (isset($config['mode'])) {
switch (strtoupper($config['mode'])) {
case 'SANDBOX':
return PPConstants::REST_SANDBOX_ENDPOINT;
case 'LIVE':
return PPConstants::REST_LIVE_ENDPOINT;
default:
throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live');
}
} else {
throw new PPConfigurationException('You must set one of service.endpoint or mode parameters in your configuration');
}
}
}
lib/handlers/IPPHandler.php 0000666 00000000252 13436755715 0011574 0 ustar 00 apiUsername = $apiUsername;
}
public function handle($httpConfig, $request, $options) {
parent::handle($httpConfig, $request, $options);
if(is_string($this->apiUsername) || is_null($this->apiUsername)) {
// $apiUsername is optional, if null the default account in config file is taken
$credMgr = PPCredentialManager::getInstance($options['config']);
$request->setCredential(clone($credMgr->getCredentialObject($this->apiUsername)));
} else {
$request->setCredential($this->apiUsername);
}
$config = $options['config'];
$credential = $request->getCredential();
//TODO: Assuming existence of getApplicationId
if($credential && $credential->getApplicationId() != NULL) {
$httpConfig->addHeader('X-PAYPAL-APPLICATION-ID', $credential->getApplicationId());
}
if(isset($config['port']) && isset($config['service.EndPoint.'.$options['port']]))
{
$endpoint = $config['service.EndPoint.'.$options['port']];
}
// for backward compatibilty (for those who are using old config files with 'service.EndPoint')
else if (isset($config['service.EndPoint']))
{
$endpoint = $config['service.EndPoint'];
}
else if (isset($config['mode']))
{
if(strtoupper($config['mode']) == 'SANDBOX')
{
$endpoint = PPConstants::PLATFORM_SANDBOX_ENDPOINT;
}
else if(strtoupper($config['mode']) == 'LIVE')
{
$endpoint = PPConstants::PLATFORM_LIVE_ENDPOINT;
}
}
else
{
throw new PPConfigurationException('endpoint Not Set');
}
$httpConfig->setUrl($endpoint . $options['serviceName'] . '/' . $options['apiMethod']);
// Call the authentication handler to tack authentication related info
$handler = new PPAuthenticationHandler();
$handler->handle($httpConfig, $request, $options);
}
}
lib/handlers/PPSignatureAuthHandler.php 0000666 00000003424 13436755715 0014173 0 ustar 00 getCredential();
if(!isset($credential)) {
return;
}
$thirdPartyAuth = $credential->getThirdPartyAuthorization();
switch($request->getBindingType()) {
case 'NV':
if(!$thirdPartyAuth || !$thirdPartyAuth instanceof PPTokenAuthorization) {
$httpConfig->addHeader('X-PAYPAL-SECURITY-USERID', $credential->getUserName());
$httpConfig->addHeader('X-PAYPAL-SECURITY-PASSWORD', $credential->getPassword());
$httpConfig->addHeader('X-PAYPAL-SECURITY-SIGNATURE', $credential->getSignature());
if($thirdPartyAuth) {
$httpConfig->addHeader('X-PAYPAL-SECURITY-SUBJECT', $thirdPartyAuth->getSubject());
}
}
break;
case 'SOAP':
if($thirdPartyAuth && $thirdPartyAuth instanceof PPTokenAuthorization) {
$request->addBindingInfo('securityHeader' , '');
} else {
$securityHeader = '';
$securityHeader .= '' . $credential->getUserName() . '';
$securityHeader .= '' . $credential->getPassword() . '';
$securityHeader .= '' . $credential->getSignature() . '';
if($thirdPartyAuth && $thirdPartyAuth instanceof PPSubjectAuthorization) {
$securityHeader .= '' . $thirdPartyAuth->getSubject() . '';
}
$securityHeader .= '';
$request->addBindingInfo('securityHeader' , $securityHeader);
}
break;
}
}
} lib/handlers/PPCertificateAuthHandler.php 0000666 00000003322 13436755715 0014451 0 ustar 00 getCredential();
if(!isset($credential)) {
return;
}
$httpConfig->setSSLCert($credential->getCertificatePath(), $credential->getCertificatePassPhrase());
$thirdPartyAuth = $credential->getThirdPartyAuthorization();
switch($request->getBindingType()) {
case 'NV':
if(!$thirdPartyAuth || !$thirdPartyAuth instanceof PPTokenAuthorization) {
$httpConfig->addHeader('X-PAYPAL-SECURITY-USERID', $credential->getUserName());
$httpConfig->addHeader('X-PAYPAL-SECURITY-PASSWORD', $credential->getPassword());
if($thirdPartyAuth) {
$httpConfig->addHeader('X-PAYPAL-SECURITY-SUBJECT', $thirdPartyAuth->getSubject());
}
}
break;
case 'SOAP':
if($thirdPartyAuth && $thirdPartyAuth instanceof PPTokenAuthorization) {
$request->addBindingInfo('securityHeader', '');
} else {
$securityHeader = '';
$securityHeader .= '' . $credential->getUserName() . '';
$securityHeader .= '' . $credential->getPassword() . '';
if($thirdPartyAuth && $thirdPartyAuth instanceof PPSubjectAuthorization) {
$securityHeader .= '' . $thirdPartyAuth->getSubject() . '';
}
$securityHeader .= '';
$request->addBindingInfo('securityHeader' , $securityHeader);
}
break;
}
}
} lib/handlers/PPMerchantServiceHandler.php 0000666 00000005201 13436755715 0014465 0 ustar 00 apiUsername = $apiUsername;
}
public function handle($httpConfig, $request, $options) {
parent::handle($httpConfig, $request, $options);
$config = $options['config'];
if(is_string($this->apiUsername) || is_null($this->apiUsername)) {
// $apiUsername is optional, if null the default account in config file is taken
$credMgr = PPCredentialManager::getInstance($options['config']);
$request->setCredential(clone($credMgr->getCredentialObject($this->apiUsername)));
} else {
$request->setCredential($this->apiUsername);
}
$endpoint = '';
$credential = $request->getCredential();
if(isset($options['port']) && isset($config['service.EndPoint.'.$options['port']]))
{
$endpoint = $config['service.EndPoint.'.$options['port']];
}
// for backward compatibilty (for those who are using old config files with 'service.EndPoint')
else if (isset($config['service.EndPoint']))
{
$endpoint = $config['service.EndPoint'];
}
else if (isset($config['mode']))
{
if(strtoupper($config['mode']) == 'SANDBOX')
{
if($credential instanceof PPSignatureCredential)
{
$endpoint = PPConstants::MERCHANT_SANDBOX_SIGNATURE_ENDPOINT;
}
else if($credential instanceof PPCertificateCredential)
{
$endpoint = PPConstants::MERCHANT_SANDBOX_CERT_ENDPOINT;
}
}
else if(strtoupper($config['mode']) == 'LIVE')
{
if($credential instanceof PPSignatureCredential)
{
$endpoint = PPConstants::MERCHANT_LIVE_SIGNATURE_ENDPOINT;
}
else if($credential instanceof PPCertificateCredential)
{
$endpoint = PPConstants::MERCHANT_LIVE_CERT_ENDPOINT;
}
}
}
else
{
throw new PPConfigurationException('endpoint Not Set');
}
if($request->getBindingType() == 'SOAP')
{
$httpConfig->setUrl($endpoint);
}
else
{
throw new PPConfigurationException('expecting service binding to be SOAP');
}
$request->addBindingInfo("namespace", "xmlns:ns=\"urn:ebay:api:PayPalAPI\" xmlns:ebl=\"urn:ebay:apis:eBLBaseComponents\" xmlns:cc=\"urn:ebay:apis:CoreComponentTypes\" xmlns:ed=\"urn:ebay:apis:EnhancedDataTypes\"");
// Call the authentication handler to tack authentication related info
$handler = new PPAuthenticationHandler();
$handler->handle($httpConfig, $request, $options);
}
}
lib/handlers/PPGenericServiceHandler.php 0000666 00000002175 13436755715 0014307 0 ustar 00 sdkName = $sdkName;
$this->sdkVersion = $sdkVersion;
}
public function handle($httpConfig, $request, $options) {
$httpConfig->addHeader('X-PAYPAL-REQUEST-DATA-FORMAT', $request->getBindingType());
$httpConfig->addHeader('X-PAYPAL-RESPONSE-DATA-FORMAT', $request->getBindingType());
$httpConfig->addHeader('X-PAYPAL-DEVICE-IPADDRESS', PPUtils::getLocalIPAddress());
$httpConfig->addHeader('X-PAYPAL-REQUEST-SOURCE', $this->getRequestSource());
if(isset($options['config']['service.SandboxEmailAddress'])) {
$httpConfig->addHeader('X-PAYPAL-SANDBOX-EMAIL-ADDRESS', $options['config']['service.SandboxEmailAddress']);
}
}
/**
* Compute the value that needs to sent for the PAYPAL_REQUEST_SOURCE
* parameter when making API calls
*/
private function getRequestSource() {
return str_replace(" ", "-", $this->sdkName) . "-" . $this->sdkVersion;
}
}
lib/cacert.pem 0000666 00000026145 13436755715 0007312 0 ustar 00 Verisign Class 3 Public Primary Certification Authority
=======================================================
-----BEGIN CERTIFICATE-----
MIICPDCCAaUCEHC65B0Q2Sk0tjjKewPMur8wDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMx
FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5
IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMTIzNTk1OVow
XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz
IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94
f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol
hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBAgUAA4GBALtMEivPLCYA
TxQT3ab7/AoRhIzzKBxnki98tsX63/Dolbwdj2wsqFHMc9ikwFPwTtYmwHYBV4GSXiHx0bH/59Ah
WM1pF+NEHJwZRDmJXNycAA9WjQKZ7aKQRUzkuxCkPfAyAw7xzvjoyVGM5mKf5p/AfbdynMk2Omuf
Tqj/ZA1k
-----END CERTIFICATE-----
Verisign Class 3 Public Primary Certification Authority - G2
============================================================
-----BEGIN CERTIFICATE-----
MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJBgNVBAYTAlVT
MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy
eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz
dCBOZXR3b3JrMB4XDTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVT
MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy
eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz
dCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCO
FoUgRm1HP9SFIIThbbP4pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71
lSk8UOg013gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwIDAQAB
MA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSkU01UbSuvDV1Ai2TT
1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7iF6YM40AIOw7n60RzKprxaZLvcRTD
Oaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpYoJ2daZH9
-----END CERTIFICATE-----
Verisign Class 3 Public Primary Certification Authority - G3
============================================================
-----BEGIN CERTIFICATE-----
MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV
UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh
dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw
CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy
dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv
cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkg
Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAMu6nFL8eB8aHm8bN3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1
EUGO+i2tKmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGukxUc
cLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBmCC+Vk7+qRy+oRpfw
EuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJXwzw3sJ2zq/3avL6QaaiMxTJ5Xpj
055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWuimi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA
ERSWwauSCPc/L8my/uRan2Te2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5f
j267Cz3qWhMeDGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC
/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565pF4ErWjfJXir0
xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGtTxzhT5yvDwyd93gN2PQ1VoDa
t20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ==
-----END CERTIFICATE-----
Verisign Class 4 Public Primary Certification Authority - G3
============================================================
-----BEGIN CERTIFICATE-----
MIIEGjCCAwICEQDsoKeLbnVqAc/EfMwvlF7XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV
UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh
dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw
CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy
dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv
cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkg
Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAK3LpRFpxlmr8Y+1GQ9Wzsy1HyDkniYlS+BzZYlZ3tCD5PUPtbut8XzoIfzk6AzufEUiGXaS
tBO3IFsJ+mGuqPKljYXCKtbeZjbSmwL0qJJgfJxptI8kHtCGUvYynEFYHiK9zUVilQhu0GbdU6LM
8BDcVHOLBKFGMzNcF0C5nk3T875Vg+ixiY5afJqWIpA7iCXy0lOIAgwLePLmNxdLMEYH5IBtptiW
Lugs+BGzOA1mppvqySNb247i8xOOGlktqgLw7KSHZtzBP/XYufTsgsbSPZUd5cBPhMnZo0QoBmrX
Razwa2rvTl/4EYIeOGM0ZlDUPpNz+jDDZq3/ky2X7wMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA
j/ola09b5KROJ1WrIhVZPMq1CtRK26vdoV9TxaBXOcLORyu+OshWv8LZJxA6sQU8wHcxuzrTBXtt
mhwwjIDLk5Mqg6sFUYICABFna/OIYUdfA5PVWw3g8dShMjWFsjrbsIKr0csKvE+MW8VLADsfKoKm
fjaF3H48ZwC15DtS4KjrXRX5xm3wrR0OhbepmnMUWluPQSjA1egtTaRezarZ7c7c2NU8Qh0XwRJd
RTjDOPP8hS6DRkiy1yBfkjaP53kPmF6Z6PDQpLv1U70qzlmwr25/bLvSHgCwIe34QWKCudiyxLtG
UPMxxY8BqHTr9Xgn2uf3ZkPznoM+IKrDNWCRzg==
-----END CERTIFICATE-----
VeriSign Class 3 Public Primary Certification Authority - G5
============================================================
-----BEGIN CERTIFICATE-----
MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE
BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO
ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk
IHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRp
ZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCB
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln
biBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBh
dXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmlt
YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQCvJAgIKXo1nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKz
j/i5Vbext0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIzSdhD
Y2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQGBO+QueQA5N06tRn/
Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+rCpSx4/VBEnkjWNHiDxpg8v+R70r
fk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/
BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2Uv
Z2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKvMzEzMA0GCSqG
SIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzEp6B4Eq1iDkVwZMXnl2YtmAl+
X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKE
KQsTb47bDN0lAtukixlE0kF6BWlKWE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiC
Km0oHw0LxOXnGiYZ4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vE
ZV8NhnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
-----END CERTIFICATE-----
VeriSign Universal Root Certification Authority
===============================================
-----BEGIN CERTIFICATE-----
MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCBvTELMAkGA1UE
BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO
ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk
IHVzZSBvbmx5MTgwNgYDVQQDEy9WZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9u
IEF1dGhvcml0eTAeFw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJV
UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
cmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0
aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj
1mCOkdeQmIN65lgZOIzF9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGP
MiJhgsWHH26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+HLL72
9fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN/BMReYTtXlT2NJ8I
AfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPTrJ9VAMf2CGqUuV/c4DPxhGD5WycR
tPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0G
CCsGAQUFBwEMBGEwX6FdoFswWTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2O
a8PPgGrUSBgsexkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud
DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4sAPmLGd75JR3
Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+seQxIcaBlVZaDrHC1LGmWazx
Y8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTx
P/jgdFcrGJ2BtMQo2pSXpXDrrB2+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+P
wGZsY6rp2aQW9IHRlRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4
mJO37M2CYfE45k+XmCpajQ==
-----END CERTIFICATE-----
VeriSign Class 3 Public Primary Certification Authority - G4
============================================================
-----BEGIN CERTIFICATE-----
MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjELMAkGA1UEBhMC
VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3
b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVz
ZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmlj
YXRpb24gQXV0aG9yaXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjEL
MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU
cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRo
b3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5
IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8
Utpkmw4tXNherJI9/gHmGUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGz
rl0Bp3vefLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUwAwEB
/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEw
HzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVyaXNpZ24u
Y29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMWkf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMD
A2gAMGUCMGYhDBgmYFo4e1ZC4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIx
AJw9SDkjOVgaFRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA==
-----END CERTIFICATE-----
Verisign Class 3 Public Primary Certification Authority
=======================================================
-----BEGIN CERTIFICATE-----
MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UEBhMCVVMx
FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5
IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVow
XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz
IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94
f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol
hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBABByUqkFFBky
CEHwxWsKzH4PIRnN5GfcX6kb5sroc50i2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWX
bj9T/UWZYB2oK0z5XqcJ2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/
D/xwzoiQ
-----END CERTIFICATE-----
lib/PPRequest.php 0000666 00000002375 13436755715 0007746 0 ustar 00 requestObject = $requestObject;
$this->bindingType = $bindingType;
}
public function getRequestObject() {
return $this->requestObject;
}
public function getBindingType() {
return $this->bindingType;
}
public function getBindingInfo($name=NULL) {
if(isset($name)) {
return array_key_exists($name, $this->bindingInfo) ? $this->bindingInfo[$name] : null;
}
return $this->bindingInfo;
}
/**
*
* @param string $name
* @param mixed $value
*/
public function addBindingInfo($name, $value) {
$this->bindingInfo[$name] = $value;
}
public function setCredential($credential) {
$this->credential = $credential;
}
public function getCredential() {
return $this->credential;
}
} lib/PPXmlFaultMessage.php 0000666 00000005144 13436755715 0011354 0 ustar 00 $val) {
$element["children"][] = array(
'name' => $key,
'text' => $val,
);
}
if (isset($element['text'])) {
$element["children"][] = array(
'name' => 'value',
'text' => $element['text'],
);
}
$this->fillRelation($element['name'], $element);
} elseif (!empty($element['text'])) {
$this->{$element['name']} = $element['text'];
} elseif (!empty($element["children"]) && is_array($element["children"])) {
$this->fillRelation($element['name'], $element);
}
}
}
/**
* @param string $property
* @param array $element
*/
private function fillRelation($property, array $element)
{
if (!class_exists($type = PPUtils::propertyType($this, $property))) {
trigger_error("Class $type not found.", E_USER_NOTICE);
return; // just ignore
}
if (isset($element['num'])) { // array of objects
$this->{$property}[$element['num']] = $item = new $type();
$item->init($element['children'], false);
} else {
$this->{$property} = new $type();
$this->{$property}->init($element["children"], false);
}
}
}
lib/auth/PPSubjectAuthorization.php 0000666 00000001137 13436755715 0013432 0 ustar 00 subject = $subject;
}
public function getSubject() {
return $this->subject;
}
} lib/auth/IPPCredential.php 0000666 00000000704 13436755715 0011434 0 ustar 00 thirdPartyAuthorization = $thirdPartyAuthorization;
}
public function getThirdPartyAuthorization() {
return $this->thirdPartyAuthorization;
}
public abstract function validate();
} lib/auth/IPPThirdPartyAuthorization.php 0000666 00000000343 13436755715 0014234 0 ustar 00 consumer = new OAuthConsumer("key", "secret", NULL);
$this->request_token = new OAuthToken("requestkey", "requestsecret", 1);
$this->access_token = new OAuthToken("accesskey", "accesssecret", 1);
$this->nonce = "nonce";
}/*}}}*/
function lookup_consumer($consumer_key) {/*{{{*/
if ($consumer_key == $this->consumer->key) return $this->consumer;
return NULL;
}/*}}}*/
function lookup_token($consumer, $token_type, $token) {/*{{{*/
$token_attrib = $token_type . "_token";
if ($consumer->key == $this->consumer->key
&& $token == $this->$token_attrib->key) {
return $this->$token_attrib;
}
return NULL;
}/*}}}*/
function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
if ($consumer->key == $this->consumer->key
&& (($token && $token->key == $this->request_token->key)
|| ($token && $token->key == $this->access_token->key))
&& $nonce == $this->nonce) {
return $this->nonce;
}
return NULL;
}/*}}}*/
function new_request_token($consumer, $callback = NULL) {/*{{{*/
if ($consumer->key == $this->consumer->key) {
return $this->request_token;
}
return NULL;
}/*}}}*/
function new_access_token($token, $consumer, $verifier = NULL) {/*{{{*/
if ($consumer->key == $this->consumer->key
&& $token->key == $this->request_token->key) {
return $this->access_token;
}
return NULL;
}/*}}}*/
}/*}}}*/
lib/auth/openid/PPOpenIdError.php 0000666 00000002674 13436755715 0012727 0 ustar 00 error = $error;
return $this;
}
/**
* A single ASCII error code from the following enum.
* @return string
*/
public function getError() {
return $this->error;
}
/**
* A resource ID that indicates the starting resource in the returned results.
* @param string $error_description
*/
public function setErrorDescription($error_description) {
$this->error_description = $error_description;
return $this;
}
/**
* A resource ID that indicates the starting resource in the returned results.
* @return string
*/
public function getErrorDescription() {
return $this->error_description;
}
/**
* A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error.
* @param string $error_uri
*/
public function setErrorUri($error_uri) {
$this->error_uri = $error_uri;
return $this;
}
/**
* A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error.
* @return string
*/
public function getErrorUri() {
return $this->error_uri;
}
}
lib/auth/openid/PPOpenIdUserinfo.php 0000666 00000021050 13436755715 0013415 0 ustar 00 user_id = $user_id;
return $this;
}
/**
* Subject - Identifier for the End-User at the Issuer.
* @return string
*/
public function getUserId() {
return $this->user_id;
}
/**
* Subject - Identifier for the End-User at the Issuer.
* @param string $sub
*/
public function setSub($sub) {
$this->sub = $sub;
return $this;
}
/**
* Subject - Identifier for the End-User at the Issuer.
* @return string
*/
public function getSub() {
return $this->sub;
}
/**
* End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
* @param string $name
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
* @return string
*/
public function getName() {
return $this->name;
}
/**
* Given name(s) or first name(s) of the End-User
* @param string $given_name
*/
public function setGivenName($given_name) {
$this->given_name = $given_name;
return $this;
}
/**
* Given name(s) or first name(s) of the End-User
* @return string
*/
public function getGivenName() {
return $this->given_name;
}
/**
* Surname(s) or last name(s) of the End-User.
* @param string $family_name
*/
public function setFamilyName($family_name) {
$this->family_name = $family_name;
return $this;
}
/**
* Surname(s) or last name(s) of the End-User.
* @return string
*/
public function getFamilyName() {
return $this->family_name;
}
/**
* Middle name(s) of the End-User.
* @param string $middle_name
*/
public function setMiddleName($middle_name) {
$this->middle_name = $middle_name;
return $this;
}
/**
* Middle name(s) of the End-User.
* @return string
*/
public function getMiddleName() {
return $this->middle_name;
}
/**
* URL of the End-User's profile picture.
* @param string $picture
*/
public function setPicture($picture) {
$this->picture = $picture;
return $this;
}
/**
* URL of the End-User's profile picture.
* @return string
*/
public function getPicture() {
return $this->picture;
}
/**
* End-User's preferred e-mail address.
* @param string $email
*/
public function setEmail($email) {
$this->email = $email;
return $this;
}
/**
* End-User's preferred e-mail address.
* @return string
*/
public function getEmail() {
return $this->email;
}
/**
* True if the End-User's e-mail address has been verified; otherwise false.
* @param boolean $email_verified
*/
public function setEmailVerified($email_verified) {
$this->email_verified = $email_verified;
return $this;
}
/**
* True if the End-User's e-mail address has been verified; otherwise false.
* @return boolean
*/
public function getEmailVerified() {
return $this->email_verified;
}
/**
* End-User's gender.
* @param string $gender
*/
public function setGender($gender) {
$this->gender = $gender;
return $this;
}
/**
* End-User's gender.
* @return string
*/
public function getGender() {
return $this->gender;
}
/**
* End-User's birthday, represented as an YYYY-MM-DD format. They year MAY be 0000, indicating it is omited. To represent only the year, YYYY format would be used.
* @param string $birthday
*/
public function setBirthday($birthday) {
$this->birthday = $birthday;
return $this;
}
/**
* End-User's birthday, represented as an YYYY-MM-DD format. They year MAY be 0000, indicating it is omited. To represent only the year, YYYY format would be used.
* @return string
*/
public function getBirthday() {
return $this->birthday;
}
/**
* Time zone database representing the End-User's time zone
* @param string $zoneinfo
*/
public function setZoneinfo($zoneinfo) {
$this->zoneinfo = $zoneinfo;
return $this;
}
/**
* Time zone database representing the End-User's time zone
* @return string
*/
public function getZoneinfo() {
return $this->zoneinfo;
}
/**
* End-User's locale.
* @param string $locale
*/
public function setLocale($locale) {
$this->locale = $locale;
return $this;
}
/**
* End-User's locale.
* @return string
*/
public function getLocale() {
return $this->locale;
}
/**
* End-User's language.
* @param string $language
*/
public function setLanguage($language) {
$this->language = $language;
return $this;
}
/**
* End-User's language.
* @return string
*/
public function getLanguage() {
return $this->language;
}
/**
* End-User's verified status.
* @param boolean $verified
*/
public function setVerified($verified) {
$this->verified = $verified;
return $this;
}
/**
* End-User's verified status.
* @return boolean
*/
public function getVerified() {
return $this->verified;
}
/**
* End-User's preferred telephone number.
* @param string $phone_number
*/
public function setPhoneNumber($phone_number) {
$this->phone_number = $phone_number;
return $this;
}
/**
* End-User's preferred telephone number.
* @return string
*/
public function getPhoneNumber() {
return $this->phone_number;
}
/**
* End-User's preferred address.
* @param PPOpenIdAddress $address
*/
public function setAddress($address) {
$this->address = $address;
return $this;
}
/**
* End-User's preferred address.
* @return PPOpenIdAddress
*/
public function getAddress() {
return $this->address;
}
/**
* Verified account status.
* @param boolean $verified_account
*/
public function setVerifiedAccount($verified_account) {
$this->verified_account = $verified_account;
return $this;
}
/**
* Verified account status.
* @return boolean
*/
public function getVerifiedAccount() {
return $this->verified_account;
}
/**
* Account type.
* @param string $account_type
*/
public function setAccountType($account_type) {
$this->account_type = $account_type;
return $this;
}
/**
* Account type.
* @return string
*/
public function getAccountType() {
return $this->account_type;
}
/**
* Account holder age range.
* @param string $age_range
*/
public function setAgeRange($age_range) {
$this->age_range = $age_range;
return $this;
}
/**
* Account holder age range.
* @return string
*/
public function getAgeRange() {
return $this->age_range;
}
/**
* Account payer identifier.
* @param string $payer_id
*/
public function setPayerId($payer_id) {
$this->payer_id = $payer_id;
return $this;
}
/**
* Account payer identifier.
* @return string
*/
public function getPayerId() {
return $this->payer_id;
}
/**
* returns user details
*
* @path /v1/identity/openidconnect/userinfo
* @method GET
* @param array $params (allowed values are access_token)
* access_token - access token from the createFromAuthorizationCode / createFromRefreshToken calls
* @param PPApiContext $apiContext Optional API Context
* @return PPOpenIdUserinfo
*/
public static function getUserinfo($params, $apiContext=null) {
static $allowedParams = array( 'schema' => 1);
if(is_null($apiContext)) {
$apiContext = new PPApiContext();
}
if(!array_key_exists('schema', $params)) {
$params['schema'] = 'openid';
}
$requestUrl = "/v1/identity/openidconnect/userinfo?"
. http_build_query(array_intersect_key($params, $allowedParams));
$call = new PPRestCall($apiContext);
$ret = new PPOpenIdUserinfo();
$ret->fromJson(
$call->execute(array(new PPOpenIdHandler($apiContext)), $requestUrl, "GET", "",
array(
'Authorization' => "Bearer " . $params['access_token'],
'Content-Type'=> 'x-www-form-urlencoded'
)
)
);
return $ret;
}
}
lib/auth/openid/PPOpenIdTokeninfo.php 0000666 00000013620 13436755715 0013563 0 ustar 00 scope = $scope;
return $this;
}
/**
* OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED.
* @return string
*/
public function getScope() {
return $this->scope;
}
/**
* The access token issued by the authorization server.
* @param string $access_token
*/
public function setAccessToken($access_token) {
$this->access_token = $access_token;
return $this;
}
/**
* The access token issued by the authorization server.
* @return string
*/
public function getAccessToken() {
return $this->access_token;
}
/**
* The refresh token, which can be used to obtain new access tokens using the same authorization grant as described in OAuth2.0 RFC6749 in Section 6.
* @param string $refresh_token
*/
public function setRefreshToken($refresh_token) {
$this->refresh_token = $refresh_token;
return $this;
}
/**
* The refresh token, which can be used to obtain new access tokens using the same authorization grant as described in OAuth2.0 RFC6749 in Section 6.
* @return string
*/
public function getRefreshToken() {
return $this->refresh_token;
}
/**
* The type of the token issued as described in OAuth2.0 RFC6749 (Section 7.1). Value is case insensitive.
* @param string $token_type
*/
public function setTokenType($token_type) {
$this->token_type = $token_type;
return $this;
}
/**
* The type of the token issued as described in OAuth2.0 RFC6749 (Section 7.1). Value is case insensitive.
* @return string
*/
public function getTokenType() {
return $this->token_type;
}
/**
* The id_token is a session token assertion that denotes the user's authentication status
* @param string $id_token
*/
public function setIdToken($id_token) {
$this->id_token = $id_token;
return $this;
}
/**
* The id_token is a session token assertion that denotes the user's authentication status
* @return string
*/
public function getIdToken() {
return $this->id_token;
}
/**
* The lifetime in seconds of the access token.
* @param integer $expires_in
*/
public function setExpiresIn($expires_in) {
$this->expires_in = $expires_in;
return $this;
}
/**
* The lifetime in seconds of the access token.
* @return integer
*/
public function getExpiresIn() {
return $this->expires_in;
}
/**
* Creates an Access Token from an Authorization Code.
*
* @path /v1/identity/openidconnect/tokenservice
* @method POST
* @param array $params (allowed values are client_id, client_secret, grant_type, code and redirect_uri)
* (required) client_id from developer portal
* (required) client_secret from developer portal
* (required) code is Authorization code previously received from the authorization server
* (required) redirect_uri Redirection endpoint that must match the one provided during the
* authorization request that ended in receiving the authorization code.
* (optional) grant_type is the Token grant type. Defaults to authorization_code
* @param PPApiContext $apiContext Optional API Context
* @return PPOpenIdTokeninfo
*/
public static function createFromAuthorizationCode($params, $apiContext=null) {
static $allowedParams = array('grant_type' => 1, 'code' => 1, 'redirect_uri' => 1);
if(is_null($apiContext)) {
$apiContext = new PPApiContext();
}
if(!array_key_exists('grant_type', $params)) {
$params['grant_type'] = 'authorization_code';
}
$call = new PPRestCall($apiContext);
$token = new PPOpenIdTokeninfo();
$token->fromJson(
$call->execute(array(new PPOpenIdHandler()),
"/v1/identity/openidconnect/tokenservice" , "POST",
http_build_query(array_intersect_key($params, $allowedParams)),
array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode($params['client_id'] . ":" . $params['client_secret'])
)
));
return $token;
}
/**
* Creates an Access Token from an Refresh Token.
*
* @path /v1/identity/openidconnect/tokenservice
* @method POST
* @param array $params (allowed values are grant_type and scope)
* (required) client_id from developer portal
* (required) client_secret from developer portal
* (optional) refresh_token refresh token. If one is not passed, refresh token from the current object is used.
* (optional) grant_type is the Token grant type. Defaults to refresh_token
* (optional) scope is an array that either the same or a subset of the scope passed to the authorization request
* @param APIContext $apiContext Optional API Context
* @return PPOpenIdTokeninfo
*/
public function createFromRefreshToken($params, $apiContext=null) {
static $allowedParams = array('grant_type' => 1, 'refresh_token' => 1, 'scope' => 1);
if(is_null($apiContext)) {
$apiContext = new PPApiContext();
}
if(!array_key_exists('grant_type', $params)) {
$params['grant_type'] = 'refresh_token';
}
if(!array_key_exists('refresh_token', $params)) {
$params['refresh_token'] = $this->getRefreshToken();
}
$call = new PPRestCall($apiContext);
$this->fromJson(
$call->execute(array(new PPOpenIdHandler()),
"/v1/identity/openidconnect/tokenservice", "POST",
http_build_query(array_intersect_key($params, $allowedParams)),
array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode($params['client_id'] . ":" . $params['client_secret'])
)
));
return $this;
}
}
lib/auth/openid/PPOpenIdAddress.php 0000666 00000003464 13436755715 0013221 0 ustar 00 street_address = $street_address;
return $this;
}
/**
* Full street address component, which may include house number, street name.
* @return string
*/
public function getStreetAddress() {
return $this->street_address;
}
/**
* City or locality component.
* @param string $locality
*/
public function setLocality($locality) {
$this->locality = $locality;
return $this;
}
/**
* City or locality component.
* @return string
*/
public function getLocality() {
return $this->locality;
}
/**
* State, province, prefecture or region component.
* @param string $region
*/
public function setRegion($region) {
$this->region = $region;
return $this;
}
/**
* State, province, prefecture or region component.
* @return string
*/
public function getRegion() {
return $this->region;
}
/**
* Zip code or postal code component.
* @param string $postal_code
*/
public function setPostalCode($postal_code) {
$this->postal_code = $postal_code;
return $this;
}
/**
* Zip code or postal code component.
* @return string
*/
public function getPostalCode() {
return $this->postal_code;
}
/**
* Country name component.
* @param string $country
*/
public function setCountry($country) {
$this->country = $country;
return $this;
}
/**
* Country name component.
* @return string
*/
public function getCountry() {
return $this->country;
}
}
lib/auth/openid/PPOpenIdSession.php 0000666 00000005124 13436755715 0013252 0 ustar 00 getConfig();
$scope = count($scope) != 0 ? $scope : array('openid', 'profile', 'address', 'email', 'phone',
'https://uri.paypal.com/services/paypalattributes', 'https://uri.paypal.com/services/expresscheckout');
if(!in_array('openid', $scope)) {
$scope[] = 'openid';
}
$params = array(
'client_id' => $clientId,
'response_type' => 'code',
'scope' => implode(" ", $scope),
'redirect_uri' => $redirectUri
);
return sprintf("%s/v1/authorize?%s", self::getBaseUrl($config), http_build_query($params));
}
/**
* Returns the URL to which the user must be redirected to
* logout from the OpenID provider (i.e. PayPal)
*
* @param string $redirectUri Uri on merchant website to where
* the user must be redirected to post logout
* @param string $idToken id_token from the TokenInfo object
* @param PPApiContext $apiContext Optional API Context
*/
public static function getLogoutUrl($redirectUri, $idToken, $apiContext=null) {
if(is_null($apiContext)) {
$apiContext = new PPApiContext();
}
$config = $apiContext->getConfig();
$params = array(
'id_token' => $idToken,
'redirect_uri' => $redirectUri,
'logout' => 'true'
);
return sprintf("%s/v1/endsession?%s", self::getBaseUrl($config), http_build_query($params));
}
private static function getBaseUrl($config) {
if(array_key_exists('openid.RedirectUri', $config)) {
return $config['openid.RedirectUri'];
} else if (array_key_exists('mode', $config)) {
switch(strtoupper($config['mode'])) {
case 'SANDBOX':
return PPConstants::OPENID_REDIRECT_SANDBOX_URL;
case 'LIVE':
return PPConstants::OPENID_REDIRECT_LIVE_URL;
}
}
return ;
}
}
lib/auth/PPSignatureCredential.php 0000666 00000002757 13436755715 0013217 0 ustar 00 userName = trim($userName);
$this->password = trim($password);
$this->signature = trim($signature);
$this->validate();
}
public function validate() {
if (empty($this->userName)) {
throw new PPMissingCredentialException("username cannot be empty");
}
if (empty($this->password)) {
throw new PPMissingCredentialException("password cannot be empty");
}
// Signature can be empty if using 3-rd party auth tokens from permissions API
}
public function getUserName() {
return $this->userName;
}
public function getPassword() {
return $this->password;
}
public function getSignature() {
return $this->signature;
}
public function setApplicationId($applicationId) {
$this->applicationId = trim($applicationId);
}
public function getApplicationId() {
return $this->applicationId;
}
} lib/auth/PPCertificateCredential.php 0000666 00000005043 13436755715 0013467 0 ustar 00 userName = trim($userName);
$this->password = trim($password);
$this->certificatePath = trim($certPath);
$this->certificatePassPhrase = $certificatePassPhrase;
$this->validate();
}
public function validate() {
if (empty($this->userName)) {
throw new PPMissingCredentialException("username cannot be empty");
}
if (empty($this->password)) {
throw new PPMissingCredentialException("password cannot be empty");
}
if (empty($this->certificatePath)) {
throw new PPMissingCredentialException("certificate cannot be empty");
}
}
public function getUserName() {
return $this->userName;
}
public function getPassword() {
return $this->password;
}
public function getCertificatePath() {
if (realpath($this->certificatePath)) {
return realpath($this->certificatePath);
} else if(defined('PP_CONFIG_PATH')) {
return constant('PP_CONFIG_PATH') . DIRECTORY_SEPARATOR . $this->certificatePath;
} else {
return realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . ".." .DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . $this->certificatePath);
}
}
public function getCertificatePassPhrase() {
return $this->certificatePassPhrase;
}
public function setApplicationId($applicationId) {
$this->applicationId = trim($applicationId);
}
public function getApplicationId() {
return $this->applicationId;
}
}
lib/auth/PPAuth.php 0000666 00000067610 13436755715 0010163 0 ustar 00 add_signature_method($hmac_method);
$sig_method = $hmac_method;
$authConsumer = new OAuthConsumer($key, $secret, NULL);
$authToken = NULL;
$authToken = new OAuthToken($token, $tokenSecret);
//$params is the query param array which is required only in the httpMethod is "GET"
$params = array();
//TODO: set the Query parameters to $params if httpMethod is "GET"
$acc_req = OAuthRequest::from_consumer_and_token($authConsumer, $authToken, $httpMethod, $endpoint, $params);
$acc_req->sign_request($sig_method,$authConsumer, $authToken);
return OAuthutil::parseQueryString($acc_req);
}
public static function generateFullAuthString($key, $secret, $token, $tokenSecret, $httpMethod, $endpoint) {
$authSignature = new AuthSignature();
$response = $authSignature->genSign($key, $secret, $token, $tokenSecret, $httpMethod, $endpoint);
return "token=" . $token .
",signature=" . $response['oauth_signature'] .
",timestamp=" . $response['oauth_timestamp'];
}
}
//PayPal specific modification ends
/* Generic exception class
*/
class OAuthException extends Exception {
// pass
}
class OAuthConsumer {
public $key;
public $secret;
function __construct($key, $secret, $callback_url=NULL) {
$this->key = $key;
$this->secret = $secret;
$this->callback_url = $callback_url;
}
function __toString() {
return "OAuthConsumer[key=$this->key,secret=$this->secret]";
}
}
class OAuthToken {
// access tokens and request tokens
public $key;
public $secret;
/**
* key = the token
* secret = the token secret
*/
function __construct($key, $secret) {
$this->key = $key;
$this->secret = $secret;
}
/**
* generates the basic string serialization of a token that a server
* would respond to request_token and access_token calls with
*/
function to_string() {
return "oauth_token=" .
OAuthUtil::urlencode_rfc3986($this->key) .
"&oauth_token_secret=" .
OAuthUtil::urlencode_rfc3986($this->secret);
}
function __toString() {
return $this->to_string();
}
}
/**
* A class for implementing a Signature Method
* See section 9 ("Signing Requests") in the spec
*/
abstract class OAuthSignatureMethod {
/**
* Needs to return the name of the Signature Method (ie HMAC-SHA1)
* @return string
*/
abstract public function get_name();
/**
* Build up the signature
* NOTE: The output of this function MUST NOT be urlencoded.
* the encoding is handled in OAuthRequest when the final
* request is serialized
* @param OAuthRequest $request
* @param OAuthConsumer $consumer
* @param OAuthToken $token
* @return string
*/
abstract public function build_signature($request, $consumer, $token);
/**
* Verifies that a given signature is correct
* @param OAuthRequest $request
* @param OAuthConsumer $consumer
* @param OAuthToken $token
* @param string $signature
* @return bool
*/
public function check_signature($request, $consumer, $token, $signature) {
$built = $this->build_signature($request, $consumer, $token);
return $built == $signature;
}
}
/**
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
* where the Signature Base String is the text and the key is the concatenated values (each first
* encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
* character (ASCII code 38) even if empty.
* - Chapter 9.2 ("HMAC-SHA1")
*/
class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
function get_name() {
return "HMAC-SHA1";
}
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$base_string = preg_replace_callback("/(%[A-Za-z0-9]{2})/", array($this, "replace_callback"), $base_string);//convert base string to lowercase
$request->base_string = $base_string;
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
$key = preg_replace_callback("/(%[A-Za-z0-9]{2})/", array($this, "replace_callback"), $key);//convert to lowercase
return base64_encode(hash_hmac('sha1', $base_string, $key, true));
}
/**
* preg_replace_callback callback function
*/
private function replace_callback($match) {
return strtolower($match[0]);
}
}
/**
* The PLAINTEXT method does not provide any security protection and SHOULD only be used
* over a secure channel such as HTTPS. It does not use the Signature Base String.
* - Chapter 9.4 ("PLAINTEXT")
*/
class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
public function get_name() {
return "PLAINTEXT";
}
/**
* oauth_signature is set to the concatenated encoded values of the Consumer Secret and
* Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
* empty. The result MUST be encoded again.
* - Chapter 9.4.1 ("Generating Signatures")
*
* Please note that the second encoding MUST NOT happen in the SignatureMethod, as
* OAuthRequest handles this!
*/
public function build_signature($request, $consumer, $token) {
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
$request->base_string = $key;
return $key;
}
}
/**
* The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
* [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
* EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
* verified way to the Service Provider, in a manner which is beyond the scope of this
* specification.
* - Chapter 9.3 ("RSA-SHA1")
*/
abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
public function get_name() {
return "RSA-SHA1";
}
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
// (2) fetch via http using a url provided by the requester
// (3) some sort of specific discovery code based on request
//
// Either way should return a string representation of the certificate
protected abstract function fetch_public_cert(&$request);
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
//
// Either way should return a string representation of the certificate
protected abstract function fetch_private_cert(&$request);
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
// Fetch the private key cert based on the request
$cert = $this->fetch_private_cert($request);
// Pull the private key ID from the certificate
$privatekeyid = openssl_get_privatekey($cert);
// Sign using the key
$ok = openssl_sign($base_string, $signature, $privatekeyid);
// Release the key resource
openssl_free_key($privatekeyid);
return base64_encode($signature);
}
public function check_signature($request, $consumer, $token, $signature) {
$decoded_sig = base64_decode($signature);
$base_string = $request->get_signature_base_string();
// Fetch the public key cert based on the request
$cert = $this->fetch_public_cert($request);
// Pull the public key ID from the certificate
$publickeyid = openssl_get_publickey($cert);
// Check the computed signature against the one passed in the query
$ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
// Release the key resource
openssl_free_key($publickeyid);
return $ok == 1;
}
}
class OAuthRequest {
public $parameters;
protected $http_method;
protected $http_url;
// for debug purposes
public $base_string;
public static $version = '1.0';
public static $POST_INPUT = 'php://input';
function __construct($http_method, $http_url, $parameters=NULL) {
$parameters = ($parameters) ? $parameters : array();
$parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
$this->parameters = $parameters;
$this->http_method = $http_method;
$this->http_url = $http_url;
}
/**
* attempt to build up a request from what was passed to the server
*/
public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
$scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
? 'http'
: 'https';
$http_url = ($http_url) ? $http_url : $scheme .
'://' . $_SERVER['HTTP_HOST'] .
':' .
$_SERVER['SERVER_PORT'] .
$_SERVER['REQUEST_URI'];
$http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD'];
// We weren't handed any parameters, so let's find the ones relevant to
// this request.
// If you run XML-RPC or similar you should use this to provide your own
// parsed parameter-list
if (!$parameters) {
// Find request headers
$request_headers = OAuthUtil::get_headers();
// Parse the query-string to find GET parameters
$parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
// It's a POST request of the proper content-type, so parse POST
// parameters and add those overriding any duplicates from GET
if ($http_method == "POST"
&& isset($request_headers['Content-Type'])
&& strstr($request_headers['Content-Type'],
'application/x-www-form-urlencoded')
) {
$post_data = OAuthUtil::parse_parameters(
file_get_contents(self::$POST_INPUT)
);
$parameters = array_merge($parameters, $post_data);
}
// We have a Authorization-header with OAuth data. Parse the header
// and add those overriding any duplicates from GET or POST
if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
$header_parameters = OAuthUtil::split_header(
$request_headers['Authorization']
);
$parameters = array_merge($parameters, $header_parameters);
}
}
return new OAuthRequest($http_method, $http_url, $parameters);
}
/**
* pretty much a helper function to set up the request
*/
public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
$parameters = ($parameters) ? $parameters : array();
$defaults = array("oauth_version" => OAuthRequest::$version,
// "oauth_nonce" => OAuthRequest::generate_nonce(),
"oauth_timestamp" => OAuthRequest::generate_timestamp(),
"oauth_consumer_key" => $consumer->key);
if ($token)
$defaults['oauth_token'] = $token->key;
$parameters = array_merge($defaults, $parameters);
ksort($parameters);
return new OAuthRequest($http_method, $http_url, $parameters);
}
public function set_parameter($name, $value, $allow_duplicates = true) {
if ($allow_duplicates && isset($this->parameters[$name])) {
// We have already added parameter(s) with this name, so add to the list
if (is_scalar($this->parameters[$name])) {
// This is the first duplicate, so transform scalar (string)
// into an array so we can add the duplicates
$this->parameters[$name] = array($this->parameters[$name]);
}
$this->parameters[$name][] = $value;
} else {
$this->parameters[$name] = $value;
}
}
public function get_parameter($name) {
return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
}
public function get_parameters() {
return $this->parameters;
}
public function unset_parameter($name) {
unset($this->parameters[$name]);
}
/**
* The request parameters, sorted and concatenated into a normalized string.
* @return string
*/
public function get_signable_parameters() {
// Grab all parameters
$params = $this->parameters;
ksort($params);
// Remove oauth_signature if present
// Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
if (isset($params['oauth_signature'])) {
unset($params['oauth_signature']);
}
foreach($params as $key => $value)
{
$res[]=$key."=".$value;
}
return implode('&', $res);
//return OAuthUtil::build_http_query($params);
}
/**
* Returns the base string of this request
*
* The base string defined as the method, the url
* and the parameters (normalized), each urlencoded
* and the concated with &.
*/
public function get_signature_base_string() {
$parts = array(
$this->get_normalized_http_method(),
$this->get_normalized_http_url(),
$this->get_signable_parameters()
);
$parts = OAuthUtil::urlencode_rfc3986($parts);
return implode('&', $parts);
}
/**
* just uppercases the http method
*/
public function get_normalized_http_method() {
return strtoupper($this->http_method);
}
/**
* parses the url and rebuilds it to be
* scheme://host/path
*/
public function get_normalized_http_url() {
$parts = parse_url($this->http_url);
$scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
$port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
$host = (isset($parts['host'])) ? $parts['host'] : '';
$path = (isset($parts['path'])) ? $parts['path'] : '';
if (($scheme == 'https' && $port != '443')
|| ($scheme == 'http' && $port != '80')) {
$host = "$host:$port";
}
return "$scheme://$host$path";
}
/**
* builds a url usable for a GET request
*/
public function to_url() {
$post_data = $this->to_postdata();
$out = $this->get_normalized_http_url();
if ($post_data) {
$out .= '?'.$post_data;
}
return $out;
}
/**
* builds the data one would send in a POST request
*/
public function to_postdata() {
return OAuthUtil::build_http_query($this->parameters);
}
/**
* builds the Authorization: header
*/
public function to_header($realm=null) {
$first = true;
if($realm) {
$out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
$first = false;
} else
$out = 'Authorization: OAuth';
$total = array();
foreach ($this->parameters as $k => $v) {
if (substr($k, 0, 5) != "oauth") continue;
if (is_array($v)) {
throw new OAuthException('Arrays not supported in headers');
}
$out .= ($first) ? ' ' : ',';
$out .= OAuthUtil::urlencode_rfc3986($k) .
'="' .
OAuthUtil::urlencode_rfc3986($v) .
'"';
$first = false;
}
return $out;
}
public function __toString() {
return $this->to_url();
}
public function sign_request($signature_method,$consumer, $token) {
$empty=false;
$msg=array();
if( $token->key==null){
$msg[] = 'Token key';
}
if($token->secret==null){
$msg[] = 'Token secret';
}
if($consumer->key == null){
$msg[] = 'Consumer key';
}
if($consumer->secret == null){
$msg[] = 'Consumer secret';
}
if($this->http_url == null){
$msg[] ='Endpoint';
}
if($this->http_method == null){
$msg[] ='HTTP method';
}
if(count($msg))
{
throw new OAuthException('Enter valid '. implode(',',$msg));
}
$this->set_parameter(
"oauth_signature_method",
$signature_method->get_name(),
false );
$signature = $this->build_signature($signature_method, $consumer, $token);
$this->set_parameter("oauth_signature", $signature, false);
}
public function build_signature($signature_method, $consumer, $token) {
$signature = $signature_method->build_signature($this, $consumer, $token);
return $signature;
}
/**
* util function: current timestamp
*/
private static function generate_timestamp() {
return time();
}
/**
* util function: current nonce
*/
private static function generate_nonce() {
$mt = microtime();
$rand = mt_rand();
return md5($mt . $rand); // md5s look nicer than numbers
}
}
class OAuthServer {
protected $timestamp_threshold = 300; // in seconds, five minutes
protected $version = '1.0'; // hi blaine
protected $signature_methods = array();
protected $data_store;
function __construct($data_store) {
$this->data_store = $data_store;
}
public function add_signature_method($signature_method) {
$this->signature_methods[$signature_method->get_name()] =
$signature_method;
}
// high level functions
/**
* process a request_token request
* returns the request token on success
*/
public function fetch_request_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// no token required for the initial token request
$token = NULL;
$this->check_signature($request, $consumer, $token);
// Rev A change
$callback = $request->get_parameter('oauth_callback');
$new_token = $this->data_store->new_request_token($consumer, $callback);
return $new_token;
}
/**
* process an access_token request
* returns the access token on success
*/
public function fetch_access_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// requires authorized request token
$token = $this->get_token($request, $consumer, "request");
$this->check_signature($request, $consumer, $token);
// Rev A change
$verifier = $request->get_parameter('oauth_verifier');
$new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
return $new_token;
}
/**
* verify an api call, checks all the parameters
*/
public function verify_request(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
$token = $this->get_token($request, $consumer, "access");
$this->check_signature($request, $consumer, $token);
return array($consumer, $token);
}
// Internals from here
/**
* version 1
*/
private function get_version(&$request) {
$version = $request->get_parameter("oauth_version");
if (!$version) {
// Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
// Chapter 7.0 ("Accessing Protected Ressources")
$version = '1.0';
}
if ($version !== $this->version) {
throw new OAuthException("OAuth version '$version' not supported");
}
return $version;
}
/**
* figure out the signature with some defaults
*/
private function get_signature_method($request) {
$signature_method = $request instanceof OAuthRequest
? $request->get_parameter("oauth_signature_method")
: NULL;
if (!$signature_method) {
// According to chapter 7 ("Accessing Protected Ressources") the signature-method
// parameter is required, and we can't just fallback to PLAINTEXT
throw new OAuthException('No signature method parameter. This parameter is required');
}
if (!in_array($signature_method,
array_keys($this->signature_methods))) {
throw new OAuthException(
"Signature method '$signature_method' not supported " .
"try one of the following: " .
implode(", ", array_keys($this->signature_methods))
);
}
return $this->signature_methods[$signature_method];
}
/**
* try to find the consumer for the provided request's consumer key
*/
private function get_consumer($request) {
$consumer_key = $request instanceof OAuthRequest
? $request->get_parameter("oauth_consumer_key")
: NULL;
if (!$consumer_key) {
throw new OAuthException("Invalid consumer key");
}
$consumer = $this->data_store->lookup_consumer($consumer_key);
if (!$consumer) {
throw new OAuthException("Invalid consumer");
}
return $consumer;
}
/**
* try to find the token for the provided request's token key
*/
private function get_token($request, $consumer, $token_type="access") {
$token_field = $request instanceof OAuthRequest
? $request->get_parameter('oauth_token')
: NULL;
$token = $this->data_store->lookup_token(
$consumer, $token_type, $token_field
);
if (!$token) {
throw new OAuthException("Invalid $token_type token: $token_field");
}
return $token;
}
/**
* all-in-one function to check the signature on a request
* should guess the signature method appropriately
*/
private function check_signature($request, $consumer, $token) {
// this should probably be in a different method
$timestamp = $request instanceof OAuthRequest
? $request->get_parameter('oauth_timestamp')
: NULL;
$nonce = $request instanceof OAuthRequest
? $request->get_parameter('oauth_nonce')
: NULL;
$this->check_timestamp($timestamp);
$this->check_nonce($consumer, $token, $nonce, $timestamp);
$signature_method = $this->get_signature_method($request);
$signature = $request->get_parameter('oauth_signature');
$valid_sig = $signature_method->check_signature(
$request,
$consumer,
$token,
$signature
);
if (!$valid_sig) {
throw new OAuthException("Invalid signature");
}
}
/**
* check that the timestamp is new enough
*/
private function check_timestamp($timestamp) {
if( ! $timestamp )
throw new OAuthException(
'Missing timestamp parameter. The parameter is required'
);
// verify that timestamp is recentish
$now = time();
if (abs($now - $timestamp) > $this->timestamp_threshold) {
throw new OAuthException(
"Expired timestamp, yours $timestamp, ours $now"
);
}
}
/**
* check that the nonce is not repeated
*/
private function check_nonce($consumer, $token, $nonce, $timestamp) {
if( ! $nonce )
throw new OAuthException(
'Missing nonce parameter. The parameter is required'
);
// verify that the nonce is uniqueish
$found = $this->data_store->lookup_nonce(
$consumer,
$token,
$nonce,
$timestamp
);
if ($found) {
throw new OAuthException("Nonce already used: $nonce");
}
}
}
class OAuthDataStore {
function lookup_consumer($consumer_key) {
// implement me
}
function lookup_token($consumer, $token_type, $token) {
// implement me
}
function lookup_nonce($consumer, $token, $nonce, $timestamp) {
// implement me
}
function new_request_token($consumer, $callback = null) {
// return a new token attached to this consumer
}
function new_access_token($token, $consumer, $verifier = null) {
// return a new access token attached to this consumer
// for the user associated with this token if the request token
// is authorized
// should also invalidate the request token
}
}
class OAuthUtil {
public static function urlencode_rfc3986($input) {
if (is_array($input)) {
return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
} else if (is_scalar($input)) {
$tmp1=str_replace('%7E', '~', rawurlencode($input));
$tmp2=str_replace(".","%2E",$tmp1);
$tmp3=str_replace("*","%2A",$tmp2);
$tmp4=str_replace( '+', ' ',$tmp3);
$tmp=str_replace("-","%2D",$tmp4);
return $tmp;
/*$tmp1=str_replace('%7E', '~', rawurlencode($input));
$tmp2= str_replace(".","%2E",$tmp1);
return $tmp;*/
}
else {
return '';
}
}
public static function parseQueryString($str) {
$op = array();
$pairs = explode("&", $str);
foreach ($pairs as $pair) {
list($k, $v) = array_map("urldecode", explode("=", $pair));
$op[$k] = $v;
}
return $op;
}
//parses string to associative array -modified for PayPal Signature
// This decode function isn't taking into consideration the above
// modifications to the encoding process. However, this method doesn't
// seem to be used anywhere so leaving it as is.
public static function urldecode_rfc3986($string) {
return urldecode($string);
}
// Utility function for turning the Authorization: header into
// parameters, has to do some unescaping
// Can filter out any non-oauth parameters if needed (default behaviour)
// May 28th, 2010 - method updated to tjerk.meesters for a speed improvement.
// see http://code.google.com/p/oauth/issues/detail?id=163
public static function split_header($header, $only_allow_oauth_parameters = true) {
$params = array();
if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) {
foreach ($matches[1] as $i => $h) {
$params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]);
}
if (isset($params['realm'])) {
unset($params['realm']);
}
}
return $params;
}
// helper to try to sort out headers for people who aren't running apache
public static function get_headers() {
if (function_exists('apache_request_headers')) {
// we need this to get the actual Authorization: header
// because apache tends to tell us it doesn't exist
$headers = apache_request_headers();
// sanitize the output of apache_request_headers because
// we always want the keys to be Cased-Like-This and arh()
// returns the headers in the same case as they are in the
// request
$out = array();
foreach ($headers AS $key => $value) {
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("-", " ", $key)))
);
$out[$key] = $value;
}
} else {
// otherwise we don't have apache and are just going to have to hope
// that $_SERVER actually contains what we need
$out = array();
if( isset($_SERVER['CONTENT_TYPE']) )
$out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
if( isset($_ENV['CONTENT_TYPE']) )
$out['Content-Type'] = $_ENV['CONTENT_TYPE'];
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
// this is chaos, basically it is just there to capitalize the first
// letter of every word that is not an initial HTTP and strip HTTP
// code from przemek
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
);
$out[$key] = $value;
}
}
}
return $out;
}
// This function takes a input like a=b&a=c&d=e and returns the parsed
// parameters like this
// array('a' => array('b','c'), 'd' => 'e')
public static function parse_parameters( $input ) {
if (!isset($input) || !$input) return array();
$pairs = explode('&', $input);
$parsed_parameters = array();
foreach ($pairs as $pair) {
$split = explode('=', $pair, 2);
$parameter = OAuthUtil::urldecode_rfc3986($split[0]);
$value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
if (isset($parsed_parameters[$parameter])) {
// We have already recieved parameter(s) with this name, so add to the list
// of parameters with this name
if (is_scalar($parsed_parameters[$parameter])) {
// This is the first duplicate, so transform scalar (string) into an array
// so we can add the duplicates
$parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
}
$parsed_parameters[$parameter][] = $value;
} else {
$parsed_parameters[$parameter] = $value;
}
}
return $parsed_parameters;
}
public static function build_http_query($params) {
if (!$params) return '';
// Urlencode both keys and values
$keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
$values = OAuthUtil::urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
// Parameters are sorted by name, using lexicographical byte value ordering.
// Ref: Spec: 9.1.1 (1)
uksort($params, 'strcmp');
$pairs = array();
foreach ($params as $parameter => $value) {
if (is_array($value)) {
// If two or more parameters share the same name, they are sorted by their value
// Ref: Spec: 9.1.1 (1)
// June 12th, 2010 - changed to sort because of issue 164 by hidetaka
sort($value, SORT_STRING);
foreach ($value as $duplicate_value) {
$pairs[] = $parameter . '=' . $duplicate_value;
}
} else {
$pairs[] = $parameter . '=' . $value;
}
}
// For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
// Each name-value pair is separated by an '&' character (ASCII code 38)
return implode('&', $pairs);
}
}
lib/auth/PPTokenAuthorization.php 0000666 00000001446 13436755715 0013116 0 ustar 00 accessToken = $accessToken;
$this->tokenSecret = $tokenSecret;
}
public function getAccessToken() {
return $this->accessToken;
}
public function getTokenSecret() {
return $this->tokenSecret;
}
} lib/formatters/PPSOAPFormatter.php 0000666 00000001666 13436755715 0013134 0 ustar 00 getBindingInfo('namespace') != null ) ? $request->getBindingInfo('namespace') : "";
$soapEnvelope = '";
$soapHeader = '';
if($request->getBindingInfo('securityHeader') != null) {
$soapHeader .= $request->getBindingInfo('securityHeader');
}
$soapHeader .= '';
$soapBody = '';
$soapBody .= $request->getRequestObject()->toXMLString();
$soapBody .= '';
return $soapEnvelope . $soapHeader . $soapBody . '';
}
public function toObject($string, $options=array()) {
throw new BadMethodCallException("Unimplemented");
}
}
lib/formatters/PPNVPFormatter.php 0000666 00000000435 13436755715 0013026 0 ustar 00 getRequestObject()->toNVPString();
}
public function toObject($string, $options=array()) {
throw new BadMethodCallException("Unimplemented");
}
}
lib/formatters/IPPFormatter.php 0000666 00000000754 13436755715 0012557 0 ustar 00 toXMLString();
}
/**
* @return string
*/
public function toXMLString()
{
$attributes = array();
$properties = get_object_vars($this);
foreach (array_keys($properties) as $property) {
if (($annots = PPUtils::propertyAnnotations($this, $property)) && isset($annots['attribute'])) {
if (($propertyValue = $this->{$property}) === NULL || $propertyValue == NULL) {
$attributes[] = NULL;
continue;
}
$attributes[] = $property . '="' . PPUtils::escapeInvalidXmlCharsRegex($propertyValue) . '"';
}
}
$attrs = implode(' ', $attributes) . (count($attributes) > 0 ? ">" : "");
$xml = array();
foreach ($properties as $property => $defaultValue) {
if (($propertyValue = $this->{$property}) === NULL || $propertyValue == NULL) {
continue;
}
if (($annots = PPUtils::propertyAnnotations($this, $property)) && isset($annots['attribute'])) {
continue;
}
if (isset($annots['value'])) {
$xml[] = PPUtils::escapeInvalidXmlCharsRegex($propertyValue);
break;
}
if (is_array($defaultValue) || is_array($propertyValue)) {
foreach ($propertyValue as $item) {
if (!is_object($item)) {
$xml[] = $this->buildProperty($property, $item);
}else{
$xml[] = $this->buildProperty($property, $item);
}
}
} else {
$xml[] = $this->buildProperty($property, $propertyValue);
}
}
return $attrs . implode($xml);
}
/**
* @param string $property
* @param PPXmlMessage|string $value
* @param string $namespace
* @return string
*/
private function buildProperty($property, $value, $namespace = 'ebl')
{
$annotations = PPUtils::propertyAnnotations($this, $property);
if (!empty($annotations['namespace'])) {
$namespace = $annotations['namespace'];
}
if (!empty($annotations['name'])) {
$property = $annotations['name'];
}
if($namespace === true)
{
$el = '<' . $property;
}
else
{
$el = '<' . $namespace . ':' . $property;
}
if (!is_object($value)) {
$el .= '>' . PPUtils::escapeInvalidXmlCharsRegex($value);
} else {
if (substr($value = $value->toXMLString(), 0, 1) === '<' || $value=='') {
$el .= '>' . $value;
} else {
$el .= ' ' . $value;
}
}
if($namespace === true)
{
return $el . '' . $property . '>';
}
else
{
return $el . '' . $namespace . ':' . $property . '>';
}
}
/**
* @param array $map intermediate array representation of XML message to deserialize
* @param string $isRoot true if this is a root class for SOAP deserialization
*/
public function init(array $map = array(), $isRoot=true)
{
if($isRoot) {
if(stristr($map[0]['name'], ":fault")) {
throw new PPTransformerException("soapfault");
} else {
$map = $map[0]['children'];
}
}
if (empty($map)) {
return;
}
if (($first = reset($map)) && !is_array($first) && !is_numeric(key($map))) {
parent::init($map, false);
return;
}
$propertiesMap = PPUtils::objectProperties($this);
$arrayCtr = array();
foreach ($map as $element) {
if (empty($element) || empty($element['name'])) {
continue;
} elseif (!array_key_exists($property = strtolower($element['name']), $propertiesMap)) {
if (!preg_match('~^(.+)[\[\(](\d+)[\]\)]$~', $property, $m)) {
continue;
}
$element['name'] = $m[1];
$element['num'] = $m[2];
}
$element['name'] = $propertiesMap[strtolower($element['name'])];
if(PPUtils::isPropertyArray($this, $element['name'])) {
$arrayCtr[$element['name']] = isset($arrayCtr[$element['name']]) ? ($arrayCtr[$element['name']]+1) : 0;
$element['num'] = $arrayCtr[$element['name']];
}
if (!empty($element["attributes"]) && is_array($element["attributes"])) {
foreach ($element["attributes"] as $key => $val) {
$element["children"][] = array(
'name' => $key,
'text' => $val,
);
}
if (isset($element['text'])) {
$element["children"][] = array(
'name' => 'value',
'text' => $element['text'],
);
}
$this->fillRelation($element['name'], $element);
} elseif (isset($element['text']) && !is_null($element['text'])) {
if (isset($element['num'])) {
$this->{$element['name']}[$element['num']] = $element['text'];
} else {
$this->{$element['name']} = $element['text'];
}
} elseif (!empty($element["children"]) && is_array($element["children"])) {
$this->fillRelation($element['name'], $element);
}
}
}
/**
* @param string $property
* @param array $element
*/
private function fillRelation($property, array $element)
{
if (!class_exists($type = PPUtils::propertyType($this, $property))) {
trigger_error("Class $type not found.", E_USER_NOTICE);
return; // just ignore
}
if (isset($element['num'])) { // array of objects
$this->{$property}[$element['num']] = $item = new $type();
$item->init($element['children'], false);
} else {
$this->{$property} = new $type();
$this->{$property}->init($element["children"], false);
}
}
}
lib/ipn/PPIPNMessage.php 0000666 00000006761 13436755715 0011042 0 ustar 00 config = PPConfigManager::getConfigWithDefaults($config);
if($postData == '') {
// reading posted data from directly from $_POST may causes serialization issues with array data in POST
// reading raw POST data from input stream instead.
$postData = file_get_contents('php://input');
}
$rawPostArray = explode('&', $postData);
foreach ($rawPostArray as $keyValue) {
$keyValue = explode ('=', $keyValue);
if (count($keyValue) == 2)
$this->ipnData[$keyValue[0]] = urldecode($keyValue[1]);
}
//var_dump($this->ipnData);
}
/**
* Returns a hashmap of raw IPN data
*
* @return array
*/
public function getRawData() {
return $this->ipnData;
}
/**
* Validates a IPN message
*
* @return boolean
*/
public function validate() {
if(isset($this->isIpnVerified))
{
return $this->isIpnVerified;
}
else
{
$request = self::IPN_CMD;
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() == 1) {
$get_magic_quotes_exists = true;
} else {
$get_magic_quotes_exists = false;
}
foreach ($this->ipnData as $key => $value) {
if($get_magic_quotes_exists) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$request .= "&$key=$value";
}
$httpConfig = new PPHttpConfig($this->setEndpoint());
$httpConfig->addCurlOption(CURLOPT_FORBID_REUSE, 1);
$httpConfig->addCurlOption(CURLOPT_HTTPHEADER, array('Connection: Close'));
$connection = PPConnectionManager::getInstance()->getConnection($httpConfig, $this->config);
$response = $connection->execute($request);
if($response == 'VERIFIED') {
$this->isIpnVerified = true;
return true;
}
$this->isIpnVerified = false;
return false; // value is 'INVALID'
}
}
/**
* Returns the transaction id for which
* this IPN was generated, if one is available
*
* @return string
*/
public function getTransactionId() {
if(isset($this->ipnData['txn_id'])) {
return $this->ipnData['txn_id'];
} else if(isset($this->ipnData['transaction[0].id'])) {
$idx = 0;
do {
$transId[] = $this->ipnData["transaction[$idx].id"];
$idx++;
} while(isset($this->ipnData["transaction[$idx].id"]));
return $transId;
}
}
/**
* Returns the transaction type for which
* this IPN was generated
*
* @return string
*/
public function getTransactionType() {
return $this->ipnData['transaction_type'];
}
private function setEndpoint()
{
if(isset($this->config['service.EndPoint.IPN']))
{
$url = $this->config['service.EndPoint.IPN'];
}
else if(isset($this->config['mode']))
{
if(strtoupper($this->config['mode']) == 'SANDBOX')
{
$url = PPConstants::IPN_SANDBOX_ENDPOINT;
}
else if (strtoupper($this->config['mode']) == 'LIVE')
{
$url = PPConstants::IPN_LIVE_ENDPOINT;
}
else
{
throw new PPConfigurationException('mode should be LIVE or SANDBOX');
}
}
else
{
throw new PPConfigurationException('You must set one of mode OR service.endpoint.IPN parameters');
}
return $url;
}
}
lib/PPCredentialManager.php 0000666 00000010026 13436755715 0011653 0 ustar 00 initCredential($config);
} catch (Exception $e) {
$this->credentialHashmap = array();
throw $e;
}
}
/*
* Create singleton instance for this class.
*/
public static function getInstance($config)
{
return self::$instance = new PPCredentialManager($config);
}
/*
* Load credentials for multiple accounts, with priority given to Signature credential.
*/
private function initCredential($config) {
$suffix = 1;
$prefix = "acct";
$credArr = array();
$arr = array();
foreach ($config as $key => $value) {
$pos = strpos($key, '.');
if(strstr($key, $prefix)){
$credArr[$key] = $value;
$arr[] = substr($key, 0, $pos);
}
}
$arrayPartKeys = array_unique($arr);
if(count($arrayPartKeys) == 0)
throw new PPMissingCredentialException("No valid API accounts have been configured");
$key = $prefix.$suffix;
while (in_array($key, $arrayPartKeys)){
if(isset($credArr[$key.".Signature"])
&& $credArr[$key.".Signature"] != null && $credArr[$key.".Signature"] != ""){
$userName = isset($credArr[$key.'.UserName']) ? $credArr[$key.'.UserName'] : "";
$password = isset($credArr[$key.'.Password']) ? $credArr[$key.'.Password'] : "";
$signature = isset($credArr[$key.'.Signature']) ? $credArr[$key.'.Signature'] : "";
$this->credentialHashmap[$userName] = new PPSignatureCredential($userName, $password, $signature);
if (isset($credArr[$key.'.AppId'])) {
$this->credentialHashmap[$userName]->setApplicationId($credArr[$key.'.AppId']);
}
} elseif (isset($credArr[$key.".CertPath"])
&& $credArr[$key.".CertPath"] != null && $credArr[$key.".CertPath"] != ""){
$userName = isset($credArr[$key.'.UserName']) ? $credArr[$key.'.UserName'] : "";
$password = isset($credArr[$key.'.Password']) ? $credArr[$key.'.Password'] : "";
$certPassPhrase = isset($credArr[$key.'.CertKey']) ? $credArr[$key.'.CertKey'] : "";
$certPath = isset($credArr[$key.'.CertPath']) ? $credArr[$key.'.CertPath'] : "";
$this->credentialHashmap[$userName] = new PPCertificateCredential($userName, $password, $certPath, $certPassPhrase);
if (isset($credArr[$key.'.AppId'])) {
$this->credentialHashmap[$userName]->setApplicationId($credArr[$key.'.AppId']);
}
} elseif (isset($credArr[$key.".ClientId"]) && isset($credArr[$key.".ClientId"]) ){
$userName = $key;
$this->credentialHashmap[$userName] = array('clientId' => $credArr[$key.".ClientId"],
'clientSecret' => $credArr[$key.".ClientSecret"]);
}
if($userName && isset($credArr[$key . ".Subject"]) && trim($credArr[$key . ".Subject"]) != "" ) {
$this->credentialHashmap[$userName]->setThirdPartyAuthorization(
new PPSubjectAuthorization($credArr[$key . ".Subject"]));
}
if ($userName && $this->defaultAccountName == null) {
if(array_key_exists($key. '.UserName', $credArr)) {
$this->defaultAccountName = $credArr[$key . '.UserName'];
} else {
$this->defaultAccountName = $key;
}
}
$suffix++;
$key = $prefix.$suffix;
}
}
/*
* Obtain Credential Object based on UserId provided.
*/
public function getCredentialObject($userId = null){
if($userId == null) {
$credObj = $this->credentialHashmap[$this->defaultAccountName];
} else if (array_key_exists($userId, $this->credentialHashmap)) {
$credObj = $this->credentialHashmap[$userId];
}
if (empty($credObj)) {
throw new PPInvalidCredentialException("Invalid userId $userId");
}
return $credObj;
}
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
lib/common/PPArrayUtil.php 0000666 00000000406 13436755715 0011513 0 ustar 00 $v) {
if(is_int($k)) {
return false;
}
}
return true;
}
} lib/common/PPModel.php 0000666 00000003142 13436755715 0010637 0 ustar 00 _propMap[$key];
}
public function __set($key, $value) {
$this->_propMap[$key] = $value;
}
public function __isset($key) {
return isset($this->_propMap[$key]);
}
public function __unset($key) {
unset($this->_propMap[$key]);
}
private function _convertToArray($param) {
$ret = array();
foreach($param as $k => $v) {
if($v instanceof PPModel ) {
$ret[$k] = $v->toArray();
} else if (is_array($v)) {
$ret[$k] = $this->_convertToArray($v);
} else {
$ret[$k] = $v;
}
}
return $ret;
}
public function fromArray($arr) {
foreach($arr as $k => $v) {
if(is_array($v)) {
$clazz = PPReflectionUtil::getPropertyClass(get_class($this), $k);
if(PPArrayUtil::isAssocArray($v)) {
$o = new $clazz();
$o->fromArray($v);
$this->__set($k, $o);
} else {
$arr = array();
foreach($v as $nk => $nv) {
if(is_array($nv)) {
$o = new $clazz();
$o->fromArray($nv);
$arr[$nk] = $o;
} else {
$arr[$nk] = $nv;
}
}
$this->__set($k, $arr);
}
}else {
$this->$k = $v;
}
}
}
public function fromJson($json) {
$this->fromArray(json_decode($json, true));
}
public function toArray() {
return $this->_convertToArray($this->_propMap);
}
public function toJSON() {
return json_encode($this->toArray());
}
} lib/common/PPApiContext.php 0000666 00000003205 13436755715 0011655 0 ustar 00 httpHeaders = $httpHeaders;
return $this;
}
/*
*
* @return array
*/
public function getHttpHeaders() {
return $this->httpHeaders;
}
/*
*
* @param string $name header name
* @param string $value header value
* @param boolean $force if true (default), existing value is overwritten
*/
public function addHttpHeader($name, $value, $force=true) {
if(!$force && array_key_exists($name, $this->httpHeaders)) {
return;
}
$this->httpHeaders[$name] = $value;
return $this;
}
/*
*
* @param PPXmlMessage object to attach to SOAP header
*/
public function setSOAPHeader($SOAPHeader) {
$this->SOAPHeader = $SOAPHeader;
return $this;
}
/*
*
* @return PPXmlMessage
*/
public function getSOAPHeader() {
return $this->SOAPHeader;
}
/*
*
* @param array SDK configuration parameters
*/
public function setConfig(array $config) {
$this->config = PPConfigManager::getConfigWithDefaults($config);
return $this;
}
/*
*
* @return array
*/
public function getConfig() {
return $this->config;
}
/*
*
* @param array SDK configuration parameters
*/
public function __construct($config=null) {
$this->config = PPConfigManager::getConfigWithDefaults($config);
}
}
lib/common/PPUserAgent.php 0000666 00000001760 13436755715 0011500 0 ustar 00 getDocComment(), $annots, PREG_PATTERN_ORDER)) {
return NULL;
}
foreach ($annots[1] as $i => $annot) {
$annotations[strtolower($annot)] = empty($annots[2][$i]) ? TRUE : rtrim($annots[2][$i], " \t\n\r)");
}
return $annotations;
}
/**
* preg_replace_callback callback function
*/
private static function replace_callback($match) {
return ucwords($match[2]);
}
}
README.md 0000666 00000002471 13436755715 0006053 0 ustar 00 # PayPal Core SDK - V1.5.0
## Prerequisites
* PHP 5.2 and above
* curl extension with support for OpenSSL
* PHPUnit 3.5 for running test suite (Optional)
* Composer (Optional - for running test cases)
## Configuration
## OpenID Connect Integration
1. Redirect your buyer to `PPOpenIdSession::getAuthorizationUrl($redirectUri, array('openid', 'address'));` to obtain authorization. The second argument is the list of access privileges that you want from the buyer.
2. Capture the authorization code that is available as a query parameter (`code`) in the redirect url
3. Exchange the authorization code for a access token, refresh token, id token combo
```php
$token = PPOpenIdTokeninfo::createFromAuthorizationCode(
array(
'code' => $authCode
)
);
```
4. The access token is valid for a predefined duration and can be used for seamless XO or for retrieving user information
```php
$user = PPOpenIdUserinfo::getUserinfo(
array(
'access_token' => $token->getAccessToken()
)
);
```
5. If the access token has expired, you can obtain a new access token using the refresh token from the 3'rd step.
```php
$token->createFromRefreshToken(array('openid', 'address'));
```
6. Redirect your buyer to `PPOpenIdSession::getLogoutUrl($redirectUri, $idToken);` to log him out of paypal.
phpunit.xml 0000666 00000001343 13436755715 0007002 0 ustar 00
.
./lib
./vendor
./lib/auth/PPAuth.php
./lib/auth/AuthUtil.php