| Current Path : /home/w/u/e/wuectly/www/03cbe/ |
| Current File : /home/w/u/e/wuectly/www/03cbe/lib.zip |
PK Ǿ!]� �O �O lib/mailjet-api-strategy.phpnu &1i� <?php
/*
* LICENSE BLOCK
*
* This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*
*/
defined('_JEXEC') or die('Restricted access');
/* Require the mailjet API libraries */
require_once (__DIR__ . '/api/mailjet-api-v1.php');
require_once (__DIR__ . '/api/mailjet-api-v3.php');
/**
* This is Api Strategy Interface
* @author Pavel Tashev
* @author Mailjet
* @link http://www.mailjet.com/
*/
# ============================================== Interface ============================================== #
interface Mailjet_Api_Interface
{
public function getSenders($params);
public function getContactLists($params);
public function addContact($params);
public function removeContact($params);
public function unsubContact($params);
public function subContact($params);
public function getAuthToken($params);
public function validateEmail($email);
}
# ============================================== Strategy ============================================== #
# Strategy ApiV1
class Mailjet_Api_Strategy_V1 extends Mailjet_Api_V1 implements Mailjet_Api_Interface
{
/**
* Get full list of senders
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getSenders($params)
{
// Set input parameters
$input = array();
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->userSenderList()->senders;
// Check if the list exists
if(isset($response))
{
$senders = array();
$senders['domain'] = array();
$senders['email'] = array();
foreach ($response as $sender)
{
if($sender->status == 'active')
{
if(substr($sender->email, 0, 2) == '*@')
$senders['domain'][] = substr($sender->email, 2, strlen($sender->email)); // This is domain
else
$senders['email'][] = $sender->email; // This is email
}
}
return $senders;
}
return (object) array('Status' => 'ERROR');
}
/**
* Get full list of contact lists
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getContactLists($params)
{
// Set input parameters
$input = array();
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->listsAll($input);
// Check if the list exists
if(isset($response->status) && $response->status == 'OK')
{
$lists = array();
foreach ($response->lists as $list)
{
$lists[] = array(
'value' => $list->id,
'label' => $list->label,
'subscribers' => $list->subscribers,
);
}
return $lists;
}
return (object) array('Status' => 'ERROR');
}
/**
* Add a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function addContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Add the contact
$response = $this->listsAddContact(array(
'method' => 'POST',
'contact' => $params['Email'],
'id' => $params['ListID']
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'ERROR');
}
/**
* Remove a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function removeContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Unsubscribe the contact
$response = $this->listsRemoveContact(array(
'method' => 'POST',
'contact' => $params['Email'],
'id' => $params['ListID']
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'OK');
}
/**
* Unsubscribe a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function unsubContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Unsubscribe the contact
$response = $this->listsUnsubContact(array(
'method' => 'POST',
'contact' => $params['Email'],
'id' => $params['ListID']
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'OK');
}
/**
* Subscribe a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function subContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Subscribe the user
$response = $this->listsAddContact(array(
'method' => 'POST',
'id' => $params['ListID'],
'contact' => $params['Email'],
'force' => 1,
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'OK');
}
/**
* Get the authentication token for the iframes
*
* @param (array) $param = array('APIKey', 'SecretKey', ...)
* @return (object)
*/
public function getAuthToken($params)
{
// Check if the input data is OK
if(strlen(trim($params['APIKey'])) == 0 || strlen(trim($params['SecretKey'])) == 0)
return (object) array('Status' => 'ERROR');
if (isset($params['MailjetToken']))
{
$op = json_decode($params['MailjetToken']);
if ($op->timestamp > time() - 3600)
return $op->token;
}
// Get the culture
if(isset($lang) && $lang != null)
{
$locale = substr($lang->getTag(), 0, 2);
if (!in_array($locale, array('en', 'fr', 'es', 'de')))
$locale = 'en';
} else {
$locale = 'en';
}
// Define some required data
$url = $this->apiUrl.'/apiKeyauthenticate?output=json';
$data = array(
'allowed_access[0]' => 'stats',
'allowed_access[1]' => 'contacts',
'allowed_access[2]' => 'campaigns',
'lang' => $locale,
'default_page' => 'campaigns',
'type' => 'page',
'apikey' => $params['APIKey']
);
// Execute POST request
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Basic ".base64_encode($params['APIKey'] . ':' . $params['SecretKey'])
));
$result = curl_exec($curl);
$resp = json_decode($result);
if (is_object($resp))
if ($resp->status == 'OK')
return $resp->token;
return (object) array('Status' => 'ERROR');
}
/**
* Validate if $email is real email
*
* @param (string) $email
* @return (boolean) TRUE|FALSE
*/
public function validateEmail($email) {
return (preg_match("/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/", $email) || !preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/", $email)) ? FALSE : TRUE;
}
}
# Strategy ApiV3
class Mailjet_Api_Strategy_V3 extends Mailjet_Api_V3 implements Mailjet_Api_Interface
{
/**
* Get full list of senders
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getSenders($params)
{
// Set input parameters
$input = array();
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->sender($input);
// Check if the list exists
if(isset($response->Data))
{
$senders = array();
$senders['domain'] = array();
$senders['email'] = array();
foreach ($response->Data as $sender)
{
if($sender->Status == 'Active')
{
if(substr($sender->Email, 0, 2) == '*@')
$senders['domain'][] = substr($sender->Email, 2, strlen($sender->Email)); // This is domain
else
$senders['email'][] = $sender->Email; // This is email
}
}
return $senders;
}
return (object) array('Status' => 'ERROR');
}
/**
* Get full list of contact lists
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getContactLists($params)
{
// Set input parameters
$input = array(
'akid' => $this->_akid
);
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->liststatistics($input);
// Check if the list exists
if(isset($response->Data))
{
$lists = array();
foreach ($response->Data as $list)
{
$lists[] = array(
'value' => $list->ID,
'label' => $list->Name,
'subscribers' => $list->SubscriberCount,
);
}
return $lists;
}
return (object) array('Status' => 'ERROR');
}
/**
* Add a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function addContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Add the contact
$result = $this->manycontacts(array(
'method' => 'POST',
'Action' => 'Add',
'Addresses' => array($params['Email']),
'ListID' => $params['ListID'],
));
// Check if any error
if(isset($result->Data['0']->Errors->Items)) {
if( strpos($result->Data['0']->Errors->Items[0]->ErrorMessage, 'duplicate') !== FALSE )
return (object) array('Status' => 'DUPLICATE');
else
return (object) array('Status' => 'ERROR');
}
$this->subContact($params);
return (object) array('Status' => 'OK');
}
/**
* Remove a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function removeContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Get the contact
$result = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'GET',
'ListID' => $params['ListID'],
'ContactEmail' => $params['Email']
));
if($result->Count > 0)
{
foreach($result->Data as $contact)
{
// Remove the contact
$response = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'delete',
'ID' => $contact->ID
));
}
// Check if the unsubscribe is done correctly
if(isset($response->Data[0]->ID))
return (object) array('Status' => 'OK');
}
return (object) array('Status' => 'ERROR');
}
/**
* Unsubscribe a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function unsubContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Get the contact
$result = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'GET',
'ListID' => $params['ListID'],
'ContactEmail' => $params['Email']
));
if($result->Count > 0)
{
foreach($result->Data as $contact)
{
if($contact->IsUnsubscribed !== TRUE)
{
$response = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'PUT',
'ID' => $contact->ID,
'IsUnsubscribed' => 'true',
'UnsubscribedAt' => date("Y-m-d\TH:i:s\Z", time()),
));
}
}
// Check if the unsubscribe is done correctly
if(isset($response->Data[0]->ID))
return (object) array('Status' => 'OK');
}
return (object) array('Status' => 'ERROR');
}
/**
* Subscribe a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function subContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Get the contact
$result = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'GET',
'ListID' => $params['ListID'],
'ContactEmail' => $params['Email']
));
if($result->Count > 0)
{
foreach($result->Data as $contact)
{
if($contact->IsUnsubscribed === TRUE)
{
$response = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'PUT',
'ID' => $contact->ID,
'IsUnsubscribed' => 'false',
));
}
}
// Check if the subscribe is done correctly
if(isset($response->Data[0]->ID))
return (object) array('Status' => 'OK');
}
return (object) array('Status' => 'ERROR');
}
/**
* Get the authentication token for the iframes
*
* @param (array) $param = array('APIKey', 'SecretKey', ...)
* @return (object)
*/
public function getAuthToken($params)
{
// Check if the input data is OK
if(strlen(trim($params['APIKey'])) == 0 || strlen(trim($params['SecretKey'])) == 0)
return (object) array('Status' => 'ERROR');
// Get the ID of the Api Key
$api_key_response = $this->apikey(array(
'method' => 'GET',
'APIKey' => $params['APIKey']
));
// Check if the response contains data
if(!isset($api_key_response->Data[0]->ID))
return (object) array('Status' => 'ERROR');
// Get token
$response = $this->apitoken(array(
'AllowedAccess' => 'campaigns,contacts,reports,stats,preferences,pricing,account',
'method' => 'POST',
'APIKeyID' => $api_key_response->Data[0]->ID,
'TokenType' => 'iframe',
'CatchedIp' => $_SERVER['REMOTE_ADDR'],
'log_once' => TRUE,
'IsActive' => TRUE
));
// Get and return the token
if(isset($response->Data) && count($response->Data) > 0)
return $response->Data[0]->Token;
return (object) array('Status' => 'ERROR');
}
/**
* Validate if $email is real email
*
* @param (string) $email
* @return (boolean) TRUE|FALSE
*/
public function validateEmail($email) {
return (preg_match("/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/", $email) || !preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/", $email)) ? FALSE : TRUE;
}
}
# ============================================== Context ============================================== #
class Mailjet_Api
{
private $context;
public $version;
public $apiUrl;
public function __construct($mailjet_username, $mailjet_password)
{
# Check the type of the user and set the corresponding Context/Strategy
// Set API V3 context and get the user and check if it's V3
$this->setContext(new Mailjet_Api_Strategy_V3($mailjet_username, $mailjet_password));
//$response = $this->context->getContactLists(array('limit' => 1));
$response = $this->context->getSenders(array('limit' => 1));
if(isset($response->Status) && $response->Status == 'ERROR')
{
// Set API V1 context and get the contact lists of this user and check if it's V1
$this->setContext(new Mailjet_Api_Strategy_V1($mailjet_username, $mailjet_password));
$response = $this->context->getSenders(array('limit' => 1));
if(isset($response->Status) && $response->Status == 'ERROR')
{
$this->clearContext();
}
else {
// Get the version and the apiUrl of the API
$this->version = $this->context->version;
$this->apiUrl = 'in.mailjet.com';
}
} else {
// Get the version and the apiUrl of the API
$this->version = $this->context->getVersion();
$this->apiUrl = 'in-v3.mailjet.com';
}
}
/**
* Set the context of the Api - V1 or V3
*
* @param Mailjet_Api_Interface $context
* @return void
*/
private function setContext(Mailjet_Api_Interface $context)
{
$this->context = $context;
}
/**
* Clear the context
*
* @param void
* @return void
*/
private function clearContext()
{
$this->context = FALSE;
}
/**
* Get full list of senders
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getSenders($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->getSenders($params);
}
/**
* Get full list of contact lists
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getContactLists($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->getContactLists($params);
}
/**
* Add a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function addContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->addContact($params);
}
/**
* Remove a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function removeContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->removeContact($params);
}
/**
* Unsubscribe a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function unsubContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->unsubContact($params);
}
/**
* Subscribe a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function subContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->subContact($params);
}
/**
* Get the authentication token for the iframes
*
* @param (array) $param = array('APIKey', 'SecretKey', ...)
* @return (object)
*/
public function getAuthToken($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->getAuthToken($params);
}
/**
* Validate if $email is real email
*
* @param (string) $email
* @return (boolean) TRUE|FALSE
*/
public function validateEmail($email) {
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->validateEmail($email);
}
}
PK Ǿ!]��7�o o lib/api/mailjet-api-v3.phpnu &1i� <?php
/**
* Mailjet Public API / The real-time Cloud Emailing platform
*
* Connect your Apps and Make our product yours with our powerful API
* http://www.mailjet.com/ Mailjet SAS Website
*
* @package API v0.3
* @author David Coullet
* @author Mailjet Dev team
* @copyright Copyright (c) 2012-2013, Mailjet SAS, http://www.mailjet.com/Terms-of-use.htm
* @file
*/
// ---------------------------------------------------------------------
/**
* Mailjet Public API Main Class
*
* This class enables you to connect your Apps and use our powerful API.
* You can use the 'metadata' call to retrieve a list of each object available
* or implemented a live discovery.
* http://www.mailjet.com/docs/api
*
* updated on 2013-09-03
*
* @class MailjetApi
* @author David Coullet
* @author Mailjet Dev team
* @version 0.1
*/
class Mailjet_Api_V3
{
/**
* Mailjet API Key to use.
* You can edit directly and add here your Mailjet infos
*
* @access private
* @var string $_apiKey
*/
private $_apiKey = '';
/**
* Mailjet API Secret Key to use.
* You can edit directly and add here your Mailjet infos
*
* @access private
* @var string $_secretKey
*/
private $_secretKey = '';
/**
* Seconds before updating the cache object
* If set to 0, Object caching will be disabled
*
* @access private
* @var integer $_cache
*/
private $_cache = 0;//600;
// ---------------------------------------------------------------------
/**
* API URL
*
* @access private
* @var string
*/
private $_apiUrl = 'api.mailjet.com/v3/';
/**
* API version to use
*
* @access private
* @var string
*/
private $_version = 'REST';
/**
* Debug internal flag
*
* @access private
* @var boolean
*/
private $_debug = false;
/**
* Debug Label
*
* @access private
* @var string
*/
private $_debug_info = '';
/**
* Debug buffer copy
*
* @access private
* @var string
*/
private $_buffer = '';
/**
* Debug method copy
*
* @access private
* @var string
*/
private $_method = '';
/**
* Debug by cURL
*
* @access private
* @var array
*/
private $_info = NULL;
/**
* cURL handle resource
*
* @access private
* @var resource
*/
private $_curl_handle = NULL;
/**
*
* @var Boolean
*/
protected $_log_allowed = false;
/**
*
* @var Boolean
*/
protected $_log = false;
/**
*
* @var Boolean
*/
protected $_log_once = false;
/**
*
* @var Boolean
*/
protected $_extra_err = false;
/**
*
* @var String
*/
protected $_log_path = 'logs/api/current.log';
/**
* Singleton pattern : Current instance
*
* @access private
* @var resource
*/
private static $_instance = NULL;
/**
* Constructor
*
* Set $_apiKey and $_secretKey if provided & Update $_apiUrl with protocol
*
* @access public
* @uses MailjetApi::$_apiKey
* @uses MailjetApi::$_secretKey
* @param string $_apiKey Mailjet API Key
* @param string $_secretKey Mailjet API Secret Key
* @param boolean $secure TRUE to secure the transaction, FALSE otherwise
*/
public function __construct($apiKey = NULL, $secretKey = NULL, $secure = FALSE)
{
if (isset($apiKey))
$this->_apiKey = $apiKey;
if (isset($secretKey))
$this->_secretKey = $secretKey;
$this->_apiUrl = 'http://'.$this->_apiUrl.$this->_version.'/';
$this->secure($secure);
$this->_log_allowed = get_cfg_var('MAILJET_ENVIRONMENT') == 'dev';
$this->_fixLogPath();
}
/**
* Singleton pattern :
* Get the instance of the object if it already exists
* or create a new one.
*
* @access public
* @uses MailjetApi::$_instance
*/
public static function getInstance()
{
if (!(self::$_instance instanceof self))
self::$_instance = new self();
return self::$_instance;
}
/**
* Destructor
*
* Close the cURL handle resource
*
* @access public
* @uses MailjetApi::$_curl_handle
*/
public function __destruct()
{
if(!is_null($this->_curl_handle))
curl_close($this->_curl_handle);
$this->_curl_handle = NULL;
}
/**
* Set new Api Key and Secret Key
*
* @access public
* @uses MailjetApi::$_apiKey
* @uses MailjetApi::$_secretKey
* @param string $apiKey Mailjet API Key
* @param string $secretKey Mailjet API Secret Key
*/
public function setKeys($apiKey, $secretKey)
{
$this->_apiKey = $apiKey;
$this->_secretKey = $secretKey;
}
/**
* Set the seconds before updating the cache object
* If set to 0, Object caching will be disabled
*
* @access public
* @uses MailjetApi::$_cache
* @param integer $cache Cache to set in seconds
*/
public function setCache($cache)
{
$this->_cache = $cache;
}
/**
* Get the seconds before updating the cache object
* If set to 0, Object caching will be disabled
*
* @access public
* @uses MailjetApi::$_cache
*
* @return integer Cache in seconds
*/
public function getCache()
{
return ($this->_cache);
}
/**
*
* @param Boolean $flag
* @return mailjetapi
*/
public function setLog($flag)
{
$this->_log = (boolean) $flag;
return $this;
}
/**
*
* @return boolean
*/
public function getLog()
{
return $this->_log;
}
/**
*
* @param Boolean $flag
* @return mailjetapi
*/
public function setLogOnce($flag)
{
$this->_log_once = (boolean) $flag;
return $this;
}
/**
*
* @return boolean
*/
public function getLogOnce()
{
return $this->_log_once;
}
/**
*
* @return string
*/
public function getVersion()
{
return $this->_version;
}
/**
*
* @param Boolean $flag
* @return mailjetapi
*/
public function setExtraError($flag)
{
$this->_extra_err = (boolean) $flag;
return $this;
}
/**
*
* @return boolean
*/
public function getExtraError()
{
return $this->_extra_err;
}
/**
* Enable log only if MAILJET_ENVIRONMENT == 'dev'
* @return boolean
*/
public function logAllowed()
{
return $this->_log_allowed;
}
/**
*
* @param String $path
* @return mailjetapi
*/
public function setLogPath($path)
{
if ($real_path = realpath($path)) {
$this->_log_path = $real_path;
}
return $this;
}
/**
*
* @return String
*/
public function getLogPath()
{
return $this->_log_path;
}
/**
*
* @return mailjetapi
*/
protected function _fixLogPath()
{
//fix log path
if(!defined('SYSTEMPATH')) define('SYSTEMPATH', dirname(__FILE__).'/../');
$this->_log_path = realpath(SYSTEMPATH.$this->_log_path);
$logFilename = 'daily-'.date('Ymd').'.log';
$this->_log_path = str_replace('current.log', $logFilename, $this->_log_path);
return $this;
}
/**
* Secure or not the transaction through https
*
* @access public
* @uses MailjetApi::$_apiUrl
* @param boolean $secure TRUE to secure the transaction, FALSE otherwise
*/
public function secure($secure = TRUE)
{
$protocol = 'http';
if ($secure)
$protocol = 'https';
$this->_apiUrl = preg_replace('/http(s)?:\/\//', $protocol.'://', $this->_apiUrl);
}
/**
* Make the magic call ;)
*
* Check for some arguments and order them before sending the request.
* If '_debug_info' is found, some data are stored and can be retrieved
* with a call to MailjetApi::getDebugInfo().
*
* @access public
* @uses MailjetApi::$_debug
* @uses MailjetApi::$_debug_info
* @uses MailjetApi::sendRequest() to send the request
* @param string $object Method to call
* @param array $args Array of parameters
*
* @return string JSON string by default (format can be change with the 'format' parameter)
*/
public function __call($object, $args)
{
if (sizeof($args) > 0)
$params = $args[0];
else
$params = array();
if (isset($params['method'])) {
$method = strtoupper($params['method']);
unset($params['method']);
}
if (!isset($method) || !in_array($method, array('GET', 'POST', 'PUT', 'DELETE', 'JSON')))
$method = 'GET';
if (isset($params['debug_info'])) {
$this->_debug = TRUE;
$this->_debug_info = $params['debug_info'];
unset($params['debug_info']);
}
/**
* Logging
*/
if (isset($params['log'])) {
$this->setLog($params['log']);
unset($params['log']);
}
if (isset($params['log_once'])) {
$this->setLogOnce($params['log_once']);
unset($params['log_once']);
}
if (isset($params['log_path'])) {
$this->setLogPath($params['log_path']);
unset($params['log_path']);
}
// Extra Error
if (isset($params['extra_err'])) {
$this->setExtraError($params['extra_err']);
unset($params['extra_err']);
}
/**
* Fallback logging when debug is true
*/
if ($this->_debug) {
$this->setLogOnce(true);
}
return (json_decode($this->sendRequest($object, $params, $method)));
}
/**
* Send Request
*
* Send the request to the Mailjet API server and get back the result
* Basically, setup and execute the curl process.
* Cache management added
*
* @access private
* @uses MailjetApi::$_info
* @uses MailjetApi::$_debug
* @uses MailjetApi::$_buffer
* @uses MailjetApi::$_method
* @uses MailjetApi::$_apiKey
* @uses MailjetApi::$_secretKey
* @uses MailjetApi::$_curl_handle
* @uses MailjetApi::buildURL() to build the full Url for the request and update the list of parameters accordingly
* @param string $object Object or collection of resources you want to access
* @param array $params Additional parameters for the request
* @param string $method POST: Create a resource
* GET: Read one or multiple resources
* PUT: Update one or multiple resources
* DELETE: Delete one or multiple resources
*
* @return string the result of the request
*/
private function sendRequest($object, $params, $method)
{
// Log if this is a JSON call with an ID inside params
$is_json_put = (isset($params['ID']) && !empty($params['ID']));
list($url, $params) = $this->buildURL($object, $params, $method);
if ($this->_cache != 0 && $method == 'GET' && !$this->_akid) {
$file = $method.'.'.$object.'.'.hash('md5', $this->_apiKey.http_build_query($params, '', '')).'.cache';
}
if(is_null($this->_curl_handle))
$this->_curl_handle = curl_init();
curl_setopt($this->_curl_handle, CURLOPT_URL, $url);
curl_setopt($this->_curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->_curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($this->_curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($this->_curl_handle, CURLOPT_USERPWD, $this->_apiKey.':'.$this->_secretKey);
curl_setopt($this->_curl_handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($this->_curl_handle, CURLOPT_USERAGENT, 'joomla-3.0');
switch ($method) {
case 'GET' :
curl_setopt($this->_curl_handle, CURLOPT_HTTPGET, TRUE);
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, NULL);
break;
case 'POST':
if(isset($params['Action']) && $params['Action']=='Add'){
curl_setopt($this->_curl_handle, CURLOPT_POST, count($params));
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($this->_curl_handle, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
}
else{
curl_setopt($this->_curl_handle, CURLOPT_POST, count($params));
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, $this->curl_build_query($params));
}
break;
case 'PUT':
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, $this->curl_build_query($params));
break;
case 'JSON':
if($is_json_put)
curl_setopt($this->_curl_handle, CURLOPT_CUSTOMREQUEST, "PUT");
else
curl_setopt($this->_curl_handle, CURLOPT_CUSTOMREQUEST, "POST");
$params = json_encode($params);
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, $params);
curl_setopt($this->_curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($this->_curl_handle, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($params))
);
break;
}
$buffer = curl_exec($this->_curl_handle);
$this->_info = curl_getinfo($this->_curl_handle);
$this->_response_code = $this->_info['http_code'];
curl_close($this->_curl_handle);
$this->_curl_handle = null;
if ($this->_debug) {
$this->_buffer = $buffer;
$this->_method = $method;
$this->_debug = FALSE;
}
if ($this->_cache != 0 && $method == 'GET' && !$this->_akid) {
$data = array('timestamp' => time(), 'result' => $buffer, 'http_code' => $this->_info['http_code']);
}
if( $this->getExtraError() ){
$this->getExtraErr( $buffer );
$this->setExtraError( false );
}
if ($this->logAllowed() && ($this->getLog() || $this->getLogOnce())) {
if ($this->_info) {
$moreInfo = print_r(array(
'content_type' => $this->_info['content_type'],
'http_code' => $this->_info['http_code'],
'total_time' => $this->_info['total_time'],
), true);
$moreInfo = substr($moreInfo, 6);
} else {
$moreInfo = 'none';
}
$date = DateTime::createFromFormat('U.u', microtime(true));
if (is_array($params)) {
$jsonParams = json_encode($params);
} else {
$jsonParams = $params;
}
$logLines = array();
$logLines[] = '';
$logLines[] = $date->format('Y-m-d H:i:s.u')." > {$object} :: {$method}";
$logLines[] = '';
$logLines[] = $this->_info['url'];
$logLines[] = '';
$logLines[] = "Request";
$logLines[] = $jsonParams;
$logLines[] = '';
$logLines[] = "Response";
$logLines[] = $buffer;
$logLines[] = '';
$logLines[] = 'Info';
$logLines[] = $moreInfo;
$logLines[] = '';
$logLines[] = str_repeat("=", 100);
$logLines[] = '';
$logText = implode(PHP_EOL, $logLines);
file_put_contents($this->getLogPath(), $logText, FILE_APPEND);
$this->setLogOnce(false);
}
return $buffer;
}
/**
* Build the full Url for the request and update the parameters if needed
*
* @access private
* @uses MailjetApi::$_apiUrl
* @param string $object Object or collection of resources you want to access
* @param array $params Additional parameters for the request
* @param string $method POST: Create a resource
* GET: Read one or multiple resources
* PUT: Update one or multiple resources
* DELETE: Delete one or multiple resources
*
* @return array Full built Url for the request and new params
*/
private function buildURL($object, $params, $method = 'GET')
{
$url = $this->_apiUrl.$object;
if (isset($params['ID'])) {
$url .= '/'.$params['ID'];
unset($params['ID']);
}
$this->_akid = array_key_exists('akid', $params);
if ($method == 'GET')
$url .= '?'.http_build_query($params, '', '&');
elseif ($method == 'PUT' || $method == 'POST' || $method == 'DELETE' || $method == 'JSON') {
$tocheck = array('format', 'style', 'countrecords', 'recurse', 'akid', 'DuplicateFrom');
$query = array();
foreach ($params as $key => $value)
if (in_array($key, $tocheck)) {
$query[$key] = $value;
unset($params[$key]);
}
if(count($query))
$url .= '?'.http_build_query($query, '', '&');
}
return (array($url, $params));
}
/**
* Build query for cURL
* Beware of the Boolean !
*
* @access private
* @param array $params Post parameters for the request
*
* @return string URL-encoded query string from the associative array provided
*/
private function curl_build_query($params)
{
foreach($params as $key => $value) {
if($value === TRUE)
$value = 'true';
elseif($value === FALSE)
$value = 'false';
}
/*array_walk($params, function(&$value, &$key) {
if ($value === TRUE) {
$value = 'true';
} elseif ($value === FALSE) {
$value = 'false';
}
});*/
return (http_build_query($params, '', '&'));
}
/**
* Get the last HTTP code retrieved by cURL
*
* Warning : Information returned by this function is kept.
* So, if you call it again, the previous info is returned.
*
* @access public
* @uses MailjetApi::$_info
*
* @return integer last HTTP code retrieved by cURL or 0 if not set
*/
public function getLastHTTPCode()
{
if (isset($this->_info['http_code']))
return ($this->_info['http_code']);
return (0);
}
/**
* Set some info if the object came from the cache
*
* @access private
* @uses MailjetApi::$_info
* @uses MailjetApi::$_buffer
* @uses MailjetApi::$_method
* @uses MailjetApi::$_debug_info
*/
private function setCacheDebugInfo($method, $url, $data)
{
$this->_debug_info .= ' /* LAST CACHED AT '.date('Y/m/d H:i:s', $data['timestamp']).' - UPDATING EVERY '.$this->_cache.'s */';
$this->_buffer = $data['result'];
$this->_method = $method;
$this->_info = array();
$this->_info['url'] = $url;
$this->_info['http_code'] = $data['http_code'];
$this->_info['total_time'] = $this->_info['pretransfer_time'] = 0;
$this->_debug = FALSE;
}
/**
* Get some info for debugging purpose
*
* Warning : Information returned by this function is kept.
* So, if you call it again, the previous info is returned.
* To update this array, you need to add the key 'debug_info'
* to the list of parameters. You can specified a value to
* identify the returned array.
*
* @access public
* @uses MailjetApi::$_info
* @uses MailjetApi::$_method
* @uses MailjetApi::$_debug_info
*
* @return array with some debug info
*/
public function getDebugInfo()
{
$status_code = array (
200 => 'OK - Everything went fine.',
201 => 'OK - Created : The POST request was successfully executed.',
204 => 'OK - No Content : The Delete request was successful.',
304 => 'OK - Not Modified : The PUT request didn’t affect any record.',
400 => 'KO - Bad Request : Please check the parameters.',
401 => 'KO - Unauthorized : A problem occurred with the apiKey/secretKey. You may be not authorized to access the API or your apiKey may have expired.',
403 => 'KO - Forbidden : You are not authorized to call that function.',
404 => 'KO - Not Found : The resource with the specified ID does not exist.',
405 => 'KO - Method not allowed : Attempt to put/post multiple resources in 1 request.',
500 => 'KO - Internal Server Error.',
503 => 'KO - Service unavailable.'
);
if (array_key_exists($this->_info['http_code'], $status_code))
$http_code_text = $status_code[$this->_info['http_code']];
else
$http_code_text = 'KO - Service unavailable.';
$status_message = '';
if ($this->_info['http_code'] >= 400) {
$buffer = json_decode($this->_buffer);
if (!is_null($buffer) && isset($buffer->StatusCode) && isset($buffer->ErrorMessage)) {
$status_message = $buffer->StatusCode.' - '.$buffer->ErrorMessage;
if (isset($buffer->ErrorInfo) && !empty($buffer->ErrorInfo))
$status_message .= ' ('.$buffer->ErrorInfo.')';
}
}
$res = array(
'debug_info' => $this->_debug_info,
'method' => $this->_method,
'url' => $this->_info['url'],
'duration' => $this->_info['total_time'] - $this->_info['pretransfer_time'],
'http_code' => $this->_info['http_code'],
'http_code_text'=> $http_code_text,
'status_message'=> $status_message,
'curl_info' => $this->_info,
'buffer' => $this->_buffer
);
return $res;
}
protected function getExtraErr( &$buffer )
{
$bufferCheck = json_decode($buffer);
if( is_null( $bufferCheck ) )
return;
$buffer = $bufferCheck;
if( $this->_info['http_code'] < 400 )
{
$response = array( (object)array( "ExtraErrCode" => $this->_info['http_code'], "ExtraErrKey" => "", "ExtraErrMsg" => "" ) );
$buffer->ExtraError = $response ;
$buffer = json_encode( $buffer );
return;
}
$internalErrors = array(
'MJ01' => 'Could not determine APIKey', // SERRCouldNotDetermineAPIKey
'MJ02' => 'No persister object found for class: "%s"', // SErrNoPersister
'MJ03' => 'A non-empty value is required', // SErrValueRequired
'MJ04' => 'Value must have at least length %d', // SErrMinLength
'MJ05' => 'Value may have at most length %d', // SErrMaxLength
'MJ06' => 'Value must be larger than or equal to %s', // SErrMinValue
'MJ07' => 'Value must be less than or equal to %s', // SErrMaxValue
'MJ08' => 'Property %s is invalid: %s', // SErrInProperty
'MJ09' => 'Value is not in list of allowed values: (%s)', // SErrValueNotInList
'MJ10' => 'Value must be positive', // SErrPositiveValueRequired
'MJ11' => 'Unknown object type "%s".', // SErrUnknownObject
'MJ12' => 'Cannot save object of type %s', // SerrCannotSaveObjectType
'MJ13' => 'Invalid characters in MD5 hash: "%s"', // SErrInvalidHashCharacters
'MJ14' => 'Invalid length for MD5 hash: %d', // SErrInvalidHashLength
'MJ15' => 'Unknown relation name : "%s"', // SErrUnkownRelation
'MJ16' => 'Class "%s" does not support a unique key.', // SErrNoAlternateKey
'MJ17' => '(%s) Cannot search unique key: unique key value is empty.', // SErrNoAlternateKeyValue
'MJ18' => 'A %s resource with value "%s" for %s already exists.', // SErrDuplicateKey
'MJ19' => 'Setting a value for property "%s" is not allowed', // SErrCannotWriteProperty
'MJ20' => 'Setting a value for properties is not allowed', // SErrCannotWriteProperties
// ContactMetadata
'CM01' => 'Property "%s" already exists', // sERRCMPropertyAlreadyExists
'CM02' => 'Unknown namespace : %s', // SERRCMUnknownNamespace
'CM03' => '"%s" is not a valid integer value for key %s', // SERRCMNotAValidIntegerValueForKey
'CM04' => '"%s" is not a valid bool value for key %s', // SERRCMNotAValidBoolValueForKey
'CM05' => '"%s" is not a valid float value for key %s', // SERRCMNotAValidFloatValue
'CM06' => 'Length of value (%d bytes) exceeds maximum data length (%d bytes) ', // SERRCMLengthOfValueExceedsMaxDataLength
'CM07' => 'Internal error: invalid data type %d', // SERRCMInternalErrorInvalidDataType
'CM08' => '"%s" is not a valid datatype' // SERRCMNotAValidDataType
);
$response = array();
// We expect here $this->_info['http_code'] to be >= 400
if ( isset($buffer->StatusCode) ) {
if( ( isset($buffer->ErrorInfo) && !empty($buffer->ErrorInfo) ) || ( isset($buffer->ErrorMessage) && !empty($buffer->ErrorMessage) ) )
{
$comeFromString = false;
if( !empty( $buffer->ErrorInfo ) )
{
$info = json_decode( $buffer->ErrorInfo );
if( empty( $info) ) // message is type=string
{
$comeFromString = true ;
$errInfos = array( (object)$buffer->ErrorInfo );
}else{
$errInfos = $info;
}
}else{ // ( !empty( $buffer->ErrorMessage ) )
$info = json_decode( $buffer->ErrorMessage );
if( empty( $info ) ) // message is type=string
{
$comeFromString = true ;
$errInfos = array( (object)$buffer->ErrorMessage );
}else{
$errInfos = $info;
}
}
/**
* Default response. Most of the ErrorInfo/ErrorMessage will come as they are - without specific err code in front!
* We keep the ExtraErrors = ErrorInfo/ErrorMessage.
*
* In the feature all the responses will consist these special codes.
* When this happen (!!! ToDo !!!) -> we have to override coming StatusCode and ErrorInfo with parsed error results. And remove this ExtraError from the buffer
* $internalErrors array and preg_match -> should be removed. We should catch the first 4 symbols from the string (this will be StatusCode),
* all the remaining string will be ErrorInfo
*/
$errCodes = array_keys( $internalErrors );
$regexp = '/^(' . implode( '|',array_values( $errCodes ) ).')/i';
foreach( $errInfos as $errInfoObj )
{
foreach( $errInfoObj as $key => $errInfo )
{
$tempResp = array();
$tempResp["ExtraErrCode"] = $buffer->StatusCode;
$tempResp["ExtraErrKey"] = "";
$tempResp["ExtraErrMsg"] = $errInfo;
preg_match($regexp, $errInfo, $matches);
if( !empty( $matches ))
{
$tempResp["ExtraErrCode"] = $matches[1];
if( $comeFromString )
$tempResp["ExtraErrKey"] = '';
else
$tempResp["ExtraErrKey"] = $key;
$tempResp["ExtraErrMsg"] = $internalErrors[$matches[1]];
}
$response[] = $tempResp ;
}
}
}
}
// Check if is $response empty !
if( empty( $response ) )
{
$response = array( (object)array( "ExtraErrCode" => $this->_info['http_code'], "ExtraErrKey" => "", "ExtraErrMsg" => "" ) );
}
$buffer->ExtraError = $response ;
$buffer = json_encode( $buffer );
}
}PK Ǿ!]�NH� lib/api/mailjet-api-v1.phpnu &1i� <?php
/**
* Mailjet Public API
*
* @package API v0.1
* @author Mailjet
* @link http://api.mailjet.com/
*
*/
class Mailjet_Api_V1
{
var $version = '0.1';
// Choose your weapon : php, json, xml, serialize, html, csv
var $output = 'json';
// Connect thru https protocol
var $secure = false;
// Mode debug ? 0 none / 1 errors only / 2 all
var $debug = 0;
// Edit with your Mailjet Infos
var $apiKey = '';
var $secretKey = '';
// Constructor function
public function __construct($apiKey = false, $secretKey = false)
{
if ($apiKey)
$this->apiKey = $apiKey;
if ($secretKey)
$this->secretKey = $secretKey;
$this->apiUrl = (($this->secure) ? 'https' : 'http') . '://api.mailjet.com/' . $this->version . '';
}
public function __call($method, $args)
{
// params
$params = (sizeof($args) > 0) ? $args[0] : array();
// request method
$request = isset($params["method"]) ? strtoupper($params["method"]) : 'GET';
// unset useless params
if (isset($params["method"]))
unset($params["method"]);
// Make request
$result = $this->sendRequest($method, $params, $request);
// Return result
$return = ($result === true) ? $this->_response : false;
if ($this->debug == 2 || ( $this->debug == 1 && $return == false))
$this->debug();
return $return;
}
public function requestUrlBuilder($method,$params=array(),$request)
{
$query_string = array('output' => 'output=' . $this->output);
foreach ($params as $key => $value)
{
if ($request == 'GET' || in_array($key, array('apikey', 'output')))
$query_string[$key] = $key . '=' . urlencode($value);
if ($key == 'output')
$this->output = $value;
}
$this->call_url = $this->apiUrl . '/' . $method . '/?' . join('&', $query_string);
return $this->call_url;
}
public function sendRequest($method = false, $params = array(), $request = 'GET')
{
// Method
$this->_method = $method;
$this->_request = $request;
// Build request URL
$url = $this->requestUrlBuilder($method, $params, $request);
if (!in_array('curl', get_loaded_extensions()))
die('Error: You must have cURL extension enabled !');
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl_handle, CURLOPT_USERPWD, $this->apiKey . ':' . $this->secretKey);
curl_setopt($curl_handle, CURLOPT_VERBOSE, true);
curl_setopt($curl_handle, CURLINFO_HEADER_OUT, true);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'joomla-1.0');
$this->_request_post = false;
if ($request == 'POST')
{
curl_setopt($curl_handle, CURLOPT_POST, count($params));
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query($params));
$this->_request_post = $params;
}
$buffer = curl_exec($curl_handle);
if ($this->debug > 2)
{
$this->debug();
// var_dump($buffer);
// var_dump(curl_getinfo($curl_handle));
}
// Response code
$this->_response_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
// Close curl process
curl_close($curl_handle);
// RESPONSE
$this->_response = ($this->output == 'json') ? json_decode($buffer) : $buffer;
return ($this->_response_code == 200) ? true : false;
}
public function debug()
{
echo '<style type="text/css">';
echo '
#debugger {width: 100%; font-family: arial;}
#debugger table {padding: 0; margin: 0 0 20px; width: 100%; font-size: 11px; text-align: left;border-collapse: collapse;}
#debugger th, #debugger td {padding: 2px 4px;}
#debugger tr.h {background: #999; color: #fff;}
#debugger tr.Success {background:#90c306; color: #fff;}
#debugger tr.Error {background:#c30029 ; color: #fff;}
#debugger tr.Not-modified {background:orange ; color: #fff;}
#debugger th {width: 20%; vertical-align:top; padding-bottom: 8px;}
';
echo '</style>';
echo '<div id="debugger">';
if (isset($this->_response_code))
{
if ($this->_response_code == 200)
{
echo '<table>';
echo '<tr class="Success"><th>Success</th><td></td></tr>';
echo '<tr><th>Status code</th><td>' . $this->_response_code . '</td></tr>';
if (isset($this->_response))
echo '<tr><th>Response</th><td><pre>' . utf8_decode(print_r($this->_response, 1)) . '</pre></td></tr>';
echo '</table>';
}
elseif($this->_response_code == 304)
{
echo '<table>';
echo '<tr class="Not-modified"><th>Error</th><td></td></tr>';
echo '<tr><th>Error no</th><td>' . $this->_response_code . '</td></tr>';
echo '<tr><th>Message</th><td>Not Modified</td></tr>';
echo '</table>';
}
else
{
echo '<table>';
echo '<tr class="Error"><th>Error</th><td></td></tr>';
echo '<tr><th>Error no</th><td>' . $this->_response_code . '</td></tr>';
if (isset($this->_response))
{
if (is_array($this->_response) || is_object($this->_response))
echo '<tr><th>Status</th><td><pre>' . print_r($this->_response, true) . '</pre></td></tr>';
else
echo '<tr><th>Status</th><td><pre>' . $this->_response . '</pre></td></tr>';
}
}
echo '</table>';
}
$call_url = parse_url($this->call_url);
echo '<table>';
echo '<tr class="h"><th>API config</th><td></td></tr>';
echo '<tr><th>Protocole</th><td>' . $call_url['scheme'] . '</td></tr>';
echo '<tr><th>Host</th><td>' . $call_url['host'] . '</td></tr>';
echo '<tr><th>Version</th><td>' . $this->version . '</td></tr>';
echo '</table>';
echo '<table>';
echo '<tr class="h"><th>Call infos</th><td></td></tr>';
echo '<tr><th>Method</th><td>' . $this->_method . '</td></tr>';
echo '<tr><th>Request type</th><td>' . $this->_request . '</td></tr>';
echo '<tr><th>Get Arguments</th><td>';
$args = explode("&", $call_url['query']);
foreach ($args as $arg)
{
$arg = explode('=', $arg);
echo ''.$arg[0].' = <span style="color:#ff6e56;">' . $arg[1] . '</span><br/>';
}
echo '</td></tr>';
if ($this->_request_post)
{
echo '<tr><th>Post Arguments</th><td>';
foreach ($this->_request_post as $k => $v)
echo $k.' = <span style="color:#ff6e56;">' . $v . '</span><br/>';
echo '</td></tr>';
}
echo '<tr><th>Call url</th><td>' . $this->call_url . '</td></tr>';
echo '</table>';
echo '</div>';
}
}PK Ǿ!]� lib/Auth.phpnu &1i� <?php
defined('_JEXEC') or die('Restricted access');
/**
* @author Mailjet SAS
*
* @copyright Copyright (C) 2014 Mailjet SAS.
* @license GNU General Public License version 2 or later; see LICENSE
*/
class Auth
{
/**
*
* @var String
*/
private $_dbData;
/**
*
* @var String
*/
private $_apiKey;
/**
*
* @var String
*/
private $_apiSecret;
/**
*
* @var String
*/
private $_token;
/**
*
* @var String
*/
private $_apiUrl;
/**
*
* @var String
*/
private $_apiVersion;
/**
*
* @var Boolean
*/
private $_enable = false;
/**
*
* @var String
*/
private $_testAddress = 'test@emailaddress';
/**
*
*/
public function __construct()
{
$this->_initData();
}
/**
*
* @return Auth
*/
protected function _initData()
{
$this->_dbData = realpath(__DIR__.'/../db/data');
touch($this->_dbData);
$data = null;
$content = trim(file_get_contents($this->_dbData));
if ($content) {
$data = json_decode($content);
}
if (!$data) {
$this->saveData();
}
if (isset($data->apiKey) && $data->apiKey) {
$this->setApiKey($data->apiKey);
}
if (isset($data->apiSecret) && $data->apiSecret) {
$this->setApiSecret($data->apiSecret);
}
if (isset($data->token) && $data->token) {
$this->setToken($data->token);
}
if (isset($data->apiUrl) && $data->apiUrl) {
$this->setApiUrl($data->apiUrl);
}
if (isset($data->apiVersion) && $data->apiVersion) {
$this->setApiVersion($data->apiVersion);
}
if(!empty($data->enable)) {
$this->setEnable($data->enable);
}
if(!empty($data->test_address)) {
$this->setTestAddress($data->test_address);
}
return $this;
}
/**
*
* @return Auth
*/
public function saveData()
{
$data = array(
'apiKey' => $this->getApiKey(),
'apiSecret' => $this->getApiSecret(),
'token' => $this->getToken(),
'apiUrl' => $this->getApiUrl(),
'apiVersion' => $this->getApiVersion(),
'enable' => $this->getEnable(),
'test_address' => $this->getTestAddress()
);
file_put_contents($this->_dbData, json_encode($data));
$mailjetConfig = realpath(__DIR__.'/../../config.php');
$dataConf = '<?php
class JMailjetConfig {
public $bak_mailer = "smtp";
public $bak_smtpauth = "1";
public $bak_smtpuser = "your API key";
public $bak_smtppass = "your API secret";
public $bak_smtphost = "'.(($this->getApiUrl())?$this->getApiUrl():"in-v3.mailjet.com").'";
public $bak_smtpsecure = "tls";
public $bak_smtpport = "587";
public $test = "";
public $test_address = "'.$this->getTestAddress().'";
public $enable = "'.$this->getEnable().'";
public $username = "'.(($this->getApiKey())?$this->getApiKey():"your API key").'";
public $password = "'.(($this->getApiSecret())?$this->getApiSecret():"your API secret").'";
public $host = "'.(($this->getApiUrl())?$this->getApiUrl():"in-v3.mailjet.com").'";
public $secure = "tls";
public $port = "587";
}';
file_put_contents($mailjetConfig, $dataConf);
return $this;
}
/**
*
* @return Auth
*/
public function deleteData()
{
$content = trim(file_get_contents($this->_dbData));
$data = array(
'apiKey' => null,
'apiSecret' => null,
'token' => null,
'apiUrl' => null,
'apiVersion' => null,
'enable' => null,
'test_address' => null,
);
file_put_contents($this->_dbData, json_encode($data));
$this->_apiKey = null;
$this->_apiSecret = null;
$this->_token = null;
$this->_apiUrl = null;
$this->_apiVersion = null;
$this->_enable = null;
$this->_testAddress = null;
return $this;
}
/**
*
* @param String $apiKey
* @return Auth
*/
public function setApiKey($apiKey)
{
$this->_apiKey = $apiKey;
return $this;
}
/**
*
* @return String
*/
public function getApiKey()
{
return $this->_apiKey;
}
/**
*
* @param String $apiSecret
* @return Auth
*/
public function setApiSecret($apiSecret)
{
$this->_apiSecret = $apiSecret;
return $this;
}
/**
*
* @return String
*/
public function getApiSecret()
{
return $this->_apiSecret;
}
/**
*
* @param String $token
* @return Auth
*/
public function setToken($token)
{
$this->_token = $token;
return $this;
}
/**
*
* @return String
*/
public function getToken()
{
if (($this->_token == NULL || strlen($this->_token) == 0) && $this->getApiKey() && $this->getApiSecret())
$this->generateToken();
return $this->_token;
}
/**
*
* @return Boolean
*/
public function getEnable()
{
return $this->_enable;
}
/**
*
* @param Boolean
* @return Boolean
*/
public function setEnable($val)
{
return $this->_enable = $val;
}
/**
*
* @return String
*/
public function getTestAddress()
{
return $this->_testAddress;
}
/**
*
* @param String
* @return String
*/
public function setTestAddress($val)
{
return $this->_testAddress = $val;
}
/**
*
* @param String $apiUrl
* @return Auth
*/
public function setApiUrl($apiUrl)
{
$this->_apiUrl = $apiUrl;
return $this;
}
/**
*
* @return String
*/
public function getApiUrl()
{
return $this->_apiUrl;
}
/**
*
* @param String $apiVersion
* @return Auth
*/
public function setApiVersion($apiVersion)
{
$this->_apiVersion = $apiVersion;
return $this;
}
/**
*
* @return String
*/
public function getApiVersion()
{
return $this->_apiVersion;
}
/**
*
* @return boolean
*/
public function haveToken()
{
return (boolean) $this->getToken();
}
/**
*
* @return boolean
*/
public function canGenerateToken()
{
return $this->getApiKey() && $this->getApiSecret();
}
/**
*
* @return boolean
*/
public function generateToken()
{
if (!$this->canGenerateToken()) {
return false;
}
$mj = new Mailjet_Api($this->getApiKey(), $this->getApiSecret());
$this->setApiUrl($mj->apiUrl);
$this->setApiVersion($mj->version);
$response = $mj->getAuthToken(array(
'APIKey' => $this->getApiKey(),
'SecretKey' => $this->getApiSecret()
));
// Log the response
$this->_log($mj);
// Check if the response is correct
if (!isset($response->Status) || (isset($response->Status) && $response->Status != 'ERROR')) {
$this->setToken($response);
$this->saveData();
}
return true;
}
public function __destruct()
{
$this->saveData();
}
private function _log($response)
{
$log = realpath(__DIR__.'/../tmp/log');
touch($log);
$delimiter = str_repeat('=', 100);
$content = file_get_contents($log);
$prepend = '';
$prepend .= $delimiter;
$prepend .= PHP_EOL;
$prepend .= date('Y-m-d H:i:s');
$prepend .= PHP_EOL;
$prepend .= 'RESPONSE';
$prepend .= PHP_EOL;
$prepend .= print_r($response, true);
$prepend .= PHP_EOL;
$content = $prepend.$content;
file_put_contents($log, $content);
}
}
?>PK Ǿ!]��֠< < hook.phpnu &1i� <?php
/**
* @author Mailjet SAS
*
* @copyright Copyright (C) 2014 Mailjet SAS.
* @license GNU General Public License version 2 or later; see LICENSE
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
require_once realpath(__DIR__.'/lib/Auth.php');
require_once realpath(__DIR__.'/lib/mailjet-api-strategy.php');
$auth = new Auth();
$log = realpath(__DIR__.'/tmp/log');
touch($log);
$delimiter = str_repeat('=', 100);
$content = file_get_contents($log);
$prepend = '';
$prepend .= $delimiter;
$prepend .= PHP_EOL;
$prepend .= date('Y-m-d H:i:s');
$prepend .= PHP_EOL;
$prepend .= 'POST';
$prepend .= PHP_EOL;
$prepend .= print_r($_POST, true);
$prepend .= PHP_EOL;
$prepend .= 'GET';
$prepend .= PHP_EOL;
$prepend .= print_r($_GET, true);
if (isset($_POST['data'])) {
$data = (object) $_POST['data'];
} else if (isset($_POST['mailjet'])) {
$mailjet = json_decode($_POST['mailjet']);
$data = $mailjet->data;
}
if (isset($data->next_step_url) && $data->next_step_url) {
//we have api key and secret but no token so generate it
if (
isset($data->apikey)
&& $data->apikey
&& isset($data->secretkey)
&& $data->secretkey
&& !$auth->haveToken()
) {
$auth->setApiKey($data->apikey);
$auth->setApiSecret($data->secretkey);
$auth->generateToken();
$auth->saveData();
}
$response = array(
"code" => 1,
"continue" => true,
"continue_address" => $data->next_step_url,
);
} else {
$response = array(
"code" => 0,
"continue" => false,
"exit_url" => 'http://prestashop.com/exit.php',
);
}
$json = json_encode($response);
$prepend .= PHP_EOL;
$prepend .= 'RESPONSE';
$prepend .= PHP_EOL;
$prepend .= $json;
$prepend .= PHP_EOL;
$prepend .= $delimiter;
$prepend .= PHP_EOL;
$content = $prepend.$content;
file_put_contents($log, $content);
echo $json;PK Ǿ!]��l�� �
config.phpnu &1i� <?php
/**
* @author Mailjet SAS
*
* @copyright Copyright (C) 2014 Mailjet SAS.
* @license GNU General Public License version 2 or later; see LICENSE
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$myHookUrl = JURI::base().'components/com_mailjet/lib/hook.php';
$myExitUrl = JURI::base().'components/com_mailjet/lib/exit.php';
$resellerName = 'test';PK Ǿ!]T� �� �� tmp/lognu &1i� ====================================================================================================
2014-09-24 18:22:51
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V1 Object
(
[version] => 0.1
[output] => json
[secure] =>
[debug] => 0
[apiKey] => 6363e9d3b0fbcc689c98e18a1a0ba9b5
[secretKey] => ea3818da6ef29051a081297d4e4ea6cb
[apiUrl] => http://api.mailjet.com/0.1
[_method] => listsAll
[_request] => GET
[call_url] => http://api.mailjet.com/0.1/listsAll/?output=json&limit=1
[_request_post] =>
[_response_code] => 200
[_response] => stdClass Object
(
[lists] => Array
(
[0] => stdClass Object
(
[id] => 830045
[name] => bugise2794a59
[label] => Bug issue 562
[created_at] => 1402918673
[subscribers] => 201
[sent] => 0
[open] => 0
[click] => 0
[bounce] => 0
[blocked] => 400
[spam] => 0
[unsub] => 0
[last_activity] => 1403006589
[handled] => 1
)
)
[status] => OK
)
)
[version] => 0.1
[apiUrl] => in.mailjet.com
)
====================================================================================================
2014-09-24 18:02:39
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V1 Object
(
[version] => 0.1
[output] => json
[secure] =>
[debug] => 0
[apiKey] => 6363e9d3b0fbcc689c98e18a1a0ba9b5
[secretKey] => ea3818da6ef29051a081297d4e4ea6cb
[apiUrl] => http://api.mailjet.com/0.1
[_method] => listsAll
[_request] => GET
[call_url] => http://api.mailjet.com/0.1/listsAll/?output=json&limit=1
[_request_post] =>
[_response_code] => 200
[_response] => stdClass Object
(
[lists] => Array
(
[0] => stdClass Object
(
[id] => 830045
[name] => bugise2794a59
[label] => Bug issue 562
[created_at] => 1402918673
[subscribers] => 201
[sent] => 0
[open] => 0
[click] => 0
[bounce] => 0
[blocked] => 400
[spam] => 0
[unsub] => 0
[last_activity] => 1403006589
[handled] => 1
)
)
[status] => OK
)
)
[version] => 0.1
[apiUrl] => in.mailjet.com
)
====================================================================================================
2014-09-24 18:02:06
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V3 Object
(
[_apiKey:Mailjet_Api_V3:private] => 7ee8e423df320c5c3ecb314ad45c0b19
[_secretKey:Mailjet_Api_V3:private] => 112f3d6bd2e3059db345a35cd2dfe5bb
[_cache:Mailjet_Api_V3:private] => 0
[_apiUrl:Mailjet_Api_V3:private] => http://api.mailjet.com/v3/REST/
[_version:Mailjet_Api_V3:private] => REST
[_debug:Mailjet_Api_V3:private] =>
[_debug_info:Mailjet_Api_V3:private] =>
[_buffer:Mailjet_Api_V3:private] =>
[_method:Mailjet_Api_V3:private] =>
[_info:Mailjet_Api_V3:private] => Array
(
[url] => http://api.mailjet.com/v3/REST/apitoken
[content_type] => text/html; charset=utf-8
[http_code] => 201
[header_size] => 184
[request_size] => 405
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.075868
[namelookup_time] => 3.1E-5
[connect_time] => 0.031974
[pretransfer_time] => 0.032039
[size_upload] => 153
[size_download] => 643
[speed_download] => 8475
[speed_upload] => 2016
[download_content_length] => 643
[upload_content_length] => 153
[starttransfer_time] => 0.075834
[redirect_time] => 0
[certinfo] => Array
(
)
[primary_ip] => 5.135.120.255
[primary_port] => 80
[local_ip] => 193.107.71.62
[local_port] => 47087
[redirect_url] =>
)
[_curl_handle:Mailjet_Api_V3:private] =>
[_log_allowed:protected] =>
[_log:protected] =>
[_log_once:protected] => 1
[_extra_err:protected] =>
[_log_path:protected] =>
[_akid] =>
[_response_code] => 201
)
[version] =>
[apiUrl] => in-v3.mailjet.com
)
====================================================================================================
2014-09-24 17:39:54
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V1 Object
(
[version] => 0.1
[output] => json
[secure] =>
[debug] => 0
[apiKey] => 709aa262a03f2279127672eadd59dc50
[secretKey] => bbd975cfe881a7cd349726049b2b022d
[apiUrl] => http://api.mailjet.com/0.1
[_method] => listsAll
[_request] => GET
[call_url] => http://api.mailjet.com/0.1/listsAll/?output=json&limit=1
[_request_post] =>
[_response_code] => 200
[_response] => stdClass Object
(
[lists] => Array
(
[0] => stdClass Object
(
[id] => 833189
[name] => test9132f737
[label] => Test
[created_at] => 1403004329
[subscribers] => 99
[sent] => 0
[open] => 0
[click] => 0
[bounce] => 0
[blocked] => 0
[spam] => 0
[unsub] => 0
[last_activity] =>
[handled] => 1
)
)
[status] => OK
)
)
[version] => 0.1
[apiUrl] => in.mailjet.com
)
====================================================================================================
2014-09-24 17:26:25
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V1 Object
(
[version] => 0.1
[output] => json
[secure] =>
[debug] => 0
[apiKey] => 6363e9d3b0fbcc689c98e18a1a0ba9b5
[secretKey] => ea3818da6ef29051a081297d4e4ea6cb
[apiUrl] => http://api.mailjet.com/0.1
[_method] => listsAll
[_request] => GET
[call_url] => http://api.mailjet.com/0.1/listsAll/?output=json&limit=1
[_request_post] =>
[_response_code] => 200
[_response] => stdClass Object
(
[lists] => Array
(
[0] => stdClass Object
(
[id] => 830045
[name] => bugise2794a59
[label] => Bug issue 562
[created_at] => 1402918673
[subscribers] => 201
[sent] => 0
[open] => 0
[click] => 0
[bounce] => 0
[blocked] => 400
[spam] => 0
[unsub] => 0
[last_activity] => 1403006589
[handled] => 1
)
)
[status] => OK
)
)
[version] => 0.1
[apiUrl] => in.mailjet.com
)
====================================================================================================
2014-09-24 17:26:09
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V1 Object
(
[version] => 0.1
[output] => json
[secure] =>
[debug] => 0
[apiKey] => 709aa262a03f2279127672eadd59dc50
[secretKey] => bbd975cfe881a7cd349726049b2b022d
[apiUrl] => http://api.mailjet.com/0.1
[_method] => listsAll
[_request] => GET
[call_url] => http://api.mailjet.com/0.1/listsAll/?output=json&limit=1
[_request_post] =>
[_response_code] => 200
[_response] => stdClass Object
(
[lists] => Array
(
[0] => stdClass Object
(
[id] => 833189
[name] => test9132f737
[label] => Test
[created_at] => 1403004329
[subscribers] => 99
[sent] => 0
[open] => 0
[click] => 0
[bounce] => 0
[blocked] => 0
[spam] => 0
[unsub] => 0
[last_activity] =>
[handled] => 1
)
)
[status] => OK
)
)
[version] => 0.1
[apiUrl] => in.mailjet.com
)
====================================================================================================
2014-09-24 17:25:55
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V1 Object
(
[version] => 0.1
[output] => json
[secure] =>
[debug] => 0
[apiKey] => 709aa262a03f2279127672eadd59dc50
[secretKey] => bbd975cfe881a7cd349726049b2b022d
[apiUrl] => http://api.mailjet.com/0.1
[_method] => listsAll
[_request] => GET
[call_url] => http://api.mailjet.com/0.1/listsAll/?output=json&limit=1
[_request_post] =>
[_response_code] => 200
[_response] => stdClass Object
(
[lists] => Array
(
[0] => stdClass Object
(
[id] => 833189
[name] => test9132f737
[label] => Test
[created_at] => 1403004329
[subscribers] => 99
[sent] => 0
[open] => 0
[click] => 0
[bounce] => 0
[blocked] => 0
[spam] => 0
[unsub] => 0
[last_activity] =>
[handled] => 1
)
)
[status] => OK
)
)
[version] => 0.1
[apiUrl] => in.mailjet.com
)
====================================================================================================
2014-09-24 16:34:26
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V3 Object
(
[_apiKey:Mailjet_Api_V3:private] => 7ee8e423df320c5c3ecb314ad45c0b19
[_secretKey:Mailjet_Api_V3:private] => 112f3d6bd2e3059db345a35cd2dfe5bb
[_cache:Mailjet_Api_V3:private] => 0
[_apiUrl:Mailjet_Api_V3:private] => http://api.mailjet.com/v3/REST/
[_version:Mailjet_Api_V3:private] => REST
[_debug:Mailjet_Api_V3:private] =>
[_debug_info:Mailjet_Api_V3:private] =>
[_buffer:Mailjet_Api_V3:private] =>
[_method:Mailjet_Api_V3:private] =>
[_info:Mailjet_Api_V3:private] => Array
(
[url] => http://api.mailjet.com/v3/REST/apitoken
[content_type] => text/html; charset=utf-8
[http_code] => 201
[header_size] => 184
[request_size] => 405
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.0752
[namelookup_time] => 3.5E-5
[connect_time] => 0.03224
[pretransfer_time] => 0.03231
[size_upload] => 153
[size_download] => 643
[speed_download] => 8550
[speed_upload] => 2034
[download_content_length] => 643
[upload_content_length] => 153
[starttransfer_time] => 0.075164
[redirect_time] => 0
[certinfo] => Array
(
)
[primary_ip] => 5.135.120.255
[primary_port] => 80
[local_ip] => 193.107.71.62
[local_port] => 41085
[redirect_url] =>
)
[_curl_handle:Mailjet_Api_V3:private] =>
[_log_allowed:protected] =>
[_log:protected] =>
[_log_once:protected] => 1
[_extra_err:protected] =>
[_log_path:protected] =>
[_akid] =>
[_response_code] => 201
)
[version] =>
[apiUrl] => in-v3.mailjet.com
)
====================================================================================================
2014-09-24 16:19:47
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V3 Object
(
[_apiKey:Mailjet_Api_V3:private] => 7ee8e423df320c5c3ecb314ad45c0b19
[_secretKey:Mailjet_Api_V3:private] => 112f3d6bd2e3059db345a35cd2dfe5bb
[_cache:Mailjet_Api_V3:private] => 0
[_apiUrl:Mailjet_Api_V3:private] => http://api.mailjet.com/v3/REST/
[_version:Mailjet_Api_V3:private] => REST
[_debug:Mailjet_Api_V3:private] =>
[_debug_info:Mailjet_Api_V3:private] =>
[_buffer:Mailjet_Api_V3:private] =>
[_method:Mailjet_Api_V3:private] =>
[_info:Mailjet_Api_V3:private] => Array
(
[url] => http://api.mailjet.com/v3/REST/apitoken
[content_type] => text/html; charset=utf-8
[http_code] => 201
[header_size] => 184
[request_size] => 405
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.077033
[namelookup_time] => 3.0E-5
[connect_time] => 0.032484
[pretransfer_time] => 0.032563
[size_upload] => 153
[size_download] => 643
[speed_download] => 8347
[speed_upload] => 1986
[download_content_length] => 643
[upload_content_length] => 153
[starttransfer_time] => 0.076998
[redirect_time] => 0
[certinfo] => Array
(
)
[primary_ip] => 5.135.120.255
[primary_port] => 80
[local_ip] => 193.107.71.62
[local_port] => 39552
[redirect_url] =>
)
[_curl_handle:Mailjet_Api_V3:private] =>
[_log_allowed:protected] =>
[_log:protected] =>
[_log_once:protected] => 1
[_extra_err:protected] =>
[_log_path:protected] =>
[_akid] =>
[_response_code] => 201
)
[version] =>
[apiUrl] => http://api.mailjet.com/v3/REST/
)
====================================================================================================
2014-09-24 14:40:57
RESPONSE
Mailjet_Api Object
(
[context:Mailjet_Api:private] => Mailjet_Api_Strategy_V3 Object
(
[_apiKey:Mailjet_Api_V3:private] => 7ee8e423df320c5c3ecb314ad45c0b19
[_secretKey:Mailjet_Api_V3:private] => 112f3d6bd2e3059db345a35cd2dfe5bb
[_cache:Mailjet_Api_V3:private] => 0
[_apiUrl:Mailjet_Api_V3:private] => http://api.mailjet.com/v3/REST/
[_version:Mailjet_Api_V3:private] => REST
[_debug:Mailjet_Api_V3:private] =>
[_debug_info:Mailjet_Api_V3:private] =>
[_buffer:Mailjet_Api_V3:private] =>
[_method:Mailjet_Api_V3:private] =>
[_info:Mailjet_Api_V3:private] => Array
(
[url] => http://api.mailjet.com/v3/REST/apitoken
[content_type] => text/html; charset=utf-8
[http_code] => 201
[header_size] => 184
[request_size] => 405
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.383548
[namelookup_time] => 2.9E-5
[connect_time] => 0.031834
[pretransfer_time] => 0.031893
[size_upload] => 153
[size_download] => 643
[speed_download] => 1676
[speed_upload] => 398
[download_content_length] => 643
[upload_content_length] => 153
[starttransfer_time] => 0.383513
[redirect_time] => 0
[certinfo] => Array
(
)
[primary_ip] => 5.135.46.177
[primary_port] => 80
[local_ip] => 193.107.71.62
[local_port] => 53699
[redirect_url] =>
)
[_curl_handle:Mailjet_Api_V3:private] =>
[_log_allowed:protected] =>
[_log:protected] =>
[_log_once:protected] => 1
[_extra_err:protected] =>
[_log_path:protected] =>
[_akid] =>
[_response_code] => 201
)
[version] =>
)
====================================================================================================
2014-09-24 13:55:44
RESPONSE
MailjetApi Object
(
[version] => REST
[output] => json
[secure] => 1
[debug] => 0
[apiKey] => 7ee8e423df320c5c3ecb314ad45c0b19
[secretKey] => 112f3d6bd2e3059db345a35cd2dfe5bb
[apiUrl] => https://api.mailjet.com/v3/REST
[_method] => apitoken
[_request] => POST
[call_url] => https://api.mailjet.com/v3/REST/apitoken/?output=json
[_request_post] => Array
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyALT] => 7ee8e423df320c5c3ecb314ad45c0b19
[TokenType] => iframe
[IsActive] => 1
)
[_response_code] => 201
[_response] => stdClass Object
(
[Count] => 1
[Data] => Array
(
[0] => stdClass Object
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyID] => 176517
[CatchedIp] => 172.16.0.11
[CreatedAt] => 2014-09-24T10:55:44Z
[FirstUsedAt] =>
[ID] => 1531814
[IsActive] => 1
[Lang] =>
[LastUsedAt] =>
[SentData] =>
[Timezone] =>
[Token] => E2A2E8E4155971C09461056DB4A2E84A88641773F890CBA6D7E4940EFFE4E0CED009FF388848B7E68C89C340F0A39B7C22273723A53A2CF57E6CEFE34173D2B4970DE3C56F369116250864C4773A02E548A9583A393C896E58453FDEA6BA76E5E0B3DFDC4E6A165CBDE3D5EB1B7702F6559323ABE83B876F9AED3CB4C7BA087
[TokenType] => iframe
[ValidFor] => 0
)
)
[Total] => 1
)
)
====================================================================================================
2014-09-24 13:55:37
RESPONSE
MailjetApi Object
(
[version] => REST
[output] => json
[secure] => 1
[debug] => 0
[apiKey] => 7ee8e423df320c5c3ecb314ad45c0b19
[secretKey] => 112f3d6bd2e3059db345a35cd2dfe5bb
[apiUrl] => https://api.mailjet.com/v3/REST
[_method] => apitoken
[_request] => POST
[call_url] => https://api.mailjet.com/v3/REST/apitoken/?output=json
[_request_post] => Array
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyALT] => 7ee8e423df320c5c3ecb314ad45c0b19
[TokenType] => iframe
[IsActive] => 1
)
[_response_code] => 201
[_response] => stdClass Object
(
[Count] => 1
[Data] => Array
(
[0] => stdClass Object
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyID] => 176517
[CatchedIp] => 172.16.0.11
[CreatedAt] => 2014-09-24T10:55:37Z
[FirstUsedAt] =>
[ID] => 1531813
[IsActive] => 1
[Lang] =>
[LastUsedAt] =>
[SentData] =>
[Timezone] =>
[Token] => FDBE4EAB1136F8B5CE0CC150D2711138180B16C46B51E6C99B873B063038E373C54686FAFABB85D3F6FED5A02B881C4649A017D30787A3D1BDCD2976CE681FAC75E67FDFE2D5D49740453999BC10FB5A92358730733F15ADF153C1CDEADCF5DC8A3A67BC8D8665921DBEBDAED395F1C56AD056332572BB5E6F48B9887D40999
[TokenType] => iframe
[ValidFor] => 0
)
)
[Total] => 1
)
)
====================================================================================================
2014-09-23 18:23:25
RESPONSE
MailjetApi Object
(
[version] => REST
[output] => json
[secure] => 1
[debug] => 0
[apiKey] => 7ee8e423df320c5c3ecb314ad45c0b19
[secretKey] => 112f3d6bd2e3059db345a35cd2dfe5bb
[apiUrl] => https://api.mailjet.com/v3/REST
[_method] => apitoken
[_request] => POST
[call_url] => https://api.mailjet.com/v3/REST/apitoken/?output=json
[_request_post] => Array
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyALT] => 7ee8e423df320c5c3ecb314ad45c0b19
[TokenType] => iframe
[IsActive] => 1
)
[_response_code] => 201
[_response] => stdClass Object
(
[Count] => 1
[Data] => Array
(
[0] => stdClass Object
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyID] => 176517
[CatchedIp] => 172.16.0.11
[CreatedAt] => 2014-09-23T15:23:25Z
[FirstUsedAt] =>
[ID] => 1531747
[IsActive] => 1
[Lang] =>
[LastUsedAt] =>
[SentData] =>
[Timezone] =>
[Token] => 31780227E49D32BD990E9A4B129DF4E8A3CAAA0228336F28CF14D9EC57EB1FCED69A17D464F93374298496DCF7412B28FBFA1ADE1E4262C6DC6B1326B0EAD0ADC3517AC082CCF2F90B25E5006F38C9E50551E9385FA1430A1D2E423E67658245FF5AA97DBDFC3A5671DE309656D002EA6066A1F8A42134A689ADCCC1964165D
[TokenType] => iframe
[ValidFor] => 0
)
)
[Total] => 1
)
)
====================================================================================================
2014-09-23 12:38:08
RESPONSE
MailjetApi Object
(
[version] => REST
[output] => json
[secure] => 1
[debug] => 0
[apiKey] => ff504f5e4e6fb57e9747fc09d7a7c6ff
[secretKey] => fa24b97126e6371d0e2c6c6266bc7f3b
[apiUrl] => https://api.mailjet.com/v3/REST
[_method] => apitoken
[_request] => POST
[call_url] => https://api.mailjet.com/v3/REST/apitoken/?output=json
[_request_post] => Array
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyALT] => ff504f5e4e6fb57e9747fc09d7a7c6ff
[TokenType] => iframe
[IsActive] => 1
)
[_response_code] => 201
[_response] => stdClass Object
(
[Count] => 1
[Data] => Array
(
[0] => stdClass Object
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyID] => 128127
[CatchedIp] => 172.16.0.11
[CreatedAt] => 2014-09-23T09:38:08Z
[FirstUsedAt] =>
[ID] => 1531715
[IsActive] => 1
[Lang] =>
[LastUsedAt] =>
[SentData] =>
[Timezone] =>
[Token] => C7470DD9910D1A4885F2E0669861165180EEE5C18ABBD23956E27E9FC14F356BB495B8D9F9E9636965404732A6675C986982832E4DCA6014B6600364286E0678B5392A1D5E30EDA650F75A8607D28257B023E2166EEACF1868337B1B218C952D997185A5128F5C80F01EA446EE63E6430C1AFFC0F2C4BBA9EA374B2A16ADDF4
[TokenType] => iframe
[ValidFor] => 0
)
)
[Total] => 1
)
)
====================================================================================================
2014-09-23 12:26:27
RESPONSE
MailjetApi Object
(
[version] => REST
[output] => json
[secure] => 1
[debug] => 0
[apiKey] => ff504f5e4e6fb57e9747fc09d7a7c6ff
[secretKey] => fa24b97126e6371d0e2c6c6266bc7f3b
[apiUrl] => https://api.mailjet.com/v3/REST
[_method] => apitoken
[_request] => POST
[call_url] => https://api.mailjet.com/v3/REST/apitoken/?output=json
[_request_post] => Array
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyALT] => ff504f5e4e6fb57e9747fc09d7a7c6ff
[TokenType] => iframe
[IsActive] => 1
)
[_response_code] => 201
[_response] => stdClass Object
(
[Count] => 1
[Data] => Array
(
[0] => stdClass Object
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyID] => 128127
[CatchedIp] => 172.16.0.12
[CreatedAt] => 2014-09-23T09:26:27Z
[FirstUsedAt] =>
[ID] => 1531706
[IsActive] => 1
[Lang] =>
[LastUsedAt] =>
[SentData] =>
[Timezone] =>
[Token] => 255B5D469EF20EECB4C56EF1D5CEADE84E0DC6E4B05AD137B8D7AE91428DDC7547C9C14573B78830BDF1911C4567115EAB21D2E524BFC7E5702601FB9E16DFF7A272A9E5C71D7BDE0B584132FC3ED6AFA6133BFE475B39A157FD2A21B663BDE3EF9D9D3904D32299949CEB4971C68EE337638A4EFAADE99ACE71DCD4F286DE8
[TokenType] => iframe
[ValidFor] => 0
)
)
[Total] => 1
)
)
====================================================================================================
2014-09-19 17:23:02
RESPONSE
MailjetApi Object
(
[version] => REST
[output] => json
[secure] => 1
[debug] => 0
[apiKey] => ff504f5e4e6fb57e9747fc09d7a7c6ff
[secretKey] => fa24b97126e6371d0e2c6c6266bc7f3b
[apiUrl] => https://api.mailjet.com/v3/REST
[_method] => apitoken
[_request] => POST
[call_url] => https://api.mailjet.com/v3/REST/apitoken/?output=json
[_request_post] => Array
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyALT] => ff504f5e4e6fb57e9747fc09d7a7c6ff
[TokenType] => iframe
[IsActive] => 1
)
[_response_code] => 201
[_response] => stdClass Object
(
[Count] => 1
[Data] => Array
(
[0] => stdClass Object
(
[AllowedAccess] => campaigns,contacts,stats,pricing,account,reports
[APIKeyID] => 128127
[CatchedIp] => 172.16.0.12
[CreatedAt] => 2014-09-19T14:23:02Z
[FirstUsedAt] =>
[ID] => 1531571
[IsActive] => 1
[Lang] =>
[LastUsedAt] =>
[SentData] =>
[Timezone] =>
[Token] => FACB508DBC7E98D9D08F66A59B0C560CFB78AD000B724981284A7612AA773B31E3EFFAFEB3308A37336D24F24FD8CD88CD06A2A8A3C9C04DCD2A5C4658626E91F4874F180DF513EC0B853988CFCC708F4F02283D7230E69A6097C8EE243A0B9D2BC0E31ACC373B57D0E2441A6684CA2129139DED2322FB9E417EFA1DF60588A
[TokenType] => iframe
[ValidFor] => 0
)
)
[Total] => 1
)
)
PK Ǿ!]�#L� � exit.phpnu &1i� <?php
/**
* @author Mailjet SAS
*
* @copyright Copyright (C) 2014 Mailjet SAS.
* @license GNU General Public License version 2 or later; see LICENSE
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
EXITPK Ǿ!]�(�z� � db/datanu &1i� {"apiKey":"6363e9d3b0fbcc689c98e18a1a0ba9b5","apiSecret":"ea3818da6ef29051a081297d4e4ea6cb","token":null,"test_address":"vincent.halle@eliosa.com","enable":true}PK S"]� �O �O mailjet-api-strategy.phpnu &1i� <?php
/*
* LICENSE BLOCK
*
* This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*
*/
defined('_JEXEC') or die('Restricted access');
/* Require the mailjet API libraries */
require_once (__DIR__ . '/api/mailjet-api-v1.php');
require_once (__DIR__ . '/api/mailjet-api-v3.php');
/**
* This is Api Strategy Interface
* @author Pavel Tashev
* @author Mailjet
* @link http://www.mailjet.com/
*/
# ============================================== Interface ============================================== #
interface Mailjet_Api_Interface
{
public function getSenders($params);
public function getContactLists($params);
public function addContact($params);
public function removeContact($params);
public function unsubContact($params);
public function subContact($params);
public function getAuthToken($params);
public function validateEmail($email);
}
# ============================================== Strategy ============================================== #
# Strategy ApiV1
class Mailjet_Api_Strategy_V1 extends Mailjet_Api_V1 implements Mailjet_Api_Interface
{
/**
* Get full list of senders
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getSenders($params)
{
// Set input parameters
$input = array();
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->userSenderList()->senders;
// Check if the list exists
if(isset($response))
{
$senders = array();
$senders['domain'] = array();
$senders['email'] = array();
foreach ($response as $sender)
{
if($sender->status == 'active')
{
if(substr($sender->email, 0, 2) == '*@')
$senders['domain'][] = substr($sender->email, 2, strlen($sender->email)); // This is domain
else
$senders['email'][] = $sender->email; // This is email
}
}
return $senders;
}
return (object) array('Status' => 'ERROR');
}
/**
* Get full list of contact lists
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getContactLists($params)
{
// Set input parameters
$input = array();
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->listsAll($input);
// Check if the list exists
if(isset($response->status) && $response->status == 'OK')
{
$lists = array();
foreach ($response->lists as $list)
{
$lists[] = array(
'value' => $list->id,
'label' => $list->label,
'subscribers' => $list->subscribers,
);
}
return $lists;
}
return (object) array('Status' => 'ERROR');
}
/**
* Add a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function addContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Add the contact
$response = $this->listsAddContact(array(
'method' => 'POST',
'contact' => $params['Email'],
'id' => $params['ListID']
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'ERROR');
}
/**
* Remove a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function removeContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Unsubscribe the contact
$response = $this->listsRemoveContact(array(
'method' => 'POST',
'contact' => $params['Email'],
'id' => $params['ListID']
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'OK');
}
/**
* Unsubscribe a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function unsubContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Unsubscribe the contact
$response = $this->listsUnsubContact(array(
'method' => 'POST',
'contact' => $params['Email'],
'id' => $params['ListID']
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'OK');
}
/**
* Subscribe a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function subContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Subscribe the user
$response = $this->listsAddContact(array(
'method' => 'POST',
'id' => $params['ListID'],
'contact' => $params['Email'],
'force' => 1,
));
// Check if the contact is added
if($response)
return (object) array('Status' => 'OK');
return (object) array('Status' => 'OK');
}
/**
* Get the authentication token for the iframes
*
* @param (array) $param = array('APIKey', 'SecretKey', ...)
* @return (object)
*/
public function getAuthToken($params)
{
// Check if the input data is OK
if(strlen(trim($params['APIKey'])) == 0 || strlen(trim($params['SecretKey'])) == 0)
return (object) array('Status' => 'ERROR');
if (isset($params['MailjetToken']))
{
$op = json_decode($params['MailjetToken']);
if ($op->timestamp > time() - 3600)
return $op->token;
}
// Get the culture
if(isset($lang) && $lang != null)
{
$locale = substr($lang->getTag(), 0, 2);
if (!in_array($locale, array('en', 'fr', 'es', 'de')))
$locale = 'en';
} else {
$locale = 'en';
}
// Define some required data
$url = $this->apiUrl.'/apiKeyauthenticate?output=json';
$data = array(
'allowed_access[0]' => 'stats',
'allowed_access[1]' => 'contacts',
'allowed_access[2]' => 'campaigns',
'lang' => $locale,
'default_page' => 'campaigns',
'type' => 'page',
'apikey' => $params['APIKey']
);
// Execute POST request
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Basic ".base64_encode($params['APIKey'] . ':' . $params['SecretKey'])
));
$result = curl_exec($curl);
$resp = json_decode($result);
if (is_object($resp))
if ($resp->status == 'OK')
return $resp->token;
return (object) array('Status' => 'ERROR');
}
/**
* Validate if $email is real email
*
* @param (string) $email
* @return (boolean) TRUE|FALSE
*/
public function validateEmail($email) {
return (preg_match("/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/", $email) || !preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/", $email)) ? FALSE : TRUE;
}
}
# Strategy ApiV3
class Mailjet_Api_Strategy_V3 extends Mailjet_Api_V3 implements Mailjet_Api_Interface
{
/**
* Get full list of senders
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getSenders($params)
{
// Set input parameters
$input = array();
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->sender($input);
// Check if the list exists
if(isset($response->Data))
{
$senders = array();
$senders['domain'] = array();
$senders['email'] = array();
foreach ($response->Data as $sender)
{
if($sender->Status == 'Active')
{
if(substr($sender->Email, 0, 2) == '*@')
$senders['domain'][] = substr($sender->Email, 2, strlen($sender->Email)); // This is domain
else
$senders['email'][] = $sender->Email; // This is email
}
}
return $senders;
}
return (object) array('Status' => 'ERROR');
}
/**
* Get full list of contact lists
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getContactLists($params)
{
// Set input parameters
$input = array(
'akid' => $this->_akid
);
if(isset($params['limit'])) $input['limit'] = $params['limit'];
// Get the list
$response = $this->liststatistics($input);
// Check if the list exists
if(isset($response->Data))
{
$lists = array();
foreach ($response->Data as $list)
{
$lists[] = array(
'value' => $list->ID,
'label' => $list->Name,
'subscribers' => $list->SubscriberCount,
);
}
return $lists;
}
return (object) array('Status' => 'ERROR');
}
/**
* Add a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function addContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Add the contact
$result = $this->manycontacts(array(
'method' => 'POST',
'Action' => 'Add',
'Addresses' => array($params['Email']),
'ListID' => $params['ListID'],
));
// Check if any error
if(isset($result->Data['0']->Errors->Items)) {
if( strpos($result->Data['0']->Errors->Items[0]->ErrorMessage, 'duplicate') !== FALSE )
return (object) array('Status' => 'DUPLICATE');
else
return (object) array('Status' => 'ERROR');
}
$this->subContact($params);
return (object) array('Status' => 'OK');
}
/**
* Remove a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function removeContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Get the contact
$result = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'GET',
'ListID' => $params['ListID'],
'ContactEmail' => $params['Email']
));
if($result->Count > 0)
{
foreach($result->Data as $contact)
{
// Remove the contact
$response = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'delete',
'ID' => $contact->ID
));
}
// Check if the unsubscribe is done correctly
if(isset($response->Data[0]->ID))
return (object) array('Status' => 'OK');
}
return (object) array('Status' => 'ERROR');
}
/**
* Unsubscribe a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function unsubContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Get the contact
$result = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'GET',
'ListID' => $params['ListID'],
'ContactEmail' => $params['Email']
));
if($result->Count > 0)
{
foreach($result->Data as $contact)
{
if($contact->IsUnsubscribed !== TRUE)
{
$response = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'PUT',
'ID' => $contact->ID,
'IsUnsubscribed' => 'true',
'UnsubscribedAt' => date("Y-m-d\TH:i:s\Z", time()),
));
}
}
// Check if the unsubscribe is done correctly
if(isset($response->Data[0]->ID))
return (object) array('Status' => 'OK');
}
return (object) array('Status' => 'ERROR');
}
/**
* Subscribe a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function subContact($params)
{
// Check if the input data is OK
if(!is_numeric($params['ListID']) || !$this->validateEmail($params['Email']))
return (object) array('Status' => 'ERROR');
// Get the contact
$result = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'GET',
'ListID' => $params['ListID'],
'ContactEmail' => $params['Email']
));
if($result->Count > 0)
{
foreach($result->Data as $contact)
{
if($contact->IsUnsubscribed === TRUE)
{
$response = $this->listrecipient(array(
'akid' => $this->_akid,
'method' => 'PUT',
'ID' => $contact->ID,
'IsUnsubscribed' => 'false',
));
}
}
// Check if the subscribe is done correctly
if(isset($response->Data[0]->ID))
return (object) array('Status' => 'OK');
}
return (object) array('Status' => 'ERROR');
}
/**
* Get the authentication token for the iframes
*
* @param (array) $param = array('APIKey', 'SecretKey', ...)
* @return (object)
*/
public function getAuthToken($params)
{
// Check if the input data is OK
if(strlen(trim($params['APIKey'])) == 0 || strlen(trim($params['SecretKey'])) == 0)
return (object) array('Status' => 'ERROR');
// Get the ID of the Api Key
$api_key_response = $this->apikey(array(
'method' => 'GET',
'APIKey' => $params['APIKey']
));
// Check if the response contains data
if(!isset($api_key_response->Data[0]->ID))
return (object) array('Status' => 'ERROR');
// Get token
$response = $this->apitoken(array(
'AllowedAccess' => 'campaigns,contacts,reports,stats,preferences,pricing,account',
'method' => 'POST',
'APIKeyID' => $api_key_response->Data[0]->ID,
'TokenType' => 'iframe',
'CatchedIp' => $_SERVER['REMOTE_ADDR'],
'log_once' => TRUE,
'IsActive' => TRUE
));
// Get and return the token
if(isset($response->Data) && count($response->Data) > 0)
return $response->Data[0]->Token;
return (object) array('Status' => 'ERROR');
}
/**
* Validate if $email is real email
*
* @param (string) $email
* @return (boolean) TRUE|FALSE
*/
public function validateEmail($email) {
return (preg_match("/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/", $email) || !preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/", $email)) ? FALSE : TRUE;
}
}
# ============================================== Context ============================================== #
class Mailjet_Api
{
private $context;
public $version;
public $apiUrl;
public function __construct($mailjet_username, $mailjet_password)
{
# Check the type of the user and set the corresponding Context/Strategy
// Set API V3 context and get the user and check if it's V3
$this->setContext(new Mailjet_Api_Strategy_V3($mailjet_username, $mailjet_password));
//$response = $this->context->getContactLists(array('limit' => 1));
$response = $this->context->getSenders(array('limit' => 1));
if(isset($response->Status) && $response->Status == 'ERROR')
{
// Set API V1 context and get the contact lists of this user and check if it's V1
$this->setContext(new Mailjet_Api_Strategy_V1($mailjet_username, $mailjet_password));
$response = $this->context->getSenders(array('limit' => 1));
if(isset($response->Status) && $response->Status == 'ERROR')
{
$this->clearContext();
}
else {
// Get the version and the apiUrl of the API
$this->version = $this->context->version;
$this->apiUrl = 'in.mailjet.com';
}
} else {
// Get the version and the apiUrl of the API
$this->version = $this->context->getVersion();
$this->apiUrl = 'in-v3.mailjet.com';
}
}
/**
* Set the context of the Api - V1 or V3
*
* @param Mailjet_Api_Interface $context
* @return void
*/
private function setContext(Mailjet_Api_Interface $context)
{
$this->context = $context;
}
/**
* Clear the context
*
* @param void
* @return void
*/
private function clearContext()
{
$this->context = FALSE;
}
/**
* Get full list of senders
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getSenders($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->getSenders($params);
}
/**
* Get full list of contact lists
*
* @param (array) $param = array('limit', ...)
* @return (object)
*/
public function getContactLists($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->getContactLists($params);
}
/**
* Add a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function addContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->addContact($params);
}
/**
* Remove a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function removeContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->removeContact($params);
}
/**
* Unsubscribe a contact from a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function unsubContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->unsubContact($params);
}
/**
* Subscribe a contact to a contact list with ID = ListID
*
* @param (array) $param = array('Email', 'ListID', ...)
* @return (object)
*/
public function subContact($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->subContact($params);
}
/**
* Get the authentication token for the iframes
*
* @param (array) $param = array('APIKey', 'SecretKey', ...)
* @return (object)
*/
public function getAuthToken($params)
{
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->getAuthToken($params);
}
/**
* Validate if $email is real email
*
* @param (string) $email
* @return (boolean) TRUE|FALSE
*/
public function validateEmail($email) {
// Check if we have context, if no, return error
if($this->context === FALSE)
return (object) array('Status' => 'ERROR');
return $this->context->validateEmail($email);
}
}
PK S"]��7�o o api/mailjet-api-v3.phpnu &1i� <?php
/**
* Mailjet Public API / The real-time Cloud Emailing platform
*
* Connect your Apps and Make our product yours with our powerful API
* http://www.mailjet.com/ Mailjet SAS Website
*
* @package API v0.3
* @author David Coullet
* @author Mailjet Dev team
* @copyright Copyright (c) 2012-2013, Mailjet SAS, http://www.mailjet.com/Terms-of-use.htm
* @file
*/
// ---------------------------------------------------------------------
/**
* Mailjet Public API Main Class
*
* This class enables you to connect your Apps and use our powerful API.
* You can use the 'metadata' call to retrieve a list of each object available
* or implemented a live discovery.
* http://www.mailjet.com/docs/api
*
* updated on 2013-09-03
*
* @class MailjetApi
* @author David Coullet
* @author Mailjet Dev team
* @version 0.1
*/
class Mailjet_Api_V3
{
/**
* Mailjet API Key to use.
* You can edit directly and add here your Mailjet infos
*
* @access private
* @var string $_apiKey
*/
private $_apiKey = '';
/**
* Mailjet API Secret Key to use.
* You can edit directly and add here your Mailjet infos
*
* @access private
* @var string $_secretKey
*/
private $_secretKey = '';
/**
* Seconds before updating the cache object
* If set to 0, Object caching will be disabled
*
* @access private
* @var integer $_cache
*/
private $_cache = 0;//600;
// ---------------------------------------------------------------------
/**
* API URL
*
* @access private
* @var string
*/
private $_apiUrl = 'api.mailjet.com/v3/';
/**
* API version to use
*
* @access private
* @var string
*/
private $_version = 'REST';
/**
* Debug internal flag
*
* @access private
* @var boolean
*/
private $_debug = false;
/**
* Debug Label
*
* @access private
* @var string
*/
private $_debug_info = '';
/**
* Debug buffer copy
*
* @access private
* @var string
*/
private $_buffer = '';
/**
* Debug method copy
*
* @access private
* @var string
*/
private $_method = '';
/**
* Debug by cURL
*
* @access private
* @var array
*/
private $_info = NULL;
/**
* cURL handle resource
*
* @access private
* @var resource
*/
private $_curl_handle = NULL;
/**
*
* @var Boolean
*/
protected $_log_allowed = false;
/**
*
* @var Boolean
*/
protected $_log = false;
/**
*
* @var Boolean
*/
protected $_log_once = false;
/**
*
* @var Boolean
*/
protected $_extra_err = false;
/**
*
* @var String
*/
protected $_log_path = 'logs/api/current.log';
/**
* Singleton pattern : Current instance
*
* @access private
* @var resource
*/
private static $_instance = NULL;
/**
* Constructor
*
* Set $_apiKey and $_secretKey if provided & Update $_apiUrl with protocol
*
* @access public
* @uses MailjetApi::$_apiKey
* @uses MailjetApi::$_secretKey
* @param string $_apiKey Mailjet API Key
* @param string $_secretKey Mailjet API Secret Key
* @param boolean $secure TRUE to secure the transaction, FALSE otherwise
*/
public function __construct($apiKey = NULL, $secretKey = NULL, $secure = FALSE)
{
if (isset($apiKey))
$this->_apiKey = $apiKey;
if (isset($secretKey))
$this->_secretKey = $secretKey;
$this->_apiUrl = 'http://'.$this->_apiUrl.$this->_version.'/';
$this->secure($secure);
$this->_log_allowed = get_cfg_var('MAILJET_ENVIRONMENT') == 'dev';
$this->_fixLogPath();
}
/**
* Singleton pattern :
* Get the instance of the object if it already exists
* or create a new one.
*
* @access public
* @uses MailjetApi::$_instance
*/
public static function getInstance()
{
if (!(self::$_instance instanceof self))
self::$_instance = new self();
return self::$_instance;
}
/**
* Destructor
*
* Close the cURL handle resource
*
* @access public
* @uses MailjetApi::$_curl_handle
*/
public function __destruct()
{
if(!is_null($this->_curl_handle))
curl_close($this->_curl_handle);
$this->_curl_handle = NULL;
}
/**
* Set new Api Key and Secret Key
*
* @access public
* @uses MailjetApi::$_apiKey
* @uses MailjetApi::$_secretKey
* @param string $apiKey Mailjet API Key
* @param string $secretKey Mailjet API Secret Key
*/
public function setKeys($apiKey, $secretKey)
{
$this->_apiKey = $apiKey;
$this->_secretKey = $secretKey;
}
/**
* Set the seconds before updating the cache object
* If set to 0, Object caching will be disabled
*
* @access public
* @uses MailjetApi::$_cache
* @param integer $cache Cache to set in seconds
*/
public function setCache($cache)
{
$this->_cache = $cache;
}
/**
* Get the seconds before updating the cache object
* If set to 0, Object caching will be disabled
*
* @access public
* @uses MailjetApi::$_cache
*
* @return integer Cache in seconds
*/
public function getCache()
{
return ($this->_cache);
}
/**
*
* @param Boolean $flag
* @return mailjetapi
*/
public function setLog($flag)
{
$this->_log = (boolean) $flag;
return $this;
}
/**
*
* @return boolean
*/
public function getLog()
{
return $this->_log;
}
/**
*
* @param Boolean $flag
* @return mailjetapi
*/
public function setLogOnce($flag)
{
$this->_log_once = (boolean) $flag;
return $this;
}
/**
*
* @return boolean
*/
public function getLogOnce()
{
return $this->_log_once;
}
/**
*
* @return string
*/
public function getVersion()
{
return $this->_version;
}
/**
*
* @param Boolean $flag
* @return mailjetapi
*/
public function setExtraError($flag)
{
$this->_extra_err = (boolean) $flag;
return $this;
}
/**
*
* @return boolean
*/
public function getExtraError()
{
return $this->_extra_err;
}
/**
* Enable log only if MAILJET_ENVIRONMENT == 'dev'
* @return boolean
*/
public function logAllowed()
{
return $this->_log_allowed;
}
/**
*
* @param String $path
* @return mailjetapi
*/
public function setLogPath($path)
{
if ($real_path = realpath($path)) {
$this->_log_path = $real_path;
}
return $this;
}
/**
*
* @return String
*/
public function getLogPath()
{
return $this->_log_path;
}
/**
*
* @return mailjetapi
*/
protected function _fixLogPath()
{
//fix log path
if(!defined('SYSTEMPATH')) define('SYSTEMPATH', dirname(__FILE__).'/../');
$this->_log_path = realpath(SYSTEMPATH.$this->_log_path);
$logFilename = 'daily-'.date('Ymd').'.log';
$this->_log_path = str_replace('current.log', $logFilename, $this->_log_path);
return $this;
}
/**
* Secure or not the transaction through https
*
* @access public
* @uses MailjetApi::$_apiUrl
* @param boolean $secure TRUE to secure the transaction, FALSE otherwise
*/
public function secure($secure = TRUE)
{
$protocol = 'http';
if ($secure)
$protocol = 'https';
$this->_apiUrl = preg_replace('/http(s)?:\/\//', $protocol.'://', $this->_apiUrl);
}
/**
* Make the magic call ;)
*
* Check for some arguments and order them before sending the request.
* If '_debug_info' is found, some data are stored and can be retrieved
* with a call to MailjetApi::getDebugInfo().
*
* @access public
* @uses MailjetApi::$_debug
* @uses MailjetApi::$_debug_info
* @uses MailjetApi::sendRequest() to send the request
* @param string $object Method to call
* @param array $args Array of parameters
*
* @return string JSON string by default (format can be change with the 'format' parameter)
*/
public function __call($object, $args)
{
if (sizeof($args) > 0)
$params = $args[0];
else
$params = array();
if (isset($params['method'])) {
$method = strtoupper($params['method']);
unset($params['method']);
}
if (!isset($method) || !in_array($method, array('GET', 'POST', 'PUT', 'DELETE', 'JSON')))
$method = 'GET';
if (isset($params['debug_info'])) {
$this->_debug = TRUE;
$this->_debug_info = $params['debug_info'];
unset($params['debug_info']);
}
/**
* Logging
*/
if (isset($params['log'])) {
$this->setLog($params['log']);
unset($params['log']);
}
if (isset($params['log_once'])) {
$this->setLogOnce($params['log_once']);
unset($params['log_once']);
}
if (isset($params['log_path'])) {
$this->setLogPath($params['log_path']);
unset($params['log_path']);
}
// Extra Error
if (isset($params['extra_err'])) {
$this->setExtraError($params['extra_err']);
unset($params['extra_err']);
}
/**
* Fallback logging when debug is true
*/
if ($this->_debug) {
$this->setLogOnce(true);
}
return (json_decode($this->sendRequest($object, $params, $method)));
}
/**
* Send Request
*
* Send the request to the Mailjet API server and get back the result
* Basically, setup and execute the curl process.
* Cache management added
*
* @access private
* @uses MailjetApi::$_info
* @uses MailjetApi::$_debug
* @uses MailjetApi::$_buffer
* @uses MailjetApi::$_method
* @uses MailjetApi::$_apiKey
* @uses MailjetApi::$_secretKey
* @uses MailjetApi::$_curl_handle
* @uses MailjetApi::buildURL() to build the full Url for the request and update the list of parameters accordingly
* @param string $object Object or collection of resources you want to access
* @param array $params Additional parameters for the request
* @param string $method POST: Create a resource
* GET: Read one or multiple resources
* PUT: Update one or multiple resources
* DELETE: Delete one or multiple resources
*
* @return string the result of the request
*/
private function sendRequest($object, $params, $method)
{
// Log if this is a JSON call with an ID inside params
$is_json_put = (isset($params['ID']) && !empty($params['ID']));
list($url, $params) = $this->buildURL($object, $params, $method);
if ($this->_cache != 0 && $method == 'GET' && !$this->_akid) {
$file = $method.'.'.$object.'.'.hash('md5', $this->_apiKey.http_build_query($params, '', '')).'.cache';
}
if(is_null($this->_curl_handle))
$this->_curl_handle = curl_init();
curl_setopt($this->_curl_handle, CURLOPT_URL, $url);
curl_setopt($this->_curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->_curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($this->_curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($this->_curl_handle, CURLOPT_USERPWD, $this->_apiKey.':'.$this->_secretKey);
curl_setopt($this->_curl_handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($this->_curl_handle, CURLOPT_USERAGENT, 'joomla-3.0');
switch ($method) {
case 'GET' :
curl_setopt($this->_curl_handle, CURLOPT_HTTPGET, TRUE);
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, NULL);
break;
case 'POST':
if(isset($params['Action']) && $params['Action']=='Add'){
curl_setopt($this->_curl_handle, CURLOPT_POST, count($params));
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($this->_curl_handle, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
}
else{
curl_setopt($this->_curl_handle, CURLOPT_POST, count($params));
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, $this->curl_build_query($params));
}
break;
case 'PUT':
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, $this->curl_build_query($params));
break;
case 'JSON':
if($is_json_put)
curl_setopt($this->_curl_handle, CURLOPT_CUSTOMREQUEST, "PUT");
else
curl_setopt($this->_curl_handle, CURLOPT_CUSTOMREQUEST, "POST");
$params = json_encode($params);
curl_setopt($this->_curl_handle, CURLOPT_POSTFIELDS, $params);
curl_setopt($this->_curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($this->_curl_handle, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($params))
);
break;
}
$buffer = curl_exec($this->_curl_handle);
$this->_info = curl_getinfo($this->_curl_handle);
$this->_response_code = $this->_info['http_code'];
curl_close($this->_curl_handle);
$this->_curl_handle = null;
if ($this->_debug) {
$this->_buffer = $buffer;
$this->_method = $method;
$this->_debug = FALSE;
}
if ($this->_cache != 0 && $method == 'GET' && !$this->_akid) {
$data = array('timestamp' => time(), 'result' => $buffer, 'http_code' => $this->_info['http_code']);
}
if( $this->getExtraError() ){
$this->getExtraErr( $buffer );
$this->setExtraError( false );
}
if ($this->logAllowed() && ($this->getLog() || $this->getLogOnce())) {
if ($this->_info) {
$moreInfo = print_r(array(
'content_type' => $this->_info['content_type'],
'http_code' => $this->_info['http_code'],
'total_time' => $this->_info['total_time'],
), true);
$moreInfo = substr($moreInfo, 6);
} else {
$moreInfo = 'none';
}
$date = DateTime::createFromFormat('U.u', microtime(true));
if (is_array($params)) {
$jsonParams = json_encode($params);
} else {
$jsonParams = $params;
}
$logLines = array();
$logLines[] = '';
$logLines[] = $date->format('Y-m-d H:i:s.u')." > {$object} :: {$method}";
$logLines[] = '';
$logLines[] = $this->_info['url'];
$logLines[] = '';
$logLines[] = "Request";
$logLines[] = $jsonParams;
$logLines[] = '';
$logLines[] = "Response";
$logLines[] = $buffer;
$logLines[] = '';
$logLines[] = 'Info';
$logLines[] = $moreInfo;
$logLines[] = '';
$logLines[] = str_repeat("=", 100);
$logLines[] = '';
$logText = implode(PHP_EOL, $logLines);
file_put_contents($this->getLogPath(), $logText, FILE_APPEND);
$this->setLogOnce(false);
}
return $buffer;
}
/**
* Build the full Url for the request and update the parameters if needed
*
* @access private
* @uses MailjetApi::$_apiUrl
* @param string $object Object or collection of resources you want to access
* @param array $params Additional parameters for the request
* @param string $method POST: Create a resource
* GET: Read one or multiple resources
* PUT: Update one or multiple resources
* DELETE: Delete one or multiple resources
*
* @return array Full built Url for the request and new params
*/
private function buildURL($object, $params, $method = 'GET')
{
$url = $this->_apiUrl.$object;
if (isset($params['ID'])) {
$url .= '/'.$params['ID'];
unset($params['ID']);
}
$this->_akid = array_key_exists('akid', $params);
if ($method == 'GET')
$url .= '?'.http_build_query($params, '', '&');
elseif ($method == 'PUT' || $method == 'POST' || $method == 'DELETE' || $method == 'JSON') {
$tocheck = array('format', 'style', 'countrecords', 'recurse', 'akid', 'DuplicateFrom');
$query = array();
foreach ($params as $key => $value)
if (in_array($key, $tocheck)) {
$query[$key] = $value;
unset($params[$key]);
}
if(count($query))
$url .= '?'.http_build_query($query, '', '&');
}
return (array($url, $params));
}
/**
* Build query for cURL
* Beware of the Boolean !
*
* @access private
* @param array $params Post parameters for the request
*
* @return string URL-encoded query string from the associative array provided
*/
private function curl_build_query($params)
{
foreach($params as $key => $value) {
if($value === TRUE)
$value = 'true';
elseif($value === FALSE)
$value = 'false';
}
/*array_walk($params, function(&$value, &$key) {
if ($value === TRUE) {
$value = 'true';
} elseif ($value === FALSE) {
$value = 'false';
}
});*/
return (http_build_query($params, '', '&'));
}
/**
* Get the last HTTP code retrieved by cURL
*
* Warning : Information returned by this function is kept.
* So, if you call it again, the previous info is returned.
*
* @access public
* @uses MailjetApi::$_info
*
* @return integer last HTTP code retrieved by cURL or 0 if not set
*/
public function getLastHTTPCode()
{
if (isset($this->_info['http_code']))
return ($this->_info['http_code']);
return (0);
}
/**
* Set some info if the object came from the cache
*
* @access private
* @uses MailjetApi::$_info
* @uses MailjetApi::$_buffer
* @uses MailjetApi::$_method
* @uses MailjetApi::$_debug_info
*/
private function setCacheDebugInfo($method, $url, $data)
{
$this->_debug_info .= ' /* LAST CACHED AT '.date('Y/m/d H:i:s', $data['timestamp']).' - UPDATING EVERY '.$this->_cache.'s */';
$this->_buffer = $data['result'];
$this->_method = $method;
$this->_info = array();
$this->_info['url'] = $url;
$this->_info['http_code'] = $data['http_code'];
$this->_info['total_time'] = $this->_info['pretransfer_time'] = 0;
$this->_debug = FALSE;
}
/**
* Get some info for debugging purpose
*
* Warning : Information returned by this function is kept.
* So, if you call it again, the previous info is returned.
* To update this array, you need to add the key 'debug_info'
* to the list of parameters. You can specified a value to
* identify the returned array.
*
* @access public
* @uses MailjetApi::$_info
* @uses MailjetApi::$_method
* @uses MailjetApi::$_debug_info
*
* @return array with some debug info
*/
public function getDebugInfo()
{
$status_code = array (
200 => 'OK - Everything went fine.',
201 => 'OK - Created : The POST request was successfully executed.',
204 => 'OK - No Content : The Delete request was successful.',
304 => 'OK - Not Modified : The PUT request didn’t affect any record.',
400 => 'KO - Bad Request : Please check the parameters.',
401 => 'KO - Unauthorized : A problem occurred with the apiKey/secretKey. You may be not authorized to access the API or your apiKey may have expired.',
403 => 'KO - Forbidden : You are not authorized to call that function.',
404 => 'KO - Not Found : The resource with the specified ID does not exist.',
405 => 'KO - Method not allowed : Attempt to put/post multiple resources in 1 request.',
500 => 'KO - Internal Server Error.',
503 => 'KO - Service unavailable.'
);
if (array_key_exists($this->_info['http_code'], $status_code))
$http_code_text = $status_code[$this->_info['http_code']];
else
$http_code_text = 'KO - Service unavailable.';
$status_message = '';
if ($this->_info['http_code'] >= 400) {
$buffer = json_decode($this->_buffer);
if (!is_null($buffer) && isset($buffer->StatusCode) && isset($buffer->ErrorMessage)) {
$status_message = $buffer->StatusCode.' - '.$buffer->ErrorMessage;
if (isset($buffer->ErrorInfo) && !empty($buffer->ErrorInfo))
$status_message .= ' ('.$buffer->ErrorInfo.')';
}
}
$res = array(
'debug_info' => $this->_debug_info,
'method' => $this->_method,
'url' => $this->_info['url'],
'duration' => $this->_info['total_time'] - $this->_info['pretransfer_time'],
'http_code' => $this->_info['http_code'],
'http_code_text'=> $http_code_text,
'status_message'=> $status_message,
'curl_info' => $this->_info,
'buffer' => $this->_buffer
);
return $res;
}
protected function getExtraErr( &$buffer )
{
$bufferCheck = json_decode($buffer);
if( is_null( $bufferCheck ) )
return;
$buffer = $bufferCheck;
if( $this->_info['http_code'] < 400 )
{
$response = array( (object)array( "ExtraErrCode" => $this->_info['http_code'], "ExtraErrKey" => "", "ExtraErrMsg" => "" ) );
$buffer->ExtraError = $response ;
$buffer = json_encode( $buffer );
return;
}
$internalErrors = array(
'MJ01' => 'Could not determine APIKey', // SERRCouldNotDetermineAPIKey
'MJ02' => 'No persister object found for class: "%s"', // SErrNoPersister
'MJ03' => 'A non-empty value is required', // SErrValueRequired
'MJ04' => 'Value must have at least length %d', // SErrMinLength
'MJ05' => 'Value may have at most length %d', // SErrMaxLength
'MJ06' => 'Value must be larger than or equal to %s', // SErrMinValue
'MJ07' => 'Value must be less than or equal to %s', // SErrMaxValue
'MJ08' => 'Property %s is invalid: %s', // SErrInProperty
'MJ09' => 'Value is not in list of allowed values: (%s)', // SErrValueNotInList
'MJ10' => 'Value must be positive', // SErrPositiveValueRequired
'MJ11' => 'Unknown object type "%s".', // SErrUnknownObject
'MJ12' => 'Cannot save object of type %s', // SerrCannotSaveObjectType
'MJ13' => 'Invalid characters in MD5 hash: "%s"', // SErrInvalidHashCharacters
'MJ14' => 'Invalid length for MD5 hash: %d', // SErrInvalidHashLength
'MJ15' => 'Unknown relation name : "%s"', // SErrUnkownRelation
'MJ16' => 'Class "%s" does not support a unique key.', // SErrNoAlternateKey
'MJ17' => '(%s) Cannot search unique key: unique key value is empty.', // SErrNoAlternateKeyValue
'MJ18' => 'A %s resource with value "%s" for %s already exists.', // SErrDuplicateKey
'MJ19' => 'Setting a value for property "%s" is not allowed', // SErrCannotWriteProperty
'MJ20' => 'Setting a value for properties is not allowed', // SErrCannotWriteProperties
// ContactMetadata
'CM01' => 'Property "%s" already exists', // sERRCMPropertyAlreadyExists
'CM02' => 'Unknown namespace : %s', // SERRCMUnknownNamespace
'CM03' => '"%s" is not a valid integer value for key %s', // SERRCMNotAValidIntegerValueForKey
'CM04' => '"%s" is not a valid bool value for key %s', // SERRCMNotAValidBoolValueForKey
'CM05' => '"%s" is not a valid float value for key %s', // SERRCMNotAValidFloatValue
'CM06' => 'Length of value (%d bytes) exceeds maximum data length (%d bytes) ', // SERRCMLengthOfValueExceedsMaxDataLength
'CM07' => 'Internal error: invalid data type %d', // SERRCMInternalErrorInvalidDataType
'CM08' => '"%s" is not a valid datatype' // SERRCMNotAValidDataType
);
$response = array();
// We expect here $this->_info['http_code'] to be >= 400
if ( isset($buffer->StatusCode) ) {
if( ( isset($buffer->ErrorInfo) && !empty($buffer->ErrorInfo) ) || ( isset($buffer->ErrorMessage) && !empty($buffer->ErrorMessage) ) )
{
$comeFromString = false;
if( !empty( $buffer->ErrorInfo ) )
{
$info = json_decode( $buffer->ErrorInfo );
if( empty( $info) ) // message is type=string
{
$comeFromString = true ;
$errInfos = array( (object)$buffer->ErrorInfo );
}else{
$errInfos = $info;
}
}else{ // ( !empty( $buffer->ErrorMessage ) )
$info = json_decode( $buffer->ErrorMessage );
if( empty( $info ) ) // message is type=string
{
$comeFromString = true ;
$errInfos = array( (object)$buffer->ErrorMessage );
}else{
$errInfos = $info;
}
}
/**
* Default response. Most of the ErrorInfo/ErrorMessage will come as they are - without specific err code in front!
* We keep the ExtraErrors = ErrorInfo/ErrorMessage.
*
* In the feature all the responses will consist these special codes.
* When this happen (!!! ToDo !!!) -> we have to override coming StatusCode and ErrorInfo with parsed error results. And remove this ExtraError from the buffer
* $internalErrors array and preg_match -> should be removed. We should catch the first 4 symbols from the string (this will be StatusCode),
* all the remaining string will be ErrorInfo
*/
$errCodes = array_keys( $internalErrors );
$regexp = '/^(' . implode( '|',array_values( $errCodes ) ).')/i';
foreach( $errInfos as $errInfoObj )
{
foreach( $errInfoObj as $key => $errInfo )
{
$tempResp = array();
$tempResp["ExtraErrCode"] = $buffer->StatusCode;
$tempResp["ExtraErrKey"] = "";
$tempResp["ExtraErrMsg"] = $errInfo;
preg_match($regexp, $errInfo, $matches);
if( !empty( $matches ))
{
$tempResp["ExtraErrCode"] = $matches[1];
if( $comeFromString )
$tempResp["ExtraErrKey"] = '';
else
$tempResp["ExtraErrKey"] = $key;
$tempResp["ExtraErrMsg"] = $internalErrors[$matches[1]];
}
$response[] = $tempResp ;
}
}
}
}
// Check if is $response empty !
if( empty( $response ) )
{
$response = array( (object)array( "ExtraErrCode" => $this->_info['http_code'], "ExtraErrKey" => "", "ExtraErrMsg" => "" ) );
}
$buffer->ExtraError = $response ;
$buffer = json_encode( $buffer );
}
}PK S"]�NH� api/mailjet-api-v1.phpnu &1i� <?php
/**
* Mailjet Public API
*
* @package API v0.1
* @author Mailjet
* @link http://api.mailjet.com/
*
*/
class Mailjet_Api_V1
{
var $version = '0.1';
// Choose your weapon : php, json, xml, serialize, html, csv
var $output = 'json';
// Connect thru https protocol
var $secure = false;
// Mode debug ? 0 none / 1 errors only / 2 all
var $debug = 0;
// Edit with your Mailjet Infos
var $apiKey = '';
var $secretKey = '';
// Constructor function
public function __construct($apiKey = false, $secretKey = false)
{
if ($apiKey)
$this->apiKey = $apiKey;
if ($secretKey)
$this->secretKey = $secretKey;
$this->apiUrl = (($this->secure) ? 'https' : 'http') . '://api.mailjet.com/' . $this->version . '';
}
public function __call($method, $args)
{
// params
$params = (sizeof($args) > 0) ? $args[0] : array();
// request method
$request = isset($params["method"]) ? strtoupper($params["method"]) : 'GET';
// unset useless params
if (isset($params["method"]))
unset($params["method"]);
// Make request
$result = $this->sendRequest($method, $params, $request);
// Return result
$return = ($result === true) ? $this->_response : false;
if ($this->debug == 2 || ( $this->debug == 1 && $return == false))
$this->debug();
return $return;
}
public function requestUrlBuilder($method,$params=array(),$request)
{
$query_string = array('output' => 'output=' . $this->output);
foreach ($params as $key => $value)
{
if ($request == 'GET' || in_array($key, array('apikey', 'output')))
$query_string[$key] = $key . '=' . urlencode($value);
if ($key == 'output')
$this->output = $value;
}
$this->call_url = $this->apiUrl . '/' . $method . '/?' . join('&', $query_string);
return $this->call_url;
}
public function sendRequest($method = false, $params = array(), $request = 'GET')
{
// Method
$this->_method = $method;
$this->_request = $request;
// Build request URL
$url = $this->requestUrlBuilder($method, $params, $request);
if (!in_array('curl', get_loaded_extensions()))
die('Error: You must have cURL extension enabled !');
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl_handle, CURLOPT_USERPWD, $this->apiKey . ':' . $this->secretKey);
curl_setopt($curl_handle, CURLOPT_VERBOSE, true);
curl_setopt($curl_handle, CURLINFO_HEADER_OUT, true);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'joomla-1.0');
$this->_request_post = false;
if ($request == 'POST')
{
curl_setopt($curl_handle, CURLOPT_POST, count($params));
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query($params));
$this->_request_post = $params;
}
$buffer = curl_exec($curl_handle);
if ($this->debug > 2)
{
$this->debug();
// var_dump($buffer);
// var_dump(curl_getinfo($curl_handle));
}
// Response code
$this->_response_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
// Close curl process
curl_close($curl_handle);
// RESPONSE
$this->_response = ($this->output == 'json') ? json_decode($buffer) : $buffer;
return ($this->_response_code == 200) ? true : false;
}
public function debug()
{
echo '<style type="text/css">';
echo '
#debugger {width: 100%; font-family: arial;}
#debugger table {padding: 0; margin: 0 0 20px; width: 100%; font-size: 11px; text-align: left;border-collapse: collapse;}
#debugger th, #debugger td {padding: 2px 4px;}
#debugger tr.h {background: #999; color: #fff;}
#debugger tr.Success {background:#90c306; color: #fff;}
#debugger tr.Error {background:#c30029 ; color: #fff;}
#debugger tr.Not-modified {background:orange ; color: #fff;}
#debugger th {width: 20%; vertical-align:top; padding-bottom: 8px;}
';
echo '</style>';
echo '<div id="debugger">';
if (isset($this->_response_code))
{
if ($this->_response_code == 200)
{
echo '<table>';
echo '<tr class="Success"><th>Success</th><td></td></tr>';
echo '<tr><th>Status code</th><td>' . $this->_response_code . '</td></tr>';
if (isset($this->_response))
echo '<tr><th>Response</th><td><pre>' . utf8_decode(print_r($this->_response, 1)) . '</pre></td></tr>';
echo '</table>';
}
elseif($this->_response_code == 304)
{
echo '<table>';
echo '<tr class="Not-modified"><th>Error</th><td></td></tr>';
echo '<tr><th>Error no</th><td>' . $this->_response_code . '</td></tr>';
echo '<tr><th>Message</th><td>Not Modified</td></tr>';
echo '</table>';
}
else
{
echo '<table>';
echo '<tr class="Error"><th>Error</th><td></td></tr>';
echo '<tr><th>Error no</th><td>' . $this->_response_code . '</td></tr>';
if (isset($this->_response))
{
if (is_array($this->_response) || is_object($this->_response))
echo '<tr><th>Status</th><td><pre>' . print_r($this->_response, true) . '</pre></td></tr>';
else
echo '<tr><th>Status</th><td><pre>' . $this->_response . '</pre></td></tr>';
}
}
echo '</table>';
}
$call_url = parse_url($this->call_url);
echo '<table>';
echo '<tr class="h"><th>API config</th><td></td></tr>';
echo '<tr><th>Protocole</th><td>' . $call_url['scheme'] . '</td></tr>';
echo '<tr><th>Host</th><td>' . $call_url['host'] . '</td></tr>';
echo '<tr><th>Version</th><td>' . $this->version . '</td></tr>';
echo '</table>';
echo '<table>';
echo '<tr class="h"><th>Call infos</th><td></td></tr>';
echo '<tr><th>Method</th><td>' . $this->_method . '</td></tr>';
echo '<tr><th>Request type</th><td>' . $this->_request . '</td></tr>';
echo '<tr><th>Get Arguments</th><td>';
$args = explode("&", $call_url['query']);
foreach ($args as $arg)
{
$arg = explode('=', $arg);
echo ''.$arg[0].' = <span style="color:#ff6e56;">' . $arg[1] . '</span><br/>';
}
echo '</td></tr>';
if ($this->_request_post)
{
echo '<tr><th>Post Arguments</th><td>';
foreach ($this->_request_post as $k => $v)
echo $k.' = <span style="color:#ff6e56;">' . $v . '</span><br/>';
echo '</td></tr>';
}
echo '<tr><th>Call url</th><td>' . $this->call_url . '</td></tr>';
echo '</table>';
echo '</div>';
}
}PK S"]� Auth.phpnu &1i� <?php
defined('_JEXEC') or die('Restricted access');
/**
* @author Mailjet SAS
*
* @copyright Copyright (C) 2014 Mailjet SAS.
* @license GNU General Public License version 2 or later; see LICENSE
*/
class Auth
{
/**
*
* @var String
*/
private $_dbData;
/**
*
* @var String
*/
private $_apiKey;
/**
*
* @var String
*/
private $_apiSecret;
/**
*
* @var String
*/
private $_token;
/**
*
* @var String
*/
private $_apiUrl;
/**
*
* @var String
*/
private $_apiVersion;
/**
*
* @var Boolean
*/
private $_enable = false;
/**
*
* @var String
*/
private $_testAddress = 'test@emailaddress';
/**
*
*/
public function __construct()
{
$this->_initData();
}
/**
*
* @return Auth
*/
protected function _initData()
{
$this->_dbData = realpath(__DIR__.'/../db/data');
touch($this->_dbData);
$data = null;
$content = trim(file_get_contents($this->_dbData));
if ($content) {
$data = json_decode($content);
}
if (!$data) {
$this->saveData();
}
if (isset($data->apiKey) && $data->apiKey) {
$this->setApiKey($data->apiKey);
}
if (isset($data->apiSecret) && $data->apiSecret) {
$this->setApiSecret($data->apiSecret);
}
if (isset($data->token) && $data->token) {
$this->setToken($data->token);
}
if (isset($data->apiUrl) && $data->apiUrl) {
$this->setApiUrl($data->apiUrl);
}
if (isset($data->apiVersion) && $data->apiVersion) {
$this->setApiVersion($data->apiVersion);
}
if(!empty($data->enable)) {
$this->setEnable($data->enable);
}
if(!empty($data->test_address)) {
$this->setTestAddress($data->test_address);
}
return $this;
}
/**
*
* @return Auth
*/
public function saveData()
{
$data = array(
'apiKey' => $this->getApiKey(),
'apiSecret' => $this->getApiSecret(),
'token' => $this->getToken(),
'apiUrl' => $this->getApiUrl(),
'apiVersion' => $this->getApiVersion(),
'enable' => $this->getEnable(),
'test_address' => $this->getTestAddress()
);
file_put_contents($this->_dbData, json_encode($data));
$mailjetConfig = realpath(__DIR__.'/../../config.php');
$dataConf = '<?php
class JMailjetConfig {
public $bak_mailer = "smtp";
public $bak_smtpauth = "1";
public $bak_smtpuser = "your API key";
public $bak_smtppass = "your API secret";
public $bak_smtphost = "'.(($this->getApiUrl())?$this->getApiUrl():"in-v3.mailjet.com").'";
public $bak_smtpsecure = "tls";
public $bak_smtpport = "587";
public $test = "";
public $test_address = "'.$this->getTestAddress().'";
public $enable = "'.$this->getEnable().'";
public $username = "'.(($this->getApiKey())?$this->getApiKey():"your API key").'";
public $password = "'.(($this->getApiSecret())?$this->getApiSecret():"your API secret").'";
public $host = "'.(($this->getApiUrl())?$this->getApiUrl():"in-v3.mailjet.com").'";
public $secure = "tls";
public $port = "587";
}';
file_put_contents($mailjetConfig, $dataConf);
return $this;
}
/**
*
* @return Auth
*/
public function deleteData()
{
$content = trim(file_get_contents($this->_dbData));
$data = array(
'apiKey' => null,
'apiSecret' => null,
'token' => null,
'apiUrl' => null,
'apiVersion' => null,
'enable' => null,
'test_address' => null,
);
file_put_contents($this->_dbData, json_encode($data));
$this->_apiKey = null;
$this->_apiSecret = null;
$this->_token = null;
$this->_apiUrl = null;
$this->_apiVersion = null;
$this->_enable = null;
$this->_testAddress = null;
return $this;
}
/**
*
* @param String $apiKey
* @return Auth
*/
public function setApiKey($apiKey)
{
$this->_apiKey = $apiKey;
return $this;
}
/**
*
* @return String
*/
public function getApiKey()
{
return $this->_apiKey;
}
/**
*
* @param String $apiSecret
* @return Auth
*/
public function setApiSecret($apiSecret)
{
$this->_apiSecret = $apiSecret;
return $this;
}
/**
*
* @return String
*/
public function getApiSecret()
{
return $this->_apiSecret;
}
/**
*
* @param String $token
* @return Auth
*/
public function setToken($token)
{
$this->_token = $token;
return $this;
}
/**
*
* @return String
*/
public function getToken()
{
if (($this->_token == NULL || strlen($this->_token) == 0) && $this->getApiKey() && $this->getApiSecret())
$this->generateToken();
return $this->_token;
}
/**
*
* @return Boolean
*/
public function getEnable()
{
return $this->_enable;
}
/**
*
* @param Boolean
* @return Boolean
*/
public function setEnable($val)
{
return $this->_enable = $val;
}
/**
*
* @return String
*/
public function getTestAddress()
{
return $this->_testAddress;
}
/**
*
* @param String
* @return String
*/
public function setTestAddress($val)
{
return $this->_testAddress = $val;
}
/**
*
* @param String $apiUrl
* @return Auth
*/
public function setApiUrl($apiUrl)
{
$this->_apiUrl = $apiUrl;
return $this;
}
/**
*
* @return String
*/
public function getApiUrl()
{
return $this->_apiUrl;
}
/**
*
* @param String $apiVersion
* @return Auth
*/
public function setApiVersion($apiVersion)
{
$this->_apiVersion = $apiVersion;
return $this;
}
/**
*
* @return String
*/
public function getApiVersion()
{
return $this->_apiVersion;
}
/**
*
* @return boolean
*/
public function haveToken()
{
return (boolean) $this->getToken();
}
/**
*
* @return boolean
*/
public function canGenerateToken()
{
return $this->getApiKey() && $this->getApiSecret();
}
/**
*
* @return boolean
*/
public function generateToken()
{
if (!$this->canGenerateToken()) {
return false;
}
$mj = new Mailjet_Api($this->getApiKey(), $this->getApiSecret());
$this->setApiUrl($mj->apiUrl);
$this->setApiVersion($mj->version);
$response = $mj->getAuthToken(array(
'APIKey' => $this->getApiKey(),
'SecretKey' => $this->getApiSecret()
));
// Log the response
$this->_log($mj);
// Check if the response is correct
if (!isset($response->Status) || (isset($response->Status) && $response->Status != 'ERROR')) {
$this->setToken($response);
$this->saveData();
}
return true;
}
public function __destruct()
{
$this->saveData();
}
private function _log($response)
{
$log = realpath(__DIR__.'/../tmp/log');
touch($log);
$delimiter = str_repeat('=', 100);
$content = file_get_contents($log);
$prepend = '';
$prepend .= $delimiter;
$prepend .= PHP_EOL;
$prepend .= date('Y-m-d H:i:s');
$prepend .= PHP_EOL;
$prepend .= 'RESPONSE';
$prepend .= PHP_EOL;
$prepend .= print_r($response, true);
$prepend .= PHP_EOL;
$content = $prepend.$content;
file_put_contents($log, $content);
}
}
?>PK ["]X�k�� � random_bytes_mcrypt.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* Powered by ext/mcrypt (and thankfully NOT libmcrypt)
*
* @ref https://bugs.php.net/bug.php?id=55169
* @ref https://github.com/php/php-src/blob/c568ffe5171d942161fc8dda066bce844bdef676/ext/mcrypt/mcrypt.c#L1321-L1386
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
$buf = @mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
if (
$buf !== false
&&
RandomCompat_strlen($buf) === $bytes
) {
/**
* Return our random entropy buffer here:
*/
return $buf;
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}
PK ["]���| | error_polyfill.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!class_exists('Error', false)) {
// We can't really avoid making this extend Exception in PHP 5.
class Error extends Exception
{
}
}
if (!class_exists('TypeError', false)) {
if (is_subclass_of('Error', 'Exception')) {
class TypeError extends Error
{
}
} else {
class TypeError extends Exception
{
}
}
}
PK ["]��� random_bytes_libsodium.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* If the libsodium PHP extension is loaded, we'll use it above any other
* solution.
*
* libsodium-php project:
* @ref https://github.com/jedisct1/libsodium-php
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/**
* \Sodium\randombytes_buf() doesn't allow more than 2147483647 bytes to be
* generated in one invocation.
*/
if ($bytes > 2147483647) {
$buf = '';
for ($i = 0; $i < $bytes; $i += 1073741824) {
$n = ($bytes - $i) > 1073741824
? 1073741824
: $bytes - $i;
$buf .= \Sodium\randombytes_buf($n);
}
} else {
$buf = \Sodium\randombytes_buf($bytes);
}
if ($buf !== false) {
if (RandomCompat_strlen($buf) === $bytes) {
return $buf;
}
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}
PK ["].�_�R R random_bytes_com_dotnet.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* Windows with PHP < 5.3.0 will not have the function
* openssl_random_pseudo_bytes() available, so let's use
* CAPICOM to work around this deficiency.
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
$buf = '';
if (!class_exists('COM')) {
throw new Error(
'COM does not exist'
);
}
$util = new COM('CAPICOM.Utilities.1');
$execCount = 0;
/**
* Let's not let it loop forever. If we run N times and fail to
* get N bytes of random data, then CAPICOM has failed us.
*/
do {
$buf .= base64_decode($util->GetRandom($bytes, 0));
if (RandomCompat_strlen($buf) >= $bytes) {
/**
* Return our random entropy buffer here:
*/
return RandomCompat_substr($buf, 0, $bytes);
}
++$execCount;
} while ($execCount < $bytes);
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}
PK ["]�
�U U byte_safe_strings.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('RandomCompat_strlen')) {
if (
defined('MB_OVERLOAD_STRING') &&
ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING
) {
/**
* strlen() implementation that isn't brittle to mbstring.func_overload
*
* This version uses mb_strlen() in '8bit' mode to treat strings as raw
* binary rather than UTF-8, ISO-8859-1, etc
*
* @param string $binary_string
*
* @throws TypeError
*
* @return int
*/
function RandomCompat_strlen($binary_string)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_strlen() expects a string'
);
}
return (int) mb_strlen($binary_string, '8bit');
}
} else {
/**
* strlen() implementation that isn't brittle to mbstring.func_overload
*
* This version just used the default strlen()
*
* @param string $binary_string
*
* @throws TypeError
*
* @return int
*/
function RandomCompat_strlen($binary_string)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_strlen() expects a string'
);
}
return (int) strlen($binary_string);
}
}
}
if (!is_callable('RandomCompat_substr')) {
if (
defined('MB_OVERLOAD_STRING')
&&
ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING
) {
/**
* substr() implementation that isn't brittle to mbstring.func_overload
*
* This version uses mb_substr() in '8bit' mode to treat strings as raw
* binary rather than UTF-8, ISO-8859-1, etc
*
* @param string $binary_string
* @param int $start
* @param int $length (optional)
*
* @throws TypeError
*
* @return string
*/
function RandomCompat_substr($binary_string, $start, $length = null)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_substr(): First argument should be a string'
);
}
if (!is_int($start)) {
throw new TypeError(
'RandomCompat_substr(): Second argument should be an integer'
);
}
if ($length === null) {
/**
* mb_substr($str, 0, NULL, '8bit') returns an empty string on
* PHP 5.3, so we have to find the length ourselves.
*/
$length = RandomCompat_strlen($binary_string) - $start;
} elseif (!is_int($length)) {
throw new TypeError(
'RandomCompat_substr(): Third argument should be an integer, or omitted'
);
}
// Consistency with PHP's behavior
if ($start === RandomCompat_strlen($binary_string) && $length === 0) {
return '';
}
if ($start > RandomCompat_strlen($binary_string)) {
return '';
}
return (string) mb_substr($binary_string, $start, $length, '8bit');
}
} else {
/**
* substr() implementation that isn't brittle to mbstring.func_overload
*
* This version just uses the default substr()
*
* @param string $binary_string
* @param int $start
* @param int $length (optional)
*
* @throws TypeError
*
* @return string
*/
function RandomCompat_substr($binary_string, $start, $length = null)
{
if (!is_string($binary_string)) {
throw new TypeError(
'RandomCompat_substr(): First argument should be a string'
);
}
if (!is_int($start)) {
throw new TypeError(
'RandomCompat_substr(): Second argument should be an integer'
);
}
if ($length !== null) {
if (!is_int($length)) {
throw new TypeError(
'RandomCompat_substr(): Third argument should be an integer, or omitted'
);
}
return (string) substr($binary_string, $start, $length);
}
return (string) substr($binary_string, $start);
}
}
}
PK ["]|��2
2
random_bytes_openssl.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Since openssl_random_pseudo_bytes() uses openssl's
* RAND_pseudo_bytes() API, which has been marked as deprecated by the
* OpenSSL team, this is our last resort before failure.
*
* @ref https://www.openssl.org/docs/crypto/RAND_bytes.html
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/**
* $secure is passed by reference. If it's set to false, fail. Note
* that this will only return false if this function fails to return
* any data.
*
* @ref https://github.com/paragonie/random_compat/issues/6#issuecomment-119564973
*/
$secure = true;
/**
* @var string
*/
$buf = openssl_random_pseudo_bytes($bytes, $secure);
if (
is_string($buf)
&&
$secure
&&
RandomCompat_strlen($buf) === $bytes
) {
return $buf;
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
PK ["]�!�ro o random_int.phpnu &1i� <?php
if (!is_callable('random_int')) {
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Fetch a random integer between $min and $max inclusive
*
* @param int $min
* @param int $max
*
* @throws Exception
*
* @return int
*/
function random_int($min, $max)
{
/**
* Type and input logic checks
*
* If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
* (non-inclusive), it will sanely cast it to an int. If you it's equal to
* ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
* lose precision, so the <= and => operators might accidentally let a float
* through.
*/
try {
$min = RandomCompat_intval($min);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $min must be an integer'
);
}
try {
$max = RandomCompat_intval($max);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $max must be an integer'
);
}
/**
* Now that we've verified our weak typing system has given us an integer,
* let's validate the logic then we can move forward with generating random
* integers along a given range.
*/
if ($min > $max) {
throw new Error(
'Minimum value must be less than or equal to the maximum value'
);
}
if ($max === $min) {
return $min;
}
/**
* Initialize variables to 0
*
* We want to store:
* $bytes => the number of random bytes we need
* $mask => an integer bitmask (for use with the &) operator
* so we can minimize the number of discards
*/
$attempts = $bits = $bytes = $mask = $valueShift = 0;
/**
* At this point, $range is a positive number greater than 0. It might
* overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to
* a float and we will lose some precision.
*/
$range = $max - $min;
/**
* Test for integer overflow:
*/
if (!is_int($range)) {
/**
* Still safely calculate wider ranges.
* Provided by @CodesInChaos, @oittaa
*
* @ref https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435
*
* We use ~0 as a mask in this case because it generates all 1s
*
* @ref https://eval.in/400356 (32-bit)
* @ref http://3v4l.org/XX9r5 (64-bit)
*/
$bytes = PHP_INT_SIZE;
$mask = ~0;
} else {
/**
* $bits is effectively ceil(log($range, 2)) without dealing with
* type juggling
*/
while ($range > 0) {
if ($bits % 8 === 0) {
++$bytes;
}
++$bits;
$range >>= 1;
$mask = $mask << 1 | 1;
}
$valueShift = $min;
}
$val = 0;
/**
* Now that we have our parameters set up, let's begin generating
* random integers until one falls between $min and $max
*/
do {
/**
* The rejection probability is at most 0.5, so this corresponds
* to a failure probability of 2^-128 for a working RNG
*/
if ($attempts > 128) {
throw new Exception(
'random_int: RNG is broken - too many rejections'
);
}
/**
* Let's grab the necessary number of random bytes
*/
$randomByteString = random_bytes($bytes);
/**
* Let's turn $randomByteString into an integer
*
* This uses bitwise operators (<< and |) to build an integer
* out of the values extracted from ord()
*
* Example: [9F] | [6D] | [32] | [0C] =>
* 159 + 27904 + 3276800 + 201326592 =>
* 204631455
*/
$val &= 0;
for ($i = 0; $i < $bytes; ++$i) {
$val |= ord($randomByteString[$i]) << ($i * 8);
}
/**
* Apply mask
*/
$val &= $mask;
$val += $valueShift;
++$attempts;
/**
* If $val overflows to a floating point number,
* ... or is larger than $max,
* ... or smaller than $min,
* then try again.
*/
} while (!is_int($val) || $val > $max || $val < $min);
return (int)$val;
}
}
PK ["]n��k� � random_bytes_dev_urandom.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
define('RANDOM_COMPAT_READ_BUFFER', 8);
}
if (!is_callable('random_bytes')) {
/**
* Unless open_basedir is enabled, use /dev/urandom for
* random numbers in accordance with best practices
*
* Why we use /dev/urandom and not /dev/random
* @ref http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
static $fp = null;
/**
* This block should only be run once
*/
if (empty($fp)) {
/**
* We use /dev/urandom if it is a char device.
* We never fall back to /dev/random
*/
$fp = fopen('/dev/urandom', 'rb');
if (!empty($fp)) {
$st = fstat($fp);
if (($st['mode'] & 0170000) !== 020000) {
fclose($fp);
$fp = false;
}
}
if (!empty($fp)) {
/**
* stream_set_read_buffer() does not exist in HHVM
*
* If we don't set the stream's read buffer to 0, PHP will
* internally buffer 8192 bytes, which can waste entropy
*
* stream_set_read_buffer returns 0 on success
*/
if (function_exists('stream_set_read_buffer')) {
stream_set_read_buffer($fp, RANDOM_COMPAT_READ_BUFFER);
}
if (function_exists('stream_set_chunk_size')) {
stream_set_chunk_size($fp, RANDOM_COMPAT_READ_BUFFER);
}
}
}
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/**
* This if() block only runs if we managed to open a file handle
*
* It does not belong in an else {} block, because the above
* if (empty($fp)) line is logic that should only be run once per
* page load.
*/
if (!empty($fp)) {
$remaining = $bytes;
$buf = '';
/**
* We use fread() in a loop to protect against partial reads
*/
do {
$read = fread($fp, $remaining);
if ($read === false) {
/**
* We cannot safely read from the file. Exit the
* do-while loop and trigger the exception condition
*/
$buf = false;
break;
}
/**
* Decrease the number of bytes returned from remaining
*/
$remaining -= RandomCompat_strlen($read);
$buf .= $read;
} while ($remaining > 0);
/**
* Is our result valid?
*/
if ($buf !== false) {
if (RandomCompat_strlen($buf) === $bytes) {
/**
* Return our random entropy buffer here:
*/
return $buf;
}
}
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Error reading from source device'
);
}
}
PK ["]E�w�P P
random.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* @version 1.4.3
* @released 2018-04-04
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!defined('PHP_VERSION_ID')) {
// This constant was introduced in PHP 5.2.7
$RandomCompatversion = array_map('intval', explode('.', PHP_VERSION));
define(
'PHP_VERSION_ID',
$RandomCompatversion[0] * 10000
+ $RandomCompatversion[1] * 100
+ $RandomCompatversion[2]
);
$RandomCompatversion = null;
}
/**
* PHP 7.0.0 and newer have these functions natively.
*/
if (PHP_VERSION_ID >= 70000) {
return;
}
if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
define('RANDOM_COMPAT_READ_BUFFER', 8);
}
$RandomCompatDIR = dirname(__FILE__);
require_once $RandomCompatDIR . '/byte_safe_strings.php';
require_once $RandomCompatDIR . '/cast_to_int.php';
require_once $RandomCompatDIR . '/error_polyfill.php';
if (!is_callable('random_bytes')) {
/**
* PHP 5.2.0 - 5.6.x way to implement random_bytes()
*
* We use conditional statements here to define the function in accordance
* to the operating environment. It's a micro-optimization.
*
* In order of preference:
* 1. Use libsodium if available.
* 2. fread() /dev/urandom if available (never on Windows)
* 3. mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)
* 4. COM('CAPICOM.Utilities.1')->GetRandom()
*
* See RATIONALE.md for our reasoning behind this particular order
*/
if (extension_loaded('libsodium')) {
// See random_bytes_libsodium.php
if (PHP_VERSION_ID >= 50300 && is_callable('\\Sodium\\randombytes_buf')) {
require_once $RandomCompatDIR . '/random_bytes_libsodium.php';
} elseif (method_exists('Sodium', 'randombytes_buf')) {
require_once $RandomCompatDIR . '/random_bytes_libsodium_legacy.php';
}
}
/**
* Reading directly from /dev/urandom:
*/
if (DIRECTORY_SEPARATOR === '/') {
// DIRECTORY_SEPARATOR === '/' on Unix-like OSes -- this is a fast
// way to exclude Windows.
$RandomCompatUrandom = true;
$RandomCompat_basedir = ini_get('open_basedir');
if (!empty($RandomCompat_basedir)) {
$RandomCompat_open_basedir = explode(
PATH_SEPARATOR,
strtolower($RandomCompat_basedir)
);
$RandomCompatUrandom = (array() !== array_intersect(
array('/dev', '/dev/', '/dev/urandom'),
$RandomCompat_open_basedir
));
$RandomCompat_open_basedir = null;
}
if (
!is_callable('random_bytes')
&&
$RandomCompatUrandom
&&
@is_readable('/dev/urandom')
) {
// Error suppression on is_readable() in case of an open_basedir
// or safe_mode failure. All we care about is whether or not we
// can read it at this point. If the PHP environment is going to
// panic over trying to see if the file can be read in the first
// place, that is not helpful to us here.
// See random_bytes_dev_urandom.php
require_once $RandomCompatDIR . '/random_bytes_dev_urandom.php';
}
// Unset variables after use
$RandomCompat_basedir = null;
} else {
$RandomCompatUrandom = false;
}
/**
* mcrypt_create_iv()
*
* We only want to use mcypt_create_iv() if:
*
* - random_bytes() hasn't already been defined
* - the mcrypt extensions is loaded
* - One of these two conditions is true:
* - We're on Windows (DIRECTORY_SEPARATOR !== '/')
* - We're not on Windows and /dev/urandom is readabale
* (i.e. we're not in a chroot jail)
* - Special case:
* - If we're not on Windows, but the PHP version is between
* 5.6.10 and 5.6.12, we don't want to use mcrypt. It will
* hang indefinitely. This is bad.
* - If we're on Windows, we want to use PHP >= 5.3.7 or else
* we get insufficient entropy errors.
*/
if (
!is_callable('random_bytes')
&&
// Windows on PHP < 5.3.7 is broken, but non-Windows is not known to be.
(DIRECTORY_SEPARATOR === '/' || PHP_VERSION_ID >= 50307)
&&
// Prevent this code from hanging indefinitely on non-Windows;
// see https://bugs.php.net/bug.php?id=69833
(
DIRECTORY_SEPARATOR !== '/' ||
(PHP_VERSION_ID <= 50609 || PHP_VERSION_ID >= 50613)
)
&&
extension_loaded('mcrypt')
) {
// See random_bytes_mcrypt.php
require_once $RandomCompatDIR . '/random_bytes_mcrypt.php';
}
$RandomCompatUrandom = null;
/**
* This is a Windows-specific fallback, for when the mcrypt extension
* isn't loaded.
*/
if (
!is_callable('random_bytes')
&&
extension_loaded('com_dotnet')
&&
class_exists('COM')
) {
$RandomCompat_disabled_classes = preg_split(
'#\s*,\s*#',
strtolower(ini_get('disable_classes'))
);
if (!in_array('com', $RandomCompat_disabled_classes)) {
try {
$RandomCompatCOMtest = new COM('CAPICOM.Utilities.1');
if (method_exists($RandomCompatCOMtest, 'GetRandom')) {
// See random_bytes_com_dotnet.php
require_once $RandomCompatDIR . '/random_bytes_com_dotnet.php';
}
} catch (com_exception $e) {
// Don't try to use it.
}
}
$RandomCompat_disabled_classes = null;
$RandomCompatCOMtest = null;
}
/**
* openssl_random_pseudo_bytes()
*/
if (
(
// Unix-like with PHP >= 5.3.0 or
(
DIRECTORY_SEPARATOR === '/'
&&
PHP_VERSION_ID >= 50300
)
||
// Windows with PHP >= 5.4.1
PHP_VERSION_ID >= 50401
)
&&
!function_exists('random_bytes')
&&
extension_loaded('openssl')
) {
// See random_bytes_openssl.php
require_once $RandomCompatDIR . '/random_bytes_openssl.php';
}
/**
* throw new Exception
*/
if (!is_callable('random_bytes')) {
/**
* We don't have any more options, so let's throw an exception right now
* and hope the developer won't let it fail silently.
*
* @param mixed $length
* @return void
* @throws Exception
*/
function random_bytes($length)
{
unset($length); // Suppress "variable not used" warnings.
throw new Exception(
'There is no suitable CSPRNG installed on your system'
);
}
}
}
if (!is_callable('random_int')) {
require_once $RandomCompatDIR . '/random_int.php';
}
$RandomCompatDIR = null;
PK ["]�t��
cast_to_int.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('RandomCompat_intval')) {
/**
* Cast to an integer if we can, safely.
*
* If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
* (non-inclusive), it will sanely cast it to an int. If you it's equal to
* ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
* lose precision, so the <= and => operators might accidentally let a float
* through.
*
* @param int|float $number The number we want to convert to an int
* @param boolean $fail_open Set to true to not throw an exception
*
* @return float|int
*
* @throws TypeError
*/
function RandomCompat_intval($number, $fail_open = false)
{
if (is_int($number) || is_float($number)) {
$number += 0;
} elseif (is_numeric($number)) {
$number += 0;
}
if (
is_float($number)
&&
$number > ~PHP_INT_MAX
&&
$number < PHP_INT_MAX
) {
$number = (int) $number;
}
if (is_int($number)) {
return (int) $number;
} elseif (!$fail_open) {
throw new TypeError(
'Expected an integer.'
);
}
return $number;
}
}
PK ["]c/
M= = ! random_bytes_libsodium_legacy.phpnu &1i� <?php
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
if (!is_callable('random_bytes')) {
/**
* If the libsodium PHP extension is loaded, we'll use it above any other
* solution.
*
* libsodium-php project:
* @ref https://github.com/jedisct1/libsodium-php
*
* @param int $bytes
*
* @throws Exception
*
* @return string
*/
function random_bytes($bytes)
{
try {
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/**
* @var string
*/
$buf = '';
/**
* \Sodium\randombytes_buf() doesn't allow more than 2147483647 bytes to be
* generated in one invocation.
*/
if ($bytes > 2147483647) {
for ($i = 0; $i < $bytes; $i += 1073741824) {
$n = ($bytes - $i) > 1073741824
? 1073741824
: $bytes - $i;
$buf .= Sodium::randombytes_buf($n);
}
} else {
$buf .= Sodium::randombytes_buf($bytes);
}
if (is_string($buf)) {
if (RandomCompat_strlen($buf) === $bytes) {
return $buf;
}
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}
PK Ǿ!]� �O �O lib/mailjet-api-strategy.phpnu &1i� PK Ǿ!]��7�o o �O lib/api/mailjet-api-v3.phpnu &1i� PK Ǿ!]�NH� :� lib/api/mailjet-api-v1.phpnu &1i� PK Ǿ!]� �� lib/Auth.phpnu &1i� PK Ǿ!]��֠< < �� hook.phpnu &1i� PK Ǿ!]��l�� �
X� config.phpnu &1i� PK Ǿ!]T� �� �� *� tmp/lognu &1i� PK Ǿ!]�#L� � � exit.phpnu &1i� PK Ǿ!]�(�z� � 9� db/datanu &1i� PK S"]� �O �O � mailjet-api-strategy.phpnu &1i� PK S"]��7�o o �� api/mailjet-api-v3.phpnu &1i� PK S"]�NH� CD api/mailjet-api-v1.phpnu &1i� PK S"]� �] Auth.phpnu &1i� PK ["]X�k�� � �y random_bytes_mcrypt.phpnu &1i� PK ["]���| | � error_polyfill.phpnu &1i� PK ["]��� �� random_bytes_libsodium.phpnu &1i� PK ["].�_�R R � random_bytes_com_dotnet.phpnu &1i� PK ["]�
�U U �� byte_safe_strings.phpnu &1i� PK ["]|��2
2
N� random_bytes_openssl.phpnu &1i� PK ["]�!�ro o �� random_int.phpnu &1i� PK ["]n��k� � u� random_bytes_dev_urandom.phpnu &1i� PK ["]E�w�P P
K� random.phpnu &1i� PK ["]�t��
� cast_to_int.phpnu &1i� PK ["]c/
M= = ! ) random_bytes_libsodium_legacy.phpnu &1i� PK � �&