Initial Commit

This commit is contained in:
GiacomoHome
2021-09-17 12:41:45 +02:00
commit 9001e4656e
570 changed files with 31013 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
<?php
class App_Service_Auth
{
protected $_auth;
protected $_configs;
protected $_acl;
public function __construct()
{
$this->_configs = new App_Service_ConfigManager();
$this->_acl = new App_Model_Acl_Acl();
}
public function authenticate($credentials)
{
$adapter = $this->getAuthAdapter($credentials);
$auth = $this->getAuth();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
return false;
}
$user = $adapter->getResultRowObject();
Zend_Registry::set("username",$user->username);
Zend_Registry::set("role",$user->role);
$auth->getStorage()->write($user);
return true;
}
public function getAuth()
{
if (null === $this->_auth) {
$this->_auth = Zend_Auth::getInstance();
}
return $this->_auth;
}
public function getIdentity()
{
$auth = $this->getAuth();
if ($auth->hasIdentity()) {
return $auth->getIdentity();
}
return false;
}
public function checkPermission($resourceName){
return $this->_acl->isAllowed($this->getIdentity()->role, $resourceName);
}
public function clear()
{
$this->getAuth()->clearIdentity();
}
public function getAuthAdapter($values)
{
$salt = Zend_Registry::get('ENVIROMENTS')->get('password_salt');
$authAdapter = new Zend_Auth_Adapter_DbTable(
Zend_Db_Table_Abstract::getDefaultAdapter(),
'users',
'username',
'password',
"MD5(CONCAT('$salt',?))"
);
$authAdapter->setIdentity($values['username']);
$authAdapter->setCredential($values['password']);
return $authAdapter;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
class App_Service_CodificaPiva
{
public static function cripta($stringa,$maxPos = 11)
{
$pos = rand(1,$maxPos);
$strCript = str_pad(($pos * 17), 4, '0', STR_PAD_LEFT);
for($i = 0;$i < strlen($stringa); $i++){
$charpos = $i+1;
if($charpos < $pos){
$strCript .= str_pad((intval(substr($stringa,$i,1)) * $charpos * 5 + 17), 4, '0', STR_PAD_LEFT);
}else{
$strCript .= str_pad((intval(substr($stringa,$i,1)) * $charpos * 3 + 177), 4, '0', STR_PAD_LEFT);
}
}
return $strCript;
}
public static function decripta($stringa)
{
$packs = str_split($stringa, 4);
$pos = $packs[0] / 17;
unset($packs[0]);
$strDecript = "";
for($i = 1;$i <= count($packs); $i++){
if($i < $pos){
$strDecript .= ($packs[$i] - 17) / $i / 5;
}else{
$strDecript .= ($packs[$i] - 177) / $i / 3;
}
}
return $strDecript;
}
public static function criptaHex($stringa,$maxPos = 11)
{
$pos = rand(1,$maxPos);
$strCript = str_pad(($pos * 17), 4, '0', STR_PAD_LEFT);
for($i = 0;$i < strlen($stringa); $i++){
$charpos = $i+1;
if($charpos < $pos){
$strCript .= str_pad((ord(substr($stringa,$i,1)) + $charpos + 17), 3, '0', STR_PAD_LEFT);
}else{
$strCript .= str_pad((ord(substr($stringa,$i,1)) + $charpos + 177), 3, '0', STR_PAD_LEFT);
}
}
return base64_encode($strCript);
}
public static function decriptaHex($stringa)
{
$stringa = base64_decode($stringa);
$pos = substr($stringa,0,4) / 17;
$packs = str_split(substr($stringa,4), 3);
$strDecript = "";
for($i = 0;$i < count($packs); $i++){
$charpos = $i+1;
if($charpos < $pos){
//echo "<br>".intval($packs[$i]) . "-$charpos-17=$x";
$strDecript .= chr(intval($packs[$i]) - $charpos - 17);
}else{
//echo "<br>".intval($packs[$i]) . "-$charpos-177=$x";
$strDecript .= chr(intval($packs[$i]) - $charpos - 177);
}
}
return $strDecript;
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
class App_Service_ConfigManager
{
protected $_config;
protected $_writer;
protected $_ipManager;
public function __construct()
{
$this->_config = Zend_Registry::get('config');
$this->_writer = new Zend_Config_Writer_Ini(array('config'=> $this->_config,'filename' => APPLICATION_PATH.'/configs/config.ini'));
$this->_ipManager = new App_Service_IpManager();
}
/**
* Aggiorna l'oggetto config ricaricando tutte le impostazioni memorizzate
* nel file config.ini
*/
public function update()
{
$this->_config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini', null, array('skipExtends'=> true,
'allowModifications' => true));
Zend_Registry::set('config',$this->_config);
}
/**
* Inserisci nel file di configurazione il parametro passato memorizzandolo
*
* @param string $param
* @param string $value
* @return void
*/
public function insert($param,$value)
{
if($param==null||$param==''){
return;
}
$this->_config->__set($param, $value);
$this->write();
}
public function set($key,$value){
$this->_config->__set($key, $value);
}
/**
* Restituisce il valore del parametro richiesto
*
* @param string $name
* @return string
*/
public function get($name){
return $this->_config->get($name);
}
/**
* Elimina il parametro richiesto se esistente
*
* @param string $param
* @return boolean
*/
public function delete($param){
if($this->_config->get($param)){
$this->_config->__unset($param);
$this->write();
return TRUE;
}else{
return FALSE;
}
}
public function write(){
$this->_writer->config=$this->_config;
$this->_writer->write();
$this->update();
}
public function getAllParam(){
$data=array();
foreach ($this->_config as $key => $value) {
$data[$key]=$value;
}
return $data;
}
}
+157
View File
@@ -0,0 +1,157 @@
<?php
class App_Service_Cpanel
{
protected $_configs;
protected $_enviroments;
protected $_cpanelApi;
protected $_CPANEL_USERNAME;
protected $_CPANEL_PASSWORD;
protected $_RESTUSERNAME;
protected $_CPANEL_HOST;
private $_cronCommandBase = '/usr/bin/lynx -source %baseUrlSite%/v1/services/m/send-emails-sync &> /dev/null';
public function __construct()
{
$this->_configs = Zend_Registry::get('config');
$this->_enviroments = Zend_Registry::get('ENVIROMENTS');
$this->_cronCommandBase = str_replace('%baseUrlSite%', $this->_enviroments->get('baseUrlSite'), $this->_cronCommandBase);
$this->_CPANEL_HOST = $this->_enviroments->get('cpanel')->get('host');
$this->_CPANEL_USERNAME = $this->_enviroments->get('cpanel')->get('username');
$this->_CPANEL_PASSWORD = $this->_enviroments->get('cpanel')->get('password');
$this->_RESTUSERNAME = $this->_enviroments->get('cpanel')->get('restusername');
$this->_cpanelApi = new App_Service_CpanelApi($this->_CPANEL_USERNAME, $this->_CPANEL_PASSWORD, $this->_CPANEL_HOST);
}
public function listCron()
{
try {
$res = $this->_cpanelApi->api2->Cron->listcron();
if ($res->errors) {
if (is_array($res->errors))
return implode(';', $res->errors);
else
return "ERRORE: richiesta elenco funzioni cron --- " . $res->errors;
}
return $res;
} catch (Exception $e) {
return $e;
}
}
public function attivaFunzioneCron()
{
try {
$res = $this->_cpanelApi->api2->Cron->add_line(array(
'command' => $this->_cronCommandBase,
'day' => '*',
'hour' => '*',
'minute' => '*/2', // Una volta ogni due minuti
'month' => '*',
'weekday' => '*',
));
if ($res->errors) {
if (is_array($res->errors))
return implode(';', $res->errors);
else
return "ERRORE: attivazione cron sync ordini --- " . $res->errors;
}
$data = $res->cpanelresult->data[0];
if($data->status == 1){
return ['stato'=>true,'message'=>'Sincronizzazione attivata'];
}elseif($data->status === 0 && $data->statusmsg == "This cron job already exists.") {
return ['stato'=>true,'message'=>'Sincronizzazione già attiva'];
}else{
return ['stato'=>false,'message'=>'Errore durante l\'operazione di sincronizzazione'];
}
} catch (Exception $e) {
return $e;
}
}
public function disattivaFunzioneCron()
{
try {
$res = null;
$cronList = $this->listCron();
$x = 0;
foreach ($cronList->cpanelresult->data as $cron) {
$x++;
if ($cron->command === $this->_cronCommandBase) {
$res = $this->removeCron($x);
}
}
$data = $res->cpanelresult->data[0];
if($data !== null && $data->status === 1){
return ['stato'=>false,'message'=>'Sincronizzazione disattivata'];
}else{
return ['stato'=>false,'message'=>'Sincronizzazione non attiva'];
}
} catch (Exception $e) {
return $e;
}
}
public function removeCron($lineKey)
{
try {
$res = $this->_cpanelApi->api2->Cron->remove_line(array('line' => $lineKey));
if ($res->errors) {
if (is_array($res->errors))
return implode(';', $res->errors);
else
return "ERRORE: rimozione funzione cron --- " . $res->errors;
}
return $res;
} catch (Exception $e) {
return $e;
}
}
public function checkFunzioneCronIsActive()
{
try {
$listCron = $this->listCron();
foreach ($listCron->cpanelresult->data as $cron){
if($cron->command === $this->_cronCommandBase) return true;
}
return false;
} catch (Exception $e) {
return $e;
}
}
}
+263
View File
@@ -0,0 +1,263 @@
<?php
/**
* PHP class to handle connections with cPanel's UAPI and API2 specifically through cURL requests as seamlessly and simply as possible.
*
* For documentation on cPanel's UAPI:
* @see https://documentation.cpanel.net/display/SDK/UAPI+Functions
*
* For documentation on cPanel's API2:
* @see https://documentation.cpanel.net/display/SDK/Guide+to+cPanel+API+2
*
* Please use UAPI where possible, only use API2 where the equivalent doesn't exist for UAPI
*
* @author Toby New - www.source-control.co.uk
* @copyright 2016 N1ghteyes
* @license license.txt The MIT License (MIT)
* @link https://github.com/N1ghteyes/cpanel-UAPI-php-class
*
* @todo - im sure there is a lot that can be improved here
*/
/**
* Class cPanelAPI
*/
class App_Service_CpanelApi
{
public $version = '2.0';
public $ssl = 1; //Bool - TRUE / FALSE for ssl connection
public $port = 2083; //default for ssl servers.
public $server;
public $maxredirect = 0; //Number of redirects to make, typically 0 is fine. on some shared setups this will need to be increased.
public $user;
public $json = '';
protected $scope; //String - Module we want to use
protected $api;
protected $auth;
protected $pass;
protected $secret;
protected $type;
protected $session;
protected $method;
protected $requestUrl;
protected $eno;
protected $emes;
protected $token = FALSE;
protected $httpMethod = 'GET';
protected $postData = '';
/**
* @param $user
* @param $pass
* @param $server
* @param $secret
*/
function __construct($user, $pass, $server, $secret = FALSE)
{
$this->user = $user;
$this->pass = $pass;
$this->server = $server;
if ($this->secret) {
$this->secret = $secret;
$this->set2Fa();
}
}
/**
* Include the ot class so we can generate a valid token for 2FA
*/
protected function set2Fa()
{
require 'otphp/lib/otphp.php';
$totp = new \OTPHP\TOTP($this->secret);
$this->token = $totp->now();
}
public function __get($name)
{
switch (strtolower($name)) {
case 'get':
$this->httpMethod = 'GET';
break;
case 'post':
$this->httpMethod = 'POST';
break;
case 'api2':
$this->setApi('api2');
break;
case 'uapi':
$this->setApi('uapi');
break;
default:
$this->scope = $name;
}
return $this;
}
/**
* Set the api to use for connections.
* @param $api
* @return $this
* @throws Exception
*/
protected function setApi($api)
{
$this->api = $api;
$this->setMethod();
return $this;
}
/**
* Function to set the method used to communicate with the chosen api.
* @return $this
* @throws Exception
*/
protected function setMethod()
{
switch ($this->api) {
case 'uapi':
$this->method = '/execute/';
break;
case 'api2':
$this->method = '/json-api/cpanel/';
break;
default:
throw new Exception('$this->api is not set or is incorrectly set. The only available options are \'uapi\' or \'api2\'');
}
return $this;
}
/**
* Magic __toSting() method, allows us to return the result as raw json
* @return mixed
*/
public function __toString()
{
return $this->json;
}
/**
* Magic __call method, will translate all function calls to object to API requests
* @param $name - name of the function
* @param $arguments - an array of arguments
* @return mixed
* @throws Exception
*/
public function __call($name, $arguments)
{
if (count($arguments) < 1 || !is_array($arguments[0]))
$arguments[0] = [];
$this->json = $this->APIcall($name, $arguments[0]);
return json_decode($this->json);
}
/**
* @param $name
* @param $arguments
* @return bool|mixed
* @throws Exception
*/
protected function APIcall($name, $arguments)
{
$this->auth = base64_encode($this->user . ":" . $this->pass);
$this->type = $this->ssl == 1 ? "https://" : "http://";
$this->requestUrl = $this->type . $this->server . ':' . $this->port . $this->method;
switch ($this->api) {
case 'uapi':
$this->requestUrl .= ($this->scope != '' ? $this->scope . "/" : '') . $name . '?';
break;
case 'api2':
if ($this->scope == '') {
throw new Exception('Scope must be set.');
}
$this->requestUrl .= '?cpanel_jsonapi_user=' . $this->user . '&cpanel_jsonapi_apiversion=2&cpanel_jsonapi_module=' . $this->scope . '&cpanel_jsonapi_func=' . $name . '&';
break;
default:
throw new Exception('$this->api is not set or is incorrectly set. The only available options are \'uapi\' or \'api2\'');
}
if($this->httpMethod == 'GET') {
$this->requestUrl .= http_build_query($arguments);
}
if($this->httpMethod == 'POST'){
$this->postData = $arguments;
}
return $this->curl_request($this->requestUrl);
}
/**
* @param $url
* @return bool|mixed
*/
protected function curl_request($url)
{
$httpHeaders = array("Authorization: Basic " . $this->auth);
//If we have a token then send that with the request for 2FA.
if ($this->token) {
$httpHeaders[] = "X-CPANEL-OTP: " . $this->token;
}
$ch = curl_init();
if($this->httpMethod == 'POST'){
$httpHeaders[] = "Content-type: multipart/form-data";
curl_setopt($ch,CURLOPT_POSTFIELDS, $this->postData);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
curl_setopt($ch, CURLOPT_TIMEOUT, 100020);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$content = $this->curl_exec_follow($ch, $this->maxredirect);
$this->eno = curl_errno($ch);
$this->emes = curl_error($ch);
curl_close($ch);
return $content;
}
/**
* @param $ch
* @param null $maxredirect
* @return bool|mixed
*/
protected function curl_exec_follow($ch, &$maxredirect = null)
{
// we emulate a browser here since some websites detect
// us as a bot and don't let us do our job
$user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5)" .
" Gecko/20041107 Firefox/1.0";
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
$mr = $maxredirect === null ? 5 : intval($maxredirect);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
return curl_exec($ch);
}
/**
* Function to get the last request made
* @return mixed
*/
public function getLastRequest()
{
return $this->requestUrl;
}
/**
* Function to return the error if there was one, or FALSE if not.
* @return array|bool
*/
public function getError()
{
if (!empty($this->eno)) {
return ['no' => $this->eno, 'message' => $this->emes];
}
return FALSE;
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
class App_Service_Emails
{
const EMAIL_TEMPLATE_PATH = APPLICATION_PATH . "/../emailtemplate/";
protected $_configs;
protected $_ipManager;
protected $_genericModel;
public function __construct()
{
$this->_configs = Zend_Registry::get('config');
$this->_ipManager = new App_Service_IpManager();
$this->_genericModel = new Application_Model_Generic();
}
public function sendEmailByTemplateHtml($email, $oggetto, $templateName, $params = array(), $nomeMittente = null, $filename = null)
{
$mail = new App_Model_Mail('UTF-8');
$templateFileName = self::EMAIL_TEMPLATE_PATH.$templateName;
if(!file_exists($templateFileName)){
throw new Exception("Email template non trovato impossibile inviare l'email");
}
$testoEmail = file_get_contents($templateFileName);
$params = $this->preparaDatiPerSostituzione($params);
if (count($params) > 0) {
foreach ($params as $key => $val) {
$oggetto = str_replace($key, $val, $oggetto);
$testoEmail = str_replace($key, $val, $testoEmail);
}
}
if ($filename != null) {
if (file_exists($filename))
$mail->createAttachment(file_get_contents($filename), 'application/pdf', Zend_Mime::DISPOSITION_ATTACHMENT, Zend_Mime::ENCODING_BASE64, $filename);
}
$nomeMittente = ($nomeMittente) ? $nomeMittente : $this->_configs->get('email_mittente_nome');
$mail->setFrom('noreply@fatturab2b.net', $nomeMittente)->setSubject($oggetto);
$mail->setBodyHtml($testoEmail);
//Inserisco il o i destinatari/o
if (is_string($email)) {
$mail->addTo($email, $email);
} else if (is_array($email)) {
foreach ($email as $val) {
$mail->addTo($val);
}
}
$mail->send();
}
/**
* Questa funzione presi i parametri passati nell array ne aggiunge i simboli
* percentuale per farli riconoscere popi nel testo e sostituirli
* @param $dati
* @return array
*/
private function preparaDatiPerSostituzione($dati){
$newParams = array();
foreach($dati as $key => $val){
$newParams['%'.$key.'%'] = $val;
}
return $newParams;
}
}
+119
View File
@@ -0,0 +1,119 @@
<?php
class App_Service_ExternalApiService
{
const API_TYPE_CHANGE_ORDER_STATUS = 'change_order_status';
protected $_httpClient;
protected $_configs;
protected $_ipManager;
protected $_genericModel;
protected $_endPoint;
protected $_authToken;
public function __construct()
{
$this->_configs = Zend_Registry::get('config');
$this->_ipManager = new App_Service_IpManager();
$this->_genericModel = new Application_Model_Generic();
$this->_httpClient = new Zend_Http_Client();
$this->_httpClient->setConfig(array(
'adapter' => 'Zend_Http_Client_Adapter_Curl',
'maxredirects' => 0,
'timeout' => 60,
'ssltransport' => 'ssl'
));
}
public function setConnectionParams($codiceAttivita, $tipoApi)
{
//Recupero se presenti i dati per la comunicazione con un eventuale endpoint
$api = $this->_genericModel->getFiltered('ExternalApi', array('CodiceAttivita = ?' => $codiceAttivita, 'TipoApi = ?' => $tipoApi, 'Attivo = ?' => 1));
if (!$api) {
$this->_authToken = null;
$this->_endPoint = null;
} else {
$this->_authToken = $api['AuthToken'];
$this->_endPoint = $api['Endpoint'];
}
}
public function checkConnectionParams()
{
if (!$this->_authToken || !$this->_endPoint) {
throw new App_Controller_Errors_WebServiceError('Parametri per la connessione non impostati correttamente', App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR);
}
}
public function postCall($dati = array())
{
$this->checkConnectionParams();
$this->_httpClient->setMethod('POST');
$this->_httpClient->setUri($this->_endPoint);
$this->_httpClient->setRawData(json_encode($dati), 'application/json;charset=utf-8');
return $this->executeCall();
}
public function putCall($dati = array())
{
$this->checkConnectionParams();
$this->_httpClient->setMethod('PUT');
$this->_httpClient->setUri($this->_endPoint);
$this->_httpClient->setRawData(json_encode($dati), 'application/json;charset=utf-8');
return $this->executeCall();
}
private function executeCall()
{
$this->_httpClient->setHeaders('Authorization', 'Secret ' . $this->_authToken);
if ($this->_ipManager->allowedDevMode()) {
$this->_httpClient->setHeaders('X-As-Dev-On', '1');
$this->_httpClient->setHeaders('X-As-Dev-Pw', 'JackDev2590');
}
$httpResponse = $this->_httpClient->request();
$httpResponse->getStatus();
$headerResponse = $httpResponse->getHeaders();
// Zend_Registry::get('log')->info(print_r($this->_httpClient->getLastRequest(),true));
// Zend_Registry::get('log')->info(print_r($this->_httpClient->getLastResponse(),true));
// Zend_Registry::get('log')->info(print_r($headerResponse,true));
// Zend_Registry::get('log')->info(print_r($httpResponse->getStatus(),true));
if (preg_match('/application\/json|json/', $headerResponse['Content-type'])) {
$httpResponseBody = json_decode($httpResponse->getBody(), 1);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new App_Controller_Errors_WebServiceError("Errore di decodifica json per la chiamata: " . $this->_httpClient->getUri(), App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR);
}
if ($httpResponse->getStatus() >= 400 && $httpResponse->getStatus() < 500) {
throw new App_Controller_Errors_WebServiceError($httpResponseBody['message'], App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR);
}
} else {
$httpResponseBody = $httpResponse->getBody();
}
return $httpResponseBody;
}
}
+345
View File
@@ -0,0 +1,345 @@
<?php
class App_Service_FatturaElettronica
{
protected $_soapClient;
protected $_ipManager;
private $_credenzialiUtente;
const TipiDocumentoFatturaElettronica = array(
'TD01' => array('Codice' => 'TD01', 'Descrizione' => 'Fattura'),
'TD02' => array('Codice' => 'TD02', 'Descrizione' => 'Acconto/Anticipo su fattura'),
'TD03' => array('Codice' => 'TD03', 'Descrizione' => 'Acconto/Anticipo su parcella'),
'TD04' => array('Codice' => 'TD04', 'Descrizione' => 'Nota di credito'),
'TD05' => array('Codice' => 'TD05', 'Descrizione' => 'Nota di debito'),
'TD06' => array('Codice' => 'TD06', 'Descrizione' => 'Parcella')
);
public function __construct()
{
$this->_ipManager = new App_Service_IpManager();
}
public function getCredenzialiUtente()
{
return $this->_credenzialiUtente;
}
public function setCredenzialiUtente($credenzialiUtente)
{
if (!isset($credenzialiUtente['CustomerCode'])) throw new Exception("Errore campo 'customerCode' non impostato nelle credenziali");
if (!isset($credenzialiUtente['Password'])) throw new Exception("Errore campo 'Password' non impostato nelle credenziali");
$this->_credenzialiUtente = $credenzialiUtente;
}
/************************ FUNZIONI FATTURE INVIATE ********************************************************/
public function verificaStatoServizioFeInviateServer()
{
$this->setCredenzialiUtente(array(
'CustomerCode' => '',
'Password' => ''
));
$this->_soapClient = new App_Service_SoapFeInviate($this->getCredenzialiUtente());
$result = $this->_soapClient->ContattoHub();
//Controllo eventuali errori sulla rispsota
if ($result->ContattoHubResult != '0') {
return false;
} else {
return true;
}
}
public function getFatturaInviata($idSdi){
$this->_soapClient = new App_Service_SoapFeInviate($this->getCredenzialiUtente());
$params = array(
'paramFilter' => array(
'IdSdi' => $idSdi,
'DataCustomerServicesConsumption' => false,
'DataFullInvoices' => true
));
$result = $this->_soapClient->GetElectronicInvoices($this->_soapClient->mergeParamsCredenziali($params));
//Controllo eventuali errori sulla rispsota
if ($result->GetElectronicInvoicesResult->ResultCode != 'Success') {
$this->SoapErrorResultHandler($result->GetElectronicInvoicesResult);
}
if (is_object($result->GetElectronicInvoicesResult->ElectronicInvoices->ElectronicInvoice)) {
$data = array(0 => (array)$result->GetElectronicInvoicesResult->ElectronicInvoices->ElectronicInvoice);
} elseif (is_array($result->GetElectronicInvoicesResult->ElectronicInvoices->ElectronicInvoice)) {
$data = $result->GetElectronicInvoicesResult->ElectronicInvoices->ElectronicInvoice;
} else {
$data = array();
}
// Zend_Registry::get('log')->info(print_r($this->_soapClient->getLastRequest(),true));
// Zend_Registry::get('log')->info(print_r($data,true));
return $data;
}
public function getEsitoFatturaInviata($idEsito, $tipoMessaggiOEsito, $getXmlData = false)
{
$this->_soapClient = new App_Service_SoapFeInviate($this->getCredenzialiUtente());
$params = array(
'paramFileOutcome' => array(
'IdOutcome' => $idEsito
));
$result = $this->_soapClient->GetFileElectronicInvoiceOutcome($this->_soapClient->mergeParamsCredenziali($params));
//Controllo eventuali errori sulla rispsota
if ($result->GetFileElectronicInvoiceOutcomeResult->ResultCode != 'Success') {
$this->SoapErrorResultHandler($result->GetFileElectronicInvoiceOutcomeResult);
}
$xmlCode = $result->GetFileElectronicInvoiceOutcomeResult->File;
$responseData = array(
'xmlFile' => $this->addXslTagToXml($xmlCode, $this->getXslByTipoMessaggioEsito($tipoMessaggiOEsito)),
'filename' => $result->GetFileElectronicInvoiceOutcomeResult->Filename
);
if ($getXmlData) {
$responseData['xmlData'] = simplexml_load_string($xmlCode);
}
return $responseData;
}
/**
* @param $idFatt - Id della fattura da recuparare dai server della 2C
* @param bool $xmlData - true: restiuisce i dati in formato xml della fattura elettronica | false: non li restituisce (DEFAULT: false)
* @param bool $onlyXmlData - restituisce solo i dati xml della fattura elettronica (DEFAULT: false)
* @param bool $fileFirmato - true: resituisce il file firmato .p7m (DEFAULT: false)
* @param bool $getXslProcessed - restituisce l'html della fattura elettronica elaborato con il foglio di stile (DEFAULT: false)
* @param string $xslFile - Indica il file del foglio di stile da utilizzare (DEFAULT: "fatturaordinaria_v1_2_1.xsl")
* @return array|bool|SimpleXMLElement
* @throws App_Controller_Errors_WebServiceError
* @throws Zend_Exception
*/
public function getFatturaInviataXml($idFatt, $xmlData = false, $onlyXmlData = false, $fileFirmato = false, $getXslProcessed = false, $xslFile = "fatturaordinaria_v1_2_1.xsl")
{
$this->_soapClient = new App_Service_SoapFeInviate($this->getCredenzialiUtente());
$params = array(
'paramFileInvoice' => array(
'IdInvoice' => $idFatt,
'ExtractionP7M' => !$fileFirmato
));
$result = $this->_soapClient->GetFileElectronicInvoice($this->_soapClient->mergeParamsCredenziali($params));
Zend_Registry::get('log')->info(print_r($result,true));
//Controllo eventuali errori sulla rispsota
if ($result->GetFileElectronicInvoiceResult->ResultCode != 'Success') {
$this->SoapErrorResultHandler($result->GetFileElectronicInvoiceResult);
}
if ($xmlData && !$fileFirmato) {
$xmlData = simplexml_load_string($result->GetFileElectronicInvoiceResult->File);
//Elimino eventuali allegati dall'xml data per non appesantire la chiamata
foreach ($xmlData->FatturaElettronicaBody as $body) {
if (isset($body->Allegati)) {
foreach ($body->Allegati as $allegato) {
unset($allegato->Attachment);
}
}
}
}
if (!$fileFirmato)
$filename = $xmlData->FatturaElettronicaHeader->DatiTrasmissione->IdTrasmittente->IdPaese . $xmlData->FatturaElettronicaHeader->DatiTrasmissione->IdTrasmittente->IdCodice . '_' . $xmlData->FatturaElettronicaHeader->DatiTrasmissione->ProgressivoInvio . ".xml";
else
$filename = $result->GetFileElectronicInvoiceResult->Filename;
if ($onlyXmlData && !$getXslProcessed) {
return $xmlData;
}
if ($getXslProcessed) {
$tipoFattura = self::TipiDocumentoFatturaElettronica[$xmlData->FatturaElettronicaBody->DatiGenerali->DatiGeneraliDocumento->TipoDocumento . ""];
$dataDocumento = implode('/', array_reverse(explode("-", $xmlData->FatturaElettronicaBody->DatiGenerali->DatiGeneraliDocumento->Data . "")));
$nomeFileFattura = $tipoFattura['Descrizione'] . " " . $xmlData->FatturaElettronicaBody->DatiGenerali->DatiGeneraliDocumento->Numero . " del " . $dataDocumento;
return array(
'htmlProcessed' => $this->getXslCodeProcessed($result->GetFileElectronicInvoiceResult->File, $xslFile),
'Filename' => $nomeFileFattura
);
}
//Se il file è firmato (p7m) allora non elaboro il file xml per aggiungere il foglio di stile altrimenti si
$elaboraXml = !preg_match('/.p7m/', $filename);
if ($elaboraXml) {
$file = $this->addXslTagToXml($result->GetFileElectronicInvoiceResult->File, $xslFile);
$allegati = $this->estraiAllegatoDaXml($result->GetFileElectronicInvoiceResult->File);
} else {
$file = $result->GetFileElectronicInvoiceResult->File;
$allegati = array();
}
return array(
'File' => $file,
'Filename' => $filename,
'XmlData' => $xmlData,
'Allegati' => $allegati,
);
}
/**********************************************************/
private function getXslByTipoMessaggioEsito($tipo)
{
switch ($tipo) {
case'MC':
case'MT':
case'NS':
case'RC':
return $tipo . "_v1_1.xsl";
break;
case'DT':
return $tipo . "_v1_0.xsl";
break;
default:
return "NE_v1_0.xsl";
break;
}
}
private function addXslTagToXml($xmlCode, $xslFileName)
{
$doc = new DOMDocument();
$doc->loadXML($xmlCode);
if ($doc->firstChild->nodeName == 'xml-stylesheet') {
$doc->firstChild->nodeValue = 'type="text/xsl" href="' . $xslFileName . '"';
return $doc->saveXML();
}
$newDoc = new DOMDocument('1.0', 'UTF-8');
$newDoc->preserveWhiteSpace = true;
$newDoc->formatOutput = true;
$newDoc->createElement("xml");
$styleSheet = $newDoc->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="' . $xslFileName . '"');
$newDoc->appendChild($styleSheet);
$newNode = $newDoc->importNode($doc->firstChild, true);
$newDoc->appendChild($newNode);
return $newDoc->saveXML();
}
private function estraiAllegatoDaXml($xmlCode)
{
$doc = new DOMDocument();
$doc->loadXML($xmlCode);
$allegati = $doc->getElementsByTagName('Allegati');
$allegatiTmp = array();
foreach ($allegati as $allegato) {
array_push($allegatiTmp, array(
'NomeFile' => $allegato->getElementsByTagName('NomeAttachment')[0]->nodeValue,
'FormatoAttachment' => $allegato->getElementsByTagName('FormatoAttachment')[0]->nodeValue,
'File' => $allegato->getElementsByTagName('Attachment')[0]->nodeValue
));
}
return $allegatiTmp;
}
private function SoapErrorResultHandler($result)
{
if (trim(str_replace('Errore -->', '', trim($result->ResultMessage))) == 'Impossibile recuperare il cliente') {
throw new Exception("Credenziali servizio FatturaFE non valide");
} else
throw new Exception(trim($result->ResultMessage));
}
private function xml2array($xmlObject, $out = array())
{
foreach ((array)$xmlObject as $index => $node)
$out[$index] = (is_object($node)) ? $this->xml2array($node) : $node;
return $out;
}
private function getXslCodeProcessed($xmlCode, $xslFile)
{
$xslPath = APPLICATION_PATH . "/../../docs/xsl/";
$tmpFile = APPLICATION_PATH . "/../../docs/tmp/" . date('d_m_Hisu') . ".xml";
$myfile = fopen($tmpFile, "w");
fwrite($myfile, $xmlCode);
fclose($myfile);
// Load the XML source
$xml = new DOMDocument;
$xml->load($tmpFile);
unlink($tmpFile);
$xsl = new DOMDocument;
$XslPath = $xslPath . $xslFile;
if (!file_exists($XslPath)) {
throw new Exception("File xsl non trovato");
}
$xsl->load($XslPath);
// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules
return $proc->transformToXML($xml);
}
/**
* Questa funzione passato un filename e un array contente i filename già utilizzati ne rinomina i duplicati aggiungendo "(incremento)" alla fine del nomefile
*
* @param $filename
* @param $listFileNamePresent
* @param int $x
* @param null $filenameOriginal
* @return string
*/
private function checkDuplicatedFileName($filename, &$listFileNamePresent, $x = 0, $filenameOriginal = null)
{
if (!in_array(strtolower($filename), $listFileNamePresent)) {
array_push($listFileNamePresent, strtolower($filename));
return $filename;
}
if ($x == 0) $filenameOriginal = pathinfo($filename, PATHINFO_FILENAME);
$x++;
$filename = $filenameOriginal . "($x)." . pathinfo($filename, PATHINFO_EXTENSION);
//Ricorsione
return $this->checkDuplicatedFileName($filename, $listFileNamePresent, $x, $filenameOriginal);
}
private function getFileSizeInByte($base64string)
{
$bytes = strlen(base64_decode($base64string));
return round($bytes, 2);
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
class App_Service_FeAuthInfo
{
private $_model;
public function __construct()
{
$this->_model = new Application_Model_Generic();
}
/**
* Funzione per il recupero delle credenziali di accesso al servizio fatturaB2B
*
* Le cerca prima nella tabella di appoggio interna fe_authdata
* se non le trova le cerca tramite il collegamento al sito fattuab2b.it e le memorizza per i successvi utilizzi
*
* @param string $piva
* @return mixed
* @throws App_Controller_Errors_WebServiceError
*/
public function getFeAuthCredential(string $piva)
{
$piva = str_replace('IT','', $piva);
$credenziali = $this->_model->getByColumnName('FeAuthData', 'PartitaIva', $piva);
if (!$credenziali) { // se non le trovo le cerco sul servizio del sito fattura b2b
$credenziali = $this->getFeAuthFatturaB2B($piva);
}
return $this->decriptaCredenziali($credenziali);
}
/**
* Recuper le credenziali dal sito fatturab2b.it e nel caso non sono presenti le memorizza sulla tabella delle credenziali
* @param $piva
* @return array|array[]
* @throws App_Controller_Errors_WebServiceError
*/
private function getFeAuthFatturaB2B($piva)
{
//Controllo se il cliente ha il servizio di fatturazione elettronica attivo sul sito FatturaB2B
$ApiFatturaB2B = new App_Model_CurlHttpClient('https://www.fatturab2b.it/services/checkserviziofe');
$credenzialiFe = $ApiFatturaB2B->getCall(array('piva' => $piva, 'info' => 1));
if (!$credenzialiFe || !$credenzialiFe['success'] || !$credenzialiFe['data']['StatoServizio']) {
throw new App_Controller_Errors_WebServiceError("Credenziali non esistenti o servizio non attivo per la partita iva $piva");
}
$credenziali = $credenzialiFe['data'];
$credenziali['PartitaIva'] = str_replace('IT','', $credenziali['PartitaIva']);
return $this->insertUpdateFeAuthRecord($credenziali);
}
/**
* Memorizza le credenziali nella tabella di appoggio fe_authdata
*
* @param $credenziali
* @return array|array[]
* @throws App_Controller_Errors_WebServiceError
* @throws Zend_Form_Exception
*/
private function insertUpdateFeAuthRecord($credenziali)
{
$feAuthDataForm = new Application_Form_Admin_Index_FeAuthData_Add();
if(!$feAuthDataForm->isValid($credenziali)){
throw new App_Controller_Errors_WebServiceError("Dati da inserire nel fe auth data non validi");
}
$credenziali = $feAuthDataForm->getValues();
$credenziali['DataUpdate'] = date('Y-m-d H:i:s');
$this->_model->deleteWhere('FeAuthData', array("PartitaIva = '?'" => $credenziali['PartitaIva']));
$credenziali['id'] = $this->_model->insert('FeAuthData', $credenziali);
return $credenziali;
}
/**
* Decripta le credenziali e le restituisce
*
* @param $credenziali
* @return mixed
*/
private function decriptaCredenziali($credenziali){
$credenziali['Password'] = App_Service_CodificaPiva::decriptaHex($credenziali['Password']);
return $credenziali;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
class App_Service_IpManager
{
protected $_configs;
protected $_enviroments;
protected $_allowedHostList;
public function __construct()
{
$this->_configs = Zend_Registry::get('config');
$this->_enviroments = Zend_Registry::get('ENVIROMENTS');
$this->_allowedHostList = array();
}
/**
* Aggiorna l'oggetto config ricaricando tutte le impostazioni memorizzate
* nel file config.ini
*/
public function allowedIp()
{
$ip_consentiti = explode(',',$this->_configs->get('ip_alternativo'));
$ip_master = trim($this->_configs->get('ip_master'));
$ip_server = trim($this->_configs->get('ip_server'));
if(in_array($_SERVER['REMOTE_ADDR'], array_merge([$ip_master], [$ip_server], $ip_consentiti))){
return true;
}
return false;
}
public function allowedHost(Zend_Controller_Request_Http $request){
$host = $request->getServer();
$host = $host['SERVER_NAME'];
if(preg_match('/'.implode('|', $this->_allowedHostList).'/',$host)){
return true;
}
return false;
}
public function allowedDevMode(){
return (APPLICATION_ENV === 'development');
}
public function allowedDevAndStagingMode(){
return (APPLICATION_ENV === 'development' || APPLICATION_ENV === 'staging');
}
public function controllaAbilitazioneTestSdk(){
return $this->allowedDevMode();
}
public function getMongoAdminDbName(){
return $this->_enviroments->get('mongodb')->get('params')->get('dbname');
}
public function getMongoDbName($nomeDb){
switch (APPLICATION_ENV){
case 'development':
return $nomeDb.'_dev';
case 'staging':
return $nomeDb.'_test';
default:
case 'production':
return $nomeDb;
}
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
class App_Service_JsonConfiguration
{
const CONFIGURATION_FOLDER_PATH = APPLICATION_PATH . "/configs/";
protected $_config;
protected $_writer;
public function __construct($nomeFile)
{
$this->initializeConfigurationFile($nomeFile);
}
private function initializeConfigurationFile($name)
{
$filePath = self::CONFIGURATION_FOLDER_PATH . $name . ".json";
if (!file_exists($filePath)) throw new Zend_Exception("File di configurazione \"$name.json\" non trovato");
$readerName = strtoupper($name) . '_CONFIG' . '_READER';
$writerName = strtoupper($name) . '_CONFIG' . '_WRITER';
//READER CONFIG FILE
if (Zend_Registry::isRegistered($readerName)){
$this->_config = Zend_Registry::get($readerName);
return;
}
$this->_config = new Zend_Config_Json($filePath, null, array('skipExtends' => true, 'allowModifications' => true));
Zend_Registry::set($readerName, $this->_config);
//WRITER
if (Zend_Registry::isRegistered($writerName)){
$this->_writer = Zend_Registry::get($writerName);
return;
}
$this->_writer = new Zend_Config_Writer_Json(array('config' => $this->_config, 'filename' => $filePath));
$this->_writer->setPrettyPrint(true);
Zend_Registry::set($writerName, $this->_writer);
}
/**
* Aggiorna l'oggetto config ricaricando tutte le impostazioni memorizzate
* nel file config.ini
*/
public function update()
{
$this->_config = new Zend_Config_Json(APPLICATION_PATH . '/configs/config.ini', null, array('skipExtends' => true, 'allowModifications' => true));
Zend_Registry::set('config', $this->_config);
}
public function write()
{
$this->_writer->config = $this->_config;
$this->_writer->write();
}
public function set($key, $value)
{
$this->_config->__set($key, $value);
$this->_writer->write();
}
/**
* Restituisce il valore del parametro richiesto
*
* @param string $name
*
* @return string
*/
public function get($name)
{
return $this->_config->get($name);
}
/**
* Elimina il parametro richiesto se esistente
*
* @param string $param
*
* @return boolean
*/
public function delete($param)
{
if (!$this->_config->get($param)) return false;
$this->_config->__unset($param);
$this->write();
return true;
}
public function getAllParams()
{
$data = array();
foreach ($this->_config as $key => $value){
$data[$key] = $value;
}
return $data;
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
class App_Service_NotifyError
{
protected $_configs;
protected $_variabiliService;
public function __construct()
{
$this->_configs = Zend_Registry::get('config');
$this->_variabiliService = new App_Service_VariabiliSito();
}
/**
* Notifica l'errore critico solo se il parametro memorizzato nelle variabili del sito è settato a zero
* Serve a notificarlo una volta sola fin quando non riattivo la notifica
*
* @param $nomeVariabileErrore
* @param $message
* @param $exception
* @param null $params
* @param bool $inviaEmail
* @throws Zend_Exception
*/
public function notificaErroreCritico($nomeVariabileErrore, $message, $exception, $params = null, $inviaEmail = true){
$variabileCheckNotififyError = $this->_variabiliService->get($nomeVariabileErrore);
if(!$variabileCheckNotififyError){
// Zend_Registry::get('log')->info(print_r($exception, true));
if($inviaEmail){
$this->inviaEmailDiErrore($message, $exception, $params);
}
$this->_variabiliService->set('I_CheckNotify_LoadMtTasks_Error', 1);
}
}
public function inviaEmailDiErrore($shortdesc, Exception $e = null, $params = null, $email = null)
{
$mail = new Zend_Mail('UTF-8');
if(!$email) $email = $this->_configs->get('test_email');
$subject = '--- SERVER AS Fatturab2b.net --- NOTIFICA ERRORE ---';
$message = '<br>ERROR MESSAGE: ' . $shortdesc;
if ($e != null) {
$message .= '<br><br>STACK TRACE ERRORE:<br>';
foreach ($e->getTrace() as $key => $value) {
$message .= "<br>[ " . $key . "] = " . $value;
if (is_array($value)) {
$message .= '<br>[';
foreach ($value as $key2 => $value2) {
$message .= "[ " . $key2 . "] = " . $value2 . "<br>";
}
$message .= ']<br>';
}
}
$message .= '<br>EXCEPTION STAMP:<br>';
$message .= "<pre>";
$message .= print_r($e,true);
$message .= "</pre>";
}
if($params){
$message .= '<br><br>PARAMETRI:<br>';
$message .= "<pre>";
$message .= print_r($params,true);
$message .= "</pre>";
$message .= '<br>';
}
$message .= '<br><br> Errore inviato dal server il ' . date('d/m/Y H:i:s');
$mail->setFrom($this->_configs->get('email_mittente'), $this->_configs->get('email_mittente_nome'))
->setSubject($subject)
->addTo($email, '')
->setBodyHtml($message)
->send();
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
class App_Service_RsaCryptor
{
const RSA_PATH = APPLICATION_PATH . '/../rsa/';
const PASS_PHRASE = 'bX3rQ5vCr8CChT';
const RSA_OBJECT_REGISTRY_NAME = 'RSA_OBJECT';
protected $_cryptor;
const RSA_KEY_OPTIONS = array(
'pemPath' => self::RSA_PATH."private_key.pem",
'certificatePath' => self::RSA_PATH. 'public_key.pub',
'passPhrase' => self::PASS_PHRASE,
'hashAlgorithm' => OPENSSL_ALGO_SHA1
);
public function __construct()
{
if(Zend_Registry::isRegistered(self::RSA_OBJECT_REGISTRY_NAME)){
$this->_cryptor = Zend_Registry::get(self::RSA_OBJECT_REGISTRY_NAME);
}else{
$this->_cryptor = new Zend_Crypt_Rsa(self::RSA_KEY_OPTIONS);
Zend_Registry::set(self::RSA_OBJECT_REGISTRY_NAME, $this->_cryptor);
}
}
public function getPrivateKey(){
return new Zend_Crypt_Rsa_Key_Private($this->_cryptor->getPemString(), self::RSA_KEY_OPTIONS['passPhrase']);
}
public function getPublicKey(){
return new Zend_Crypt_Rsa_Key_Public($this->_cryptor->getCertificateString(), self::RSA_KEY_OPTIONS['passPhrase']);
}
public function cripta($data){
return $this->_cryptor->encrypt($data, $this->getPrivateKey(), 'base64');
}
public function decripta($data){
return $this->_cryptor->decrypt($data, $this->getPublicKey(), 'base64');
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
class App_Service_SoapFeInviate extends Zend_Soap_Client
{
const TEST_URL = "https://testfe.solutiondocondemand.com/solutiondoc_hub.asmx?wsdl";
const PROD_URL = "https://hubfe.solutiondocondemand.com/solutiondoc_hub.asmx?wsdl";
const TEST_CRED = array(
'CustomerCode'=>'0000001Test0000463',
'Password'=>'B13144FA3D9E11D70079B2C929B549D2'
);
protected $_configs;
protected $_ipManager;
private $_credenziali;
private $_testSDK;
public function __construct(array $credenziali = null)
{
$this->_configs = new App_Service_ConfigManager();
$this->_ipManager = new App_Service_IpManager();
if($this->_ipManager->allowedDevMode())
$this->_testSDK = true;
else
$this->_testSDK = false;
if($this->_testSDK){
parent::__construct(self::TEST_URL);
if(!$credenziali)
$this->_credenziali = self::TEST_CRED;
else
$this->_credenziali = $credenziali;
}else{
parent::__construct(self::PROD_URL);
if(!$credenziali){
throw new Zend_Exception("Errore credenziali non presenti nell'inizializzione del SOAP FEInviate");
}
$this->_credenziali = $credenziali;
}
}
public function getCredenziali()
{
return $this->_credenziali;
}
public function getOldCredenziali()
{
return array(
'codiceCliente'=>$this->_credenziali['CustomerCode'],
'passwordServizi'=>$this->_credenziali['Password']
);
}
public function mergeParamsCredenziali($params = array()){
return array_merge_recursive(array('paramAuth'=>$this->_credenziali),$params);
}
public function mergeParamsOldCredenziali($params = array()){
return array_merge_recursive(array(
'codiceCliente'=>$this->_credenziali['CustomerCode'],
'passwordServizi'=>$this->_credenziali['Password']
),$params);
}
public static function strToBytesArray($str){
$tmp = array();
for($i = 0; $i < mb_strlen($str, 'ASCII'); $i++) {
$tmp[$i] = ord($str[$i]);
}
return $tmp;
}
public static function BytesArrayToStr($arrayOfBytes){
return implode(array_map("chr", $arrayOfBytes));
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
class App_Service_V1Auth
{
protected $_genericModel;
public function __construct()
{
$this->_genericModel = new Application_Model_Generic();
}
public function getUser()
{
if (Zend_Registry::isRegistered('TOKEN')) {
return $this->_genericModel->getByColumnName('Users', 'token', Zend_Registry::get('TOKEN'));
} else {
return null;
}
}
public function controllaPermessiSuOrdine($ordineMapping, $user = null)
{
if (!$user) {
$user = $this->getUser();
}
switch ($user['role']) {
case 'admin':
return true;
case 'user':
return $user['id'] === $ordineMapping['ID_Utente'];
case 'attivita':
return $user['id'] === $ordineMapping['ID_Attivita'];
case 'rider':
return $user['id'] === $ordineMapping['ID_UserRider'];
default:
return false;
}
}
/**
* Controlla se il permesso passatto o i permessi sono validi per l'utente loggato
* @param array $role
* @param null $user
* @return bool
*/
public function controllaPermessiByRole(array $role, $user = null)
{
if (!$user) {
$user = $this->getUser();
}
return in_array($user['role'], $role);
}
public function getPermissionWhere($user = null)
{
if (!$user) {
$user = $this->getUser();
}
switch ($user['role']) {
case 'admin':
return [];
case 'user':
return ['ID_Utente = ?' => $user['id']];
case 'attivita':
return ['ID_Attivita = ?' => $user['id']];
case 'rider':
return ['ID_UserRider = ?' => $user['id']];
default:
return ['id < ?' => '0']; // forza a non restituire nulla
}
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
class App_Service_VariabiliSito
{
const VARIABILI_SITO_REGISTRY_NAME = 'VARIABILI_SITO';
protected $_genericModel;
protected $_variabili;
public function __construct()
{
$this->_genericModel = new Application_Model_Generic();
$this->initialize();
}
private function initialize()
{
if (Zend_Registry::isRegistered(self::VARIABILI_SITO_REGISTRY_NAME)){
$this->_variabili = Zend_Registry::get(self::VARIABILI_SITO_REGISTRY_NAME);
return;
}
$tmp = $this->_genericModel->getList('VariabiliSito');
$variabili = array();
foreach($tmp as $key => $val){
$tipo = explode('_',$val['Nome'])[0];
switch($tipo){
case'I':
$variabili[$val['Nome']] = $val['ValoreInteger'];
break;
case'D':
$variabili[$val['Nome']] = $val['ValoreDouble'];
break;
case'S':
$variabili[$val['Nome']] = $val['ValoreString'];
break;
case'TJ':
$variabili[$val['Nome']] = Zend_Json::decode($val['ValoreString']);
break;
}
}
$this->_variabili = $variabili;
Zend_Registry::set(self::VARIABILI_SITO_REGISTRY_NAME, $this->_variabili);
}
public function get($key)
{
return $this->_variabili[$key];
}
public function set($key,$value){
$tipo = explode('_',$key)[0];
switch($tipo){
case'I':
$data = array('ValoreInteger'=>$value);
break;
case'D':
$data = array('ValoreDouble'=>$value);
break;
case'T':
$data = array('ValoreString'=>$value);
break;
case'TJ':
$data = array('ValoreString'=>Zend_Json::encode($value));
break;
default:
throw new Exception("Tipo del valore da inserire non specificato");
break;
}
if(array_key_exists($key,$this->_variabili)) //update
$this->_genericModel->updateWhere('VariabiliSito',"Nome = '$key'",$data);
else //Inserimento
$this->_genericModel->insert('VariabiliSito',array_merge(array('Nome'=>$key),$data));
$this->_variabili[$key] = $value;
Zend_Registry::set(self::VARIABILI_SITO_REGISTRY_NAME, $this->_variabili);
}
public function getAll(){
return $this->_variabili;
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
class App_Service_WebServiceV1Auth
{
//ERRORI GENERATI DALLO ZEND_AUTH RICODIFICATI DA ME
const NO_CREDENTIAL_CLOUDUSER = 'V1AUTH_ERROR_NO_CREDENTIAL_CLOUDUSER';
const FAILURE_IDENTITY_NOT_FOUND = 'V1AUTH_ERROR_FAILURE_IDENTITY_NOT_FOUND';
const FAILURE_CREDENTIAL_INVALID = 'V1AUTH_ERROR_FAILURE_CREDENTIAL_INVALID';
const ACCOUNT_DEACTIVATED = 'V1AUTH_ERROR_ACCOUNT_DEACTIVATED';
const FAILURE = 'V1AUTH_ERROR_FAILURE';
protected $_model;
protected $_auth;
protected $_configs;
protected $_ipManager;
public function __construct()
{
$this->_model = new Application_Model_Generic();
$this->_configs = new App_Service_ConfigManager();
$this->_ipManager = new App_Service_IpManager();
}
public function authenticate($username, $password, $staylogin = 0)
{
$adapter = $this->getAuthAdapter(array('username' => $username, 'password' => $password));
$auth = $this->getAuth();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
return $result->getCode();
}
$user = (array)$adapter->getResultRowObject();
if (!$user['stato']) {
return self::ACCOUNT_DEACTIVATED;
}
//Generazione del Token temporaneo per l'accesso
if ($user['token'] != null) {
$token = $user['token']; //Esistente uso quello già presente
} else {
do { //se non esiste ne genero uno nuovo e controllo che sia univoco
$token = hash('sha1', $user['username'] . date('H:i:s') . mt_rand(5, 10));
if ($this->_model->getByColumnName('Users', 'token', $token)) {
$exist = true;
} else {
$exist = false;
}
$user['token'] = $token;
} while ($exist);
}
//Imposto il DB MONGO dell'utente
$mongoDbName = $this->_ipManager->getMongoDbName($user['NomeDB']);
if(Zend_Registry::isRegistered(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME))
Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME)->setDbname($mongoDbName);
else
Zend_Registry::set(App_Model_Mongo_Adapter::MONGO_DB_NAME, $mongoDbName);
//Memorizzo l'ultimo accesso dell'utente
$this->_model->update('Users', $user['id'], array(
'token' => $token,
'UltimoLogin' => date('Y-m-d H:i:s'),
'staylogin' => $staylogin)
);
$auth->getStorage()->write($user);
return $user;
}
public function getAuth()
{
if (null === $this->_auth) {
$this->_auth = Zend_Auth::getInstance();
$this->_auth->setStorage(new Zend_Auth_Storage_Session('Web_Auth'));
}
return $this->_auth;
}
public function getIdentity()
{
$auth = $this->getAuth();
if ($auth->hasIdentity()) {
return $auth->getIdentity();
}
return false;
}
public function clear()
{
$this->getAuth()->clearIdentity();
}
public function getAuthAdapter($values)
{
$salt = Zend_Registry::get('ENVIROMENTS')->get('password_salt');
$authAdapter = new Zend_Auth_Adapter_DbTable(
Zend_Db_Table_Abstract::getDefaultAdapter(),
'users',
'username',
'password',
"MD5(CONCAT('$salt',?))"
);
$authAdapter->setIdentity($values['username']);
$authAdapter->setCredential($values['password']);
return $authAdapter;
}
}