Initial Commit
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
class App_Constants_Domains
|
||||
{
|
||||
|
||||
const DOMAIN_NAME_ROLES = 'roles';
|
||||
const DOMAIN_SOFTWARE = 'software';
|
||||
const DOMAIN_NAME_STATIFE = 'stati_fe';
|
||||
const DOMAIN_NAME_STATI_INVIO_EMAILS = 'stati_invio_emails';
|
||||
|
||||
const DOMAINS = [
|
||||
self::DOMAIN_NAME_ROLES =>
|
||||
[
|
||||
'admin' => ['name' => 'Amministratore', 'icon' => 'user-cog', 'color' => ''],
|
||||
'user' => ['name' => 'Utente', 'icon' => 'user', 'color' => '']
|
||||
],
|
||||
self::DOMAIN_SOFTWARE =>
|
||||
[
|
||||
'Winfatt' => ['name' => 'Winfatt', 'icon' => '', 'color' => ''],
|
||||
'GestioneSpiaggia' => ['name' => 'Gestione Spiaggia', 'icon' => '', 'color' => ''],
|
||||
'Webfatt' => ['name' => 'Webfatt', 'icon' => '', 'color' => '']
|
||||
],
|
||||
self::DOMAIN_NAME_STATI_INVIO_EMAILS =>
|
||||
[
|
||||
'DaInviare' => ['name' => 'Da Inviare', 'icon' => 'user-cog', 'color' => 'gray'],
|
||||
'InElaborazione' => ['name' => 'In Elaborazione', 'icon' => 'user-cog', 'color' => 'warning'],
|
||||
'Inviato' => ['name' => 'Inviato', 'icon' => 'user-cog', 'color' => 'success'],
|
||||
'Annullato' => ['name' => 'Annullato', 'icon' => 'user-cog', 'color' => 'danger'],
|
||||
],
|
||||
self::DOMAIN_NAME_STATIFE =>
|
||||
[
|
||||
'AC' => ['name' => 'In Attesa Consegna', 'icon' => '', 'color' => 'gray'],
|
||||
'RC' => ['name' => 'Consegnata', 'icon' => '', 'color' => 'success'],
|
||||
'NS' => ['name' => 'Scartata', 'icon' => '', 'color' => 'danger'],
|
||||
'MC' => ['name' => 'Mancata Consegna', 'icon' => '', 'color' => 'warning'],
|
||||
// 'DT' => ['name' => 'Decorrenza Termini', 'icon' => '', 'color' => ''],
|
||||
// 'EC_ACCETTAZIONE' => ['name' => 'Accettata', 'icon' => '', 'color' => ''],
|
||||
// 'EC_RIFIUTO' => ['name' => 'Rifiutata', 'icon' => '', 'color' => ''],
|
||||
],
|
||||
];
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
class App_Controller_Errors_WebServiceError extends Zend_Rest_Exception
|
||||
{
|
||||
protected $_DbName;
|
||||
protected $_message;
|
||||
protected $_errorCode;
|
||||
protected $_errorDetail;
|
||||
|
||||
const WEBSERVICE_SESSION_EXPIRED = "WEBSERVICE_SESSION_EXPIRED";
|
||||
const WEBSERVICE_SECRETID_ERROR = "WEBSERVICE_SECRETID_ERROR";
|
||||
const WEBSERVICE_METHOD_NOTFOUND = "WEBSERVICE_METHOD_NOTFOUND";
|
||||
|
||||
const WEBSERVICE_GENERIC_ERROR = "WEBSERVICE_GENERIC_ERROR";
|
||||
const WEBSERVICE_GENERIC_NOIDERROR = "WEBSERVICE_GENERIC_NOIDERROR";
|
||||
const WEBSERVICE_GENERIC_DATAINVALID = "WEBSERVICE_GENERIC_DATAINVALID";
|
||||
const WEBSERVICE_GENERIC_NOPERMISSION = "WEBSERVICE_GENERIC_NOPERMISSION";
|
||||
|
||||
const WEBSERVICE_MAPS_PARAMSINVALID = "WEBSERVICE_MAPS_PARAMSINVALID";
|
||||
const WEBSERVICE_MAPS_NOINMACROAREA = "WEBSERVICE_MAPS_NOINMACROAREA";
|
||||
const WEBSERVICE_MAPS_NOINSOTTOAREA = "WEBSERVICE_MAPS_NOINSOTTOAREA";
|
||||
|
||||
const WEBSERVICE_ORDINI_NOFASCIAORARIA = "WEBSERVICE_ORDINI_NOFASCIAORARIA";
|
||||
const WEBSERVICE_ORDINI_CREATECHECKLIST = "WEBSERVICE_ORDINI_CREATECHECKLIST";
|
||||
|
||||
const WEBSERVICE_ORDINI_UPDATEDISABLED = "WEBSERVICE_ORDINI_UPDATEDISABLED";
|
||||
|
||||
const WEBSERVICE_FORM_DATAINVALID = "WEBSERVICE_FORM_DATAINVALID";
|
||||
|
||||
public function __construct($message, $errorDetail = null, $errorCode = self::WEBSERVICE_GENERIC_ERROR)
|
||||
{
|
||||
parent::__construct($message);
|
||||
$this->_message = $message;
|
||||
$this->_errorDetail = $errorDetail;
|
||||
$this->_errorCode = $errorCode;
|
||||
}
|
||||
|
||||
public function getMyMessage()
|
||||
{
|
||||
return $this->_message;
|
||||
}
|
||||
|
||||
public function getErrorDetail()
|
||||
{
|
||||
return $this->_errorDetail;
|
||||
}
|
||||
|
||||
public function getErrorCode()
|
||||
{
|
||||
return $this->_errorCode;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
<?php
|
||||
|
||||
class App_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
|
||||
{
|
||||
|
||||
const AUTHORIZATION_HEADER = 'Authorization';
|
||||
const MONGO_DB_NAME = 'MongoDBName';
|
||||
|
||||
const AUTH_TYPE_SECRET_ID = 'SECRET';
|
||||
|
||||
protected $_acl;
|
||||
protected $_aclRestV1;
|
||||
protected $_role;
|
||||
protected $_auth;
|
||||
protected $_genericModel;
|
||||
protected $_configs;
|
||||
protected $_ipManager;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->_genericModel = new Application_Model_Generic();
|
||||
$this->_auth = Zend_Auth::getInstance();
|
||||
$this->_acl = new App_Model_Acl_Acl();
|
||||
$this->_aclRestV1 = new App_Model_Acl_AclRestV1();
|
||||
|
||||
$this->_role = !$this->_auth->hasIdentity() ? 'unregistered' : $this->_auth->getIdentity()->role;
|
||||
$this->_configs = new App_Service_ConfigManager();
|
||||
$this->_ipManager = new App_Service_IpManager();
|
||||
|
||||
}
|
||||
|
||||
public function preDispatch(Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
|
||||
//Gestione degli accessi separati per i vari moduli
|
||||
/**
|
||||
* V1 = Web Service di tipo REST per interfacciarsi verso lesterno [Accesso Tramite TOKEN]
|
||||
* DEFAULT | AUTH: Accesso normale del sito
|
||||
* ADMIN: Accesso solo per l'utente admin
|
||||
*/
|
||||
|
||||
switch ($request->getModuleName()) {
|
||||
//Il modulo default e auth non hanno bisogno di autenticazione quindi imposto user come 'unregistered' e vado avanti
|
||||
case'default':
|
||||
case'auth':
|
||||
$this->_role = 'unregistered';
|
||||
if (!$this->_acl->isAllowed($this->_role, $request->getModuleName())) {
|
||||
$this->denyAccess();
|
||||
}
|
||||
return;
|
||||
case 'admin':
|
||||
case 'user':
|
||||
case 'monitoring':
|
||||
if (!$this->_acl->isAllowed($this->_role, $request->getModuleName())) {
|
||||
$this->_auth->clearIdentity();
|
||||
$this->_redirectLogin($request);
|
||||
}
|
||||
return;
|
||||
case'v1':
|
||||
//controllo se il web services non è offline
|
||||
if ($this->_configs->get('interrutore_webservices_v1') == 'off' && !$this->_ipManager->allowedIp()) {
|
||||
$this->_redirectOffline($request);
|
||||
}
|
||||
|
||||
//controllo il web services ad accesso libero
|
||||
$this->_role = 'unregistered';
|
||||
if (!$this->_aclRestV1->isAllowed(trim($this->_role), $request->getControllerName())) {
|
||||
//Se il controller non è abilitato all'accesso libero allora procedo con l'autenticazione server v1 tramite token
|
||||
$this->accessoV1($request, $request->getHeader(self::AUTHORIZATION_HEADER));
|
||||
} else {
|
||||
if (Zend_Registry::get('ENABLE_MONGODB')) {
|
||||
// controllo se settare il parametro per il nome DB nel caso non sono autenticato utilizzo un db mongo di default
|
||||
$mongoDbName = $request->getHeader(self::MONGO_DB_NAME);
|
||||
if ($mongoDbName) {
|
||||
$mongoDbName = $this->_ipManager->getMongoDbName($mongoDbName);
|
||||
$this->setMongoDbRegistryName($mongoDbName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
//Controllo i permessi prima sul modulo e poi sul controller in caso sia un webservices
|
||||
if (!$this->_acl->isAllowed(trim($this->_role), $request->getModuleName())) {
|
||||
$this->denyAccess();
|
||||
} else {
|
||||
switch ($request->getModuleName()) {
|
||||
case'v1':
|
||||
if (!$this->_aclRestV1->isAllowed(trim($this->_role), $request->getControllerName()))
|
||||
$this->denyAccess();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function accessoV1(Zend_Controller_Request_Abstract $request, $token)
|
||||
{
|
||||
if (!$token) return $this->_redirectNoAuth($request);
|
||||
|
||||
//Controllo che nell'autorization header sia contenuto anche il metodo di autorizazzione lo scompongo e ottendo il codice
|
||||
$authorizationHeaderParts = explode(' ', $token);
|
||||
if (count($authorizationHeaderParts) > 1) {
|
||||
$type = strtoupper($authorizationHeaderParts[0]);
|
||||
$token = $authorizationHeaderParts[1];
|
||||
} else {
|
||||
$token = $authorizationHeaderParts[0];
|
||||
}
|
||||
|
||||
$user = null;
|
||||
switch ($type) {
|
||||
case self::AUTH_TYPE_SECRET_ID:
|
||||
$user = $this->authenticateV1SecretToken($token);
|
||||
break;
|
||||
default:
|
||||
$user = $this->authenticateV1($token);
|
||||
break;
|
||||
}
|
||||
|
||||
// Salvo il token nel registry
|
||||
Zend_Registry::set('TOKEN', $token);
|
||||
|
||||
if ($user != null)
|
||||
$this->_role = $user['role'];
|
||||
else
|
||||
$this->_redirectTokenScaduto($request);
|
||||
|
||||
if (!$user['stato']) {
|
||||
$this->_redirectDeactiveUserState($request);
|
||||
}
|
||||
|
||||
if (Zend_Registry::get('ENABLE_MONGODB')) {
|
||||
$mongoDbName = $this->_ipManager->getMongoDbName($user['NomeDB']);
|
||||
if ($user['role'] === 'admin') {
|
||||
$mongoDbName = $request->getHeader(self::MONGO_DB_NAME);
|
||||
if (!$mongoDbName) {
|
||||
$mongoDbName = $this->_ipManager->getMongoAdminDbName();
|
||||
} else {
|
||||
$mongoDbName = $this->_ipManager->getMongoDbName($mongoDbName);
|
||||
}
|
||||
}
|
||||
|
||||
$this->setMongoDbRegistryName($mongoDbName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function setMongoDbRegistryName($mongoDbName)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
private function authenticateV1($token)
|
||||
{
|
||||
$user = $this->_genericModel->getByColumnName('Users', 'token', $token, '=', true);
|
||||
if (!$user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//Aggiornamento del campo UltimoAccesso
|
||||
$this->_genericModel->update('Users', $user['id'], array('UltimoAccesso' => date('Y-m-d H:i:s')));
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function authenticateV1SecretToken($token)
|
||||
{
|
||||
$user = $this->_genericModel->getByColumnName('Users', 'secret_token', $token, '=', true);
|
||||
if (!$user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//Aggiornamento del campo UltimoAccesso
|
||||
$this->_genericModel->update('Users', $user['id'], array('UltimoAccesso' => date('Y-m-d H:i:s')));
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
public function denyAccess()
|
||||
{
|
||||
$this->_request->setModuleName('default')
|
||||
->setControllerName('error')
|
||||
->setActionName('invalid')
|
||||
->setParam('message', 'L\'utente non ha i permessi per accedere alla risorsa.');
|
||||
}
|
||||
|
||||
protected function _invalidCredential()
|
||||
{
|
||||
$this->_request->setModuleName('default')
|
||||
->setControllerName('error')
|
||||
->setActionName('invalid')
|
||||
->setParam('message', 'Username e/o password errati.');
|
||||
}
|
||||
|
||||
protected function _redirectInvalidRequest(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
$request->setModuleName('default')
|
||||
->setControllerName('error')
|
||||
->setActionName('invalid')
|
||||
->setParam('message', 'Invalid authentication header.');
|
||||
}
|
||||
|
||||
protected function _redirectNoAuth(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
$request->setModuleName('default')
|
||||
->setControllerName('error')
|
||||
->setActionName('invalid')
|
||||
->setParam('message', 'Authentication header not found');
|
||||
}
|
||||
|
||||
protected function _redirectUrlScaduto(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
$request->setModuleName('default')
|
||||
->setControllerName('error')
|
||||
->setActionName('invalid')
|
||||
->setParam('message', 'Url Scaduto');
|
||||
}
|
||||
|
||||
protected function _redirectTokenScaduto(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
throw new App_Controller_Errors_WebServiceError(utf8_encode("Accesso Scaduto"), null, App_Controller_Errors_WebServiceError::WEBSERVICE_SESSION_EXPIRED);
|
||||
}
|
||||
|
||||
protected function _redirectOffline(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
$request->setModuleName('default')
|
||||
->setControllerName('error')
|
||||
->setActionName('invalid')
|
||||
->setParam('message', 'Il web services è offline');
|
||||
}
|
||||
|
||||
protected function _redirectDeactiveUserState(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
throw new App_Controller_Errors_WebServiceError(utf8_encode("Account Api Disattivato"), null, App_Controller_Errors_WebServiceError::WEBSERVICE_SESSION_EXPIRED);
|
||||
}
|
||||
|
||||
protected function _redirectNoMongoDBName(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
throw new App_Controller_Errors_WebServiceError(utf8_encode("Nomd DB Mongo non specificato"), null, App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR);
|
||||
}
|
||||
|
||||
protected function _redirectLogin(\Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
// Forward the request to the noauth error page.
|
||||
$request->setParam('section', $request->getModuleName())
|
||||
->setModuleName('default')
|
||||
->setControllerName('index')
|
||||
->setActionName('login');
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
class App_Controller_Plugin_LangSelector extends Zend_Controller_Plugin_Abstract
|
||||
{
|
||||
public function preDispatch(Zend_Controller_Request_Abstract $request)
|
||||
{
|
||||
$session = new Zend_Session_Namespace('session');
|
||||
|
||||
$lang = $request->getParam('lang','');
|
||||
$langLocale = '';
|
||||
|
||||
switch($lang) {
|
||||
case "it":
|
||||
$langLocale = 'it'; break;
|
||||
case "en":
|
||||
$langLocale = 'en'; break;
|
||||
default:
|
||||
$langLocale = isset($session->lang) ? $session->lang : Zend_Registry::get('Zend_Locale')->getLanguage();
|
||||
}
|
||||
|
||||
$locale = new Zend_Locale($langLocale);
|
||||
Zend_Registry::set('Zend_Locale', $locale);
|
||||
|
||||
$translationPath = dirname( APPLICATION_PATH ) . DIRECTORY_SEPARATOR . 'languages' . DIRECTORY_SEPARATOR . $langLocale;
|
||||
$translate = new Zend_Translate('array', $translationPath, $locale);
|
||||
|
||||
$session->lang = $langLocale;
|
||||
|
||||
Zend_Registry::set('Zend_Translate', $translate);
|
||||
Zend_Validate_Abstract::setDefaultTranslator($translate);
|
||||
Zend_Form::setDefaultTranslator($translate);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class App_Controller_Rest_Controller
|
||||
* Versione 1.0.1 - Data: 12/08/2020
|
||||
*/
|
||||
abstract class App_Controller_Rest_Controller extends Zend_Rest_Controller
|
||||
{
|
||||
public $_resourceName;
|
||||
public $_resourceFormName;
|
||||
public $_patchResourceName;
|
||||
|
||||
public $_responseData;
|
||||
public $_status;
|
||||
public $_inArray;
|
||||
|
||||
public $_genericModel;
|
||||
public $_dbAdapter;
|
||||
|
||||
public $_joinData = null;
|
||||
public $_groupBy = null;
|
||||
|
||||
public $_defaultPageNumber = null;
|
||||
public $_defaultPageCount = null;
|
||||
public $_defaultOrder = null;
|
||||
|
||||
public $_returnWithDataObject = true;
|
||||
|
||||
public function init()
|
||||
{
|
||||
$this->_helper->viewRenderer->setNoRender(true);
|
||||
$this->_helper->AjaxContext()
|
||||
->addActionContext('get', 'json')
|
||||
->addActionContext('post', 'json')
|
||||
->addActionContext('put', 'json')
|
||||
->addActionContext('patch', 'json')
|
||||
->addActionContext('delete', 'json')
|
||||
->addActionContext('options', 'json')
|
||||
->addActionContext('head', 'json')
|
||||
->initContext('json');
|
||||
|
||||
$this->_responseData = new stdClass();
|
||||
$this->_status = false;
|
||||
$this->_inArray = false;
|
||||
|
||||
if (!$this->_resourceFormName) {
|
||||
$this->_resourceFormName = $this->_resourceName;
|
||||
}
|
||||
|
||||
if (!$this->_patchResourceName) {
|
||||
$this->_patchResourceName = $this->_resourceName;
|
||||
}
|
||||
|
||||
$this->_genericModel = new Application_Model_Generic();
|
||||
$this->_dbAdapter = $this->_genericModel->getResource($this->_resourceName)->getDbAdapter();
|
||||
}
|
||||
|
||||
public function preDispatch()
|
||||
{
|
||||
$this->_response->setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Authorization,x-requested-with,Content-Type,Cache-Control,X-As-Dev-On,X-As-Dev-Pw,MongoDbName');
|
||||
$this->_response->setHeader('Access-Control-Expose-Headers', 'X-Tot-Items,X-Page,X-Count,X-Tot-Filtered');
|
||||
$this->_response->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, PATCH, DELETE');
|
||||
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
|
||||
$this->_response->setHeader('Access-Control-Allow-Credentials', 'true');
|
||||
|
||||
// Controllo sui metodi di prefetch
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
return $this->optionsAction();
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'HEAD') {
|
||||
return $this->optionsAction();
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
|
||||
return $this->patchAction();
|
||||
}
|
||||
}
|
||||
|
||||
//##################################### CRUD FUNCTIONS #############################################################
|
||||
|
||||
public function indexAction()
|
||||
{
|
||||
$this->getAction();
|
||||
}
|
||||
|
||||
public function getAction()
|
||||
{
|
||||
try {
|
||||
$this->switchMethodFunction($this->_getParam('method'));
|
||||
} catch (Exception $e) {
|
||||
$this->_status = false;
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function postAction()
|
||||
{
|
||||
|
||||
try {
|
||||
|
||||
$this->_dbAdapter->beginTransaction();
|
||||
|
||||
$params = Zend_Json::decode($this->getRequest()->getRawBody());
|
||||
|
||||
$form = $this->getAddFormForResource();
|
||||
|
||||
//Inserimento di batch
|
||||
if (is_array($params[0])) {
|
||||
$failedElements = array();
|
||||
foreach ($params as $key => $riga) {
|
||||
if ($form->isValid($riga)) {
|
||||
$dati = $form->getValues();
|
||||
$this->insertSingleElement($dati);
|
||||
} else {
|
||||
array_push($failedElements, $key);
|
||||
}
|
||||
}
|
||||
|
||||
$this->_dbAdapter->commit();
|
||||
|
||||
$this->_status = true;
|
||||
$this->_responseData->data = array('failed_elements_index' => $failedElements);
|
||||
return $this->sendResponse();
|
||||
}
|
||||
|
||||
//Inserimento di un singolo elemento
|
||||
if (!$form->isValid($params)) {
|
||||
$this->_status = false;
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_FORM_DATAINVALID;
|
||||
$this->_responseData->message = 'I dati inseriti non sono validi';
|
||||
$this->_responseData->errorDetails = $form->getMessages();
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$dati = $form->getValues();
|
||||
|
||||
$dati = $this->preInsertElement($dati);
|
||||
|
||||
$dati['id'] = $this->insertSingleElement($dati);
|
||||
|
||||
$this->_dbAdapter->commit();
|
||||
|
||||
$dati = $this->afterInsertElement($dati);
|
||||
|
||||
$this->_responseData->data = ($this->_returnWithDataObject) ? array('data' => $dati) : $dati;
|
||||
$this->_status = true;
|
||||
|
||||
$this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
try{
|
||||
$this->_dbAdapter->rollBack();
|
||||
}catch (Exception $e2){}
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function putAction()
|
||||
{
|
||||
try {
|
||||
$params = Zend_Json::decode($this->getRequest()->getRawBody());
|
||||
|
||||
$this->_dbAdapter->beginTransaction();
|
||||
$form = $this->getAddFormForResource();
|
||||
|
||||
//Aggiornamento di batch
|
||||
if (is_array($params[0])) {
|
||||
$failedElements = array();
|
||||
$resolvedElements = array();
|
||||
foreach ($params as $key => $riga) {
|
||||
if ($form->isValid($riga) && $riga['id']) {
|
||||
$this->updateSingleElement($riga['id'], $form->getValues());
|
||||
array_push($resolvedElements, $riga['id']);
|
||||
} else {
|
||||
array_push($failedElements, $riga['id']);
|
||||
}
|
||||
}
|
||||
|
||||
$this->_dbAdapter->commit();
|
||||
|
||||
$this->_status = true;
|
||||
$this->_responseData->data = array('failed_elements_id' => $failedElements, 'resolved_elements_id' => $resolvedElements);
|
||||
return $this->sendResponse();
|
||||
}
|
||||
|
||||
//Aggiornamento singolo
|
||||
if (!$form->isValidPartial($params)) {
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_FORM_DATAINVALID;
|
||||
$this->_responseData->message = 'I dati inseriti non sono validi';
|
||||
$this->_responseData->errorDetails = $form->getMessages();
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$dati = $form->getValues();
|
||||
|
||||
if (!$this->_getParam('id')) {
|
||||
$this->_responseData->message = 'Id elemento non trovato';
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$dati = $this->preUpdateElement($dati, $this->_getParam('id'));
|
||||
|
||||
$this->updateSingleElement($this->_getParam('id'), $dati);
|
||||
$dati['id'] = $this->_getParam('id');
|
||||
|
||||
$this->_dbAdapter->commit();
|
||||
|
||||
$dati = $this->afterUpdateElement($dati);
|
||||
|
||||
$this->_responseData->data = ($this->_returnWithDataObject) ? array('data' => $dati) : $dati;
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
try{
|
||||
$this->_dbAdapter->rollBack();
|
||||
}catch (Exception $e2){}
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function patchAction()
|
||||
{
|
||||
try {
|
||||
$params = Zend_Json::decode($this->getRequest()->getRawBody());
|
||||
|
||||
$this->_dbAdapter->beginTransaction();
|
||||
$form = $this->getAddFormForResource();
|
||||
|
||||
//Aggiornamento singolo
|
||||
if (!$form->isValidPartial($params)) {
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_FORM_DATAINVALID;
|
||||
$this->_responseData->message = 'I dati inseriti non sono validi';
|
||||
$this->_responseData->errorDetails = $form->getMessages();
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$formData = $form->getValues();
|
||||
|
||||
//rimuovo i valori vuoti che non devono essere sovrascritti
|
||||
foreach ($formData as $key => $val) {
|
||||
if (!$val) unset($formData[$key]);
|
||||
}
|
||||
|
||||
$id = $this->_getParam('id');
|
||||
if (!$id) {
|
||||
$this->_responseData->message = 'Id elemento non trovato';
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$oldElement = $this->_genericModel->getById($this->_resourceName, $id);
|
||||
$dati = array_merge($oldElement, $formData);
|
||||
|
||||
$dati = $this->preUpdateElement($dati, $this->_getParam('id'));
|
||||
|
||||
$dati = $this->updateSingleElement($this->_getParam('id'), $dati);
|
||||
|
||||
$this->_dbAdapter->commit();
|
||||
|
||||
$dati = $this->afterUpdateElement($dati);
|
||||
|
||||
$this->_responseData->data = $dati;
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
try{
|
||||
$this->_dbAdapter->rollBack();
|
||||
}catch (Exception $e2){}
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteAction()
|
||||
{
|
||||
try {
|
||||
|
||||
$this->_dbAdapter->beginTransaction();
|
||||
|
||||
if (!$this->_getParam('id')) {
|
||||
$this->_status = false;
|
||||
$this->_responseData->message = "Errore id non trovato";
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_NOIDERROR;
|
||||
return $this->sendResponse();
|
||||
}
|
||||
|
||||
$toDelete = explode(',', $this->_getParam('id'));
|
||||
//Eliminazione batch
|
||||
if (is_array($toDelete) && count($toDelete) > 1) {
|
||||
$failedElements = array();
|
||||
$resolvedElements = array();
|
||||
foreach ($toDelete as $key => $id) {
|
||||
try {
|
||||
$this->deleteSingleElement($id);
|
||||
array_push($resolvedElements, $id);
|
||||
} catch (Exception $e) {
|
||||
array_push($failedElements, $id);
|
||||
}
|
||||
}
|
||||
|
||||
$this->_dbAdapter->commit();
|
||||
$this->_responseData->data = $resolvedElements;
|
||||
$this->_status = true;
|
||||
|
||||
return $this->sendResponse();
|
||||
}
|
||||
|
||||
$id = $this->_getParam('id', null);
|
||||
if (!$id) {
|
||||
$this->_responseData->message = 'Id non ricevuto';
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
// Pre delete
|
||||
$this->preDeleteElement($id);
|
||||
|
||||
//Eliminazione Singola
|
||||
$this->deleteSingleElement($id);
|
||||
|
||||
// After delete
|
||||
$this->afterDeleteElement($id);
|
||||
|
||||
$this->_dbAdapter->commit();
|
||||
$this->_status = true;
|
||||
return $this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
try{
|
||||
$this->_dbAdapter->rollBack();
|
||||
}catch (Exception $e2){}
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
return $this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function headAction()
|
||||
{
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
public function optionsAction()
|
||||
{
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
//##################################### SINGLE ELEMENT FUNCTIONS ###################################################
|
||||
|
||||
public function getSingleElement($id)
|
||||
{
|
||||
return $this->getSingleElementManipulate($this->_genericModel->getById($this->_resourceName, $id));
|
||||
}
|
||||
|
||||
public function insertSingleElement($dati)
|
||||
{
|
||||
return $this->_genericModel->insert($this->_resourceName, $dati);
|
||||
}
|
||||
|
||||
public function updateSingleElement($id, $dati)
|
||||
{
|
||||
return $this->_genericModel->update($this->_resourceName, $id, $dati);
|
||||
}
|
||||
|
||||
public function deleteSingleElement($id)
|
||||
{
|
||||
return $this->_genericModel->delete($this->_resourceName, $id);
|
||||
}
|
||||
|
||||
public function insertDataToRowList($list)
|
||||
{
|
||||
return $list;
|
||||
}
|
||||
|
||||
//##################################### SWITCH METHOD FUNCTIONS ###################################################
|
||||
|
||||
public function switchMethodFunction($method)
|
||||
{
|
||||
switch ($method) {
|
||||
case'bycolumn':
|
||||
$this->defaultGetByColumnName();
|
||||
break;
|
||||
default:
|
||||
$this->defaultGetList();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected function defaultGetList()
|
||||
{
|
||||
if ($this->_getParam('id') != null) {
|
||||
$this->_responseData->data = $this->getSingleElement($this->_getParam('id'));
|
||||
} else {
|
||||
$this->_inArray = true;
|
||||
|
||||
$page = $this->_getParam('page', $this->_defaultPageNumber);
|
||||
$count = $this->_getParam('count', $this->_defaultPageCount);
|
||||
$order = $this->_getParam('order', $this->_defaultOrder);
|
||||
$select = $this->_getParam('select', null);
|
||||
|
||||
$this->checkIfSetJoinData($this->getAllParams());
|
||||
$this->checkIfSetGroupBy($this->getAllParams());
|
||||
|
||||
$where = $this->_helper->FilterFunctions($this->getAllParams());
|
||||
|
||||
$where = $this->setFixedSelectWhere($where);
|
||||
$data = $this->_genericModel->getList($this->_resourceName, $page, $count, $where, $order, $select, $this->_joinData, $this->_groupBy);
|
||||
|
||||
$data = $this->insertDataToRowList($data);
|
||||
|
||||
$this->_responseData->data = $data;
|
||||
}
|
||||
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
public function defaultGetByColumnName()
|
||||
{
|
||||
$columnName = $this->_getParam('name', '');
|
||||
$val = $this->_getParam('val', '');
|
||||
|
||||
$data = $this->_genericModel->getByColumnName($this->_resourceName, $columnName, $val);
|
||||
|
||||
$this->_responseData->data = $data;
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve per applicare eventuali filtri fissi
|
||||
* @param $where
|
||||
* @return mixed
|
||||
*/
|
||||
public function setFixedSelectWhere($where)
|
||||
{
|
||||
return $where;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve ad applicare un eventuale joinData
|
||||
* @param $params
|
||||
*/
|
||||
public function checkIfSetJoinData($params)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve ad applicare un eventuale groupBy
|
||||
* @param $params
|
||||
*/
|
||||
public function checkIfSetGroupBy($params)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
//##################################### HELPERS FUNCTIONS ###################################################
|
||||
|
||||
public function getSingleElementManipulate($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function preInsertElement($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function afterInsertElement($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function preUpdateElement($data, $id)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function afterUpdateElement($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function preDeleteElement($id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
public function afterDeleteElement($id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//##################################### GENERIC FUNCTIONS ##########################################################
|
||||
|
||||
public function sendResponse()
|
||||
{
|
||||
|
||||
if (!$this->_status) {
|
||||
$message = (!$this->_responseData->message) ? "Errore non identificato sul web service risorsa: '$this->_resourceName'" : $this->_responseData->message;
|
||||
$errorCode = (!$this->_responseData->errorCode) ? App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR : $this->_responseData->errorCode;
|
||||
|
||||
$this->sendErrorResponse($message, $errorCode);
|
||||
}
|
||||
|
||||
if (isset($this->_responseData->data)) {
|
||||
if ($this->_responseData->data instanceof Zend_Paginator) {
|
||||
$this->_responseData->totalItems = $this->_genericModel->getCountTotal($this->_resourceName);
|
||||
$this->_responseData->currentItemsCount = $this->_responseData->data->getTotalItemCount();
|
||||
$this->_responseData->data = (array)$this->_responseData->data->getCurrentItems();
|
||||
} else if (is_array($this->_responseData->data)) {
|
||||
$this->_responseData->totalItems = $this->_genericModel->getCountTotal($this->_resourceName);
|
||||
$this->_responseData->currentItemsCount = count($this->_responseData->data);
|
||||
} else if (is_string($this->_responseData->data)) {
|
||||
$this->_responseData->data = array('message' => $this->_responseData->data);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->_inArray) {
|
||||
$content = $this->_responseData->data;
|
||||
$this->getResponse()
|
||||
->setHeader('X-Page', $this->getParam('page'))
|
||||
->setHeader('X-Count', $this->getParam('count'))
|
||||
->setHeader('X-Tot-Filtered', $this->_responseData->currentItemsCount)
|
||||
->setHeader('X-Tot-Items', $this->_responseData->totalItems);
|
||||
} else {
|
||||
$content = ($this->_responseData->data);
|
||||
}
|
||||
|
||||
$this->getResponse()
|
||||
->setHeader('Content-Type', 'application/json;charset=utf-8')
|
||||
->setBody($this->_helper->Globalfunction->safeJsonEncode($content))
|
||||
->sendResponse();
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
public function sendErrorResponse($message, $errorCode, $dbName = null)
|
||||
{
|
||||
|
||||
$message = (!$message) ? "Errore non identificato sul web service risorsa: '$this->_resourceName'" : $message;
|
||||
$errorCode = (!$errorCode) ? App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR : $errorCode;
|
||||
|
||||
throw new App_Controller_Errors_WebServiceError(utf8_encode($message), $dbName, $errorCode);
|
||||
}
|
||||
|
||||
public function disableCallAction()
|
||||
{
|
||||
// Disabilito la risorsa
|
||||
$this->sendErrorResponse("Funzione non disponibile", App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_NOPERMISSION);
|
||||
}
|
||||
|
||||
public function getAddFormForResource()
|
||||
{
|
||||
|
||||
$class = implode('_', array(
|
||||
'Application_Form',
|
||||
strtoupper($this->getRequest()->getModuleName()),
|
||||
ucfirst($this->_resourceFormName),
|
||||
'Add'));
|
||||
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Classe '$class' potrebbe non esistere");
|
||||
}
|
||||
|
||||
return new $class();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
<?php
|
||||
|
||||
abstract class App_Controller_Rest_MongoController extends Zend_Rest_Controller
|
||||
{
|
||||
|
||||
public $_resourceName;
|
||||
|
||||
public $_responseData;
|
||||
public $_status;
|
||||
public $_inArray;
|
||||
|
||||
public $_mongoModel;
|
||||
|
||||
public function init()
|
||||
{
|
||||
$this->_helper->viewRenderer->setNoRender(true);
|
||||
$this->_helper->AjaxContext()
|
||||
->addActionContext('get', 'json')
|
||||
->addActionContext('post', 'json')
|
||||
->addActionContext('put', 'json')
|
||||
->addActionContext('patch', 'json')
|
||||
->addActionContext('delete', 'json')
|
||||
->addActionContext('options', 'json')
|
||||
->addActionContext('head', 'json')
|
||||
->initContext('json');
|
||||
|
||||
}
|
||||
|
||||
public function preDispatch()
|
||||
{
|
||||
$this->_responseData = new stdClass();
|
||||
$this->_status = false;
|
||||
$this->_inArray = false;
|
||||
|
||||
$this->_mongoModel = new App_Model_Mongo_Client();
|
||||
|
||||
$this->_response->setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Authorization,x-requested-with,Content-Type,Cache-Control,X-As-Dev-On,X-As-Dev-Pw');
|
||||
$this->_response->setHeader('Access-Control-Expose-Headers', 'X-Tot-Items, X-Page,X-Count,X-Tot-Filtered');
|
||||
$this->_response->setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, PATCH, DELETE');
|
||||
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
|
||||
$this->_response->setHeader('Access-Control-Allow-Credentials', 'true');
|
||||
|
||||
// Controllo sui metodi di prefetch
|
||||
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
|
||||
return $this->optionsAction();
|
||||
}
|
||||
|
||||
if($_SERVER['REQUEST_METHOD'] === 'HEAD'){
|
||||
return $this->optionsAction();
|
||||
}
|
||||
|
||||
if($_SERVER['REQUEST_METHOD'] === 'PATCH'){
|
||||
return $this->patchAction();
|
||||
}
|
||||
}
|
||||
|
||||
//##################################### CRUD FUNCTIONS #############################################################
|
||||
|
||||
public function indexAction()
|
||||
{
|
||||
$this->getAction();
|
||||
}
|
||||
|
||||
public function getAction()
|
||||
{
|
||||
|
||||
try {
|
||||
switch ($this->_getParam('method')) {
|
||||
default:
|
||||
if ($this->_getParam('id') != null) {
|
||||
$this->_responseData->data = $this->getSingleElement($this->_getParam('id'));
|
||||
} else {
|
||||
$this->_inArray = true;
|
||||
|
||||
$page = intval($this->_getParam('page', null));
|
||||
$count = intval($this->_getParam('count', null));
|
||||
$order = $this->_getParam('order', null);
|
||||
//$projection = $this->_helper->MongoProjectionFunctions($this->_getParam('select', null), $this->_defaultProjection);
|
||||
$projection = $this->_getParam('select', null);
|
||||
$addFields = null;
|
||||
|
||||
$where = $this->_helper->MongoFilterFunctions($this->getAllParams());
|
||||
|
||||
$where = $this->handleGetListFilters($where);
|
||||
|
||||
$data = $this->_mongoModel->getListAggregation($this->_resourceName, $page, $count, $where, $order, $projection, $addFields);
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($data,true));
|
||||
|
||||
$this->_responseData->data = $data;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
$this->_status = false;
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function postAction()
|
||||
{
|
||||
|
||||
try {
|
||||
|
||||
$params = Zend_Json::decode($this->getRequest()->getRawBody());
|
||||
|
||||
$form = $this->getAddFormForResource();
|
||||
|
||||
//Inserimento di un singolo elemento
|
||||
if (!$form->isValid($params)) {
|
||||
$this->_status = false;
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_FORM_DATAINVALID;
|
||||
$this->_responseData->message = 'I dati inseriti non sono validi';
|
||||
$this->_responseData->errorDetails = $form->getMessages();
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$dati = $form->getValues();
|
||||
|
||||
$dati = $this->preInsertElement($dati);
|
||||
|
||||
$dati['id'] = $this->insertSingleElement($dati);
|
||||
|
||||
$dati = $this->afterInsertElement($dati);
|
||||
|
||||
$this->_responseData->data = array('data' => $dati);
|
||||
$this->_status = true;
|
||||
|
||||
$this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function putAction()
|
||||
{
|
||||
try {
|
||||
$params = Zend_Json::decode($this->getRequest()->getRawBody());
|
||||
|
||||
$form = $this->getAddFormForResource();
|
||||
|
||||
//Aggiornamento singolo
|
||||
if (!$form->isValidPartial($params)) {
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_FORM_DATAINVALID;
|
||||
$this->_responseData->message = 'I dati inseriti non sono validi';
|
||||
$this->_responseData->errorDetails = $form->getMessages();
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$dati = $form->getValues();
|
||||
|
||||
if (!$this->_getParam('id')) {
|
||||
$this->_responseData->message = 'Id elemento non trovato';
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$dati = $this->preUpdateElement($dati, $this->_getParam('id'));
|
||||
|
||||
$this->updateSingleElement($this->_getParam('id'), $dati);
|
||||
$dati['id'] = $this->_getParam('id');
|
||||
|
||||
$dati = $this->afterUpdateElement($dati);
|
||||
|
||||
$this->_responseData->data = array('data' => $dati);
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function patchAction()
|
||||
{
|
||||
try {
|
||||
$params = Zend_Json::decode($this->getRequest()->getRawBody());
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($params,true));
|
||||
|
||||
$form = $this->getAddFormForResource();
|
||||
|
||||
//Aggiornamento singolo
|
||||
if (!$form->isValidPartial($params)) {
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_FORM_DATAINVALID;
|
||||
$this->_responseData->message = 'I dati inseriti non sono validi';
|
||||
$this->_responseData->errorDetails = $form->getMessages();
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
$dati = $form->getValues();
|
||||
|
||||
//rimuovo i valori vuoti che non devono essere sovrascritti
|
||||
foreach ($dati as $key => $val){
|
||||
if(!$val) unset($dati[$key]);
|
||||
}
|
||||
|
||||
$id = $this->_getParam('id');
|
||||
if (!$id) {
|
||||
$this->_responseData->message = 'Id elemento non trovato';
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($dati,true));
|
||||
|
||||
$oldElement = (array) $this->_mongoModel->getById($this->_resourceName, $id);
|
||||
$dati = array_merge($oldElement, $dati);
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($oldElement,true));
|
||||
|
||||
$dati = $this->preUpdateElement($dati, $id);
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($dati,true));
|
||||
|
||||
$this->updateSingleElement($id, $dati);
|
||||
$dati['id'] = $id;
|
||||
|
||||
$dati = $this->afterUpdateElement($dati);
|
||||
|
||||
$this->_responseData->data = array('data' => $dati);
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
$this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteAction()
|
||||
{
|
||||
try {
|
||||
|
||||
if (!$this->_getParam('id')) {
|
||||
$this->_status = false;
|
||||
$this->_responseData->message = "Errore id non trovato";
|
||||
$this->_responseData->errorCode = App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_NOIDERROR;
|
||||
return $this->sendResponse();
|
||||
}
|
||||
|
||||
//Eliminazione Singola
|
||||
$this->deleteSingleElement($this->_getParam('id'));
|
||||
|
||||
$this->_status = true;
|
||||
return $this->sendResponse();
|
||||
} catch (Exception $e) {
|
||||
$this->_responseData->message = $e->getMessage();
|
||||
return $this->sendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
public function headAction()
|
||||
{
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
public function optionsAction()
|
||||
{
|
||||
$this->_status = true;
|
||||
$this->sendResponse();
|
||||
}
|
||||
|
||||
//##################################### SINGLE ELEMENT FUNCTIONS ###################################################
|
||||
|
||||
public function getSingleElement($id)
|
||||
{
|
||||
return $this->getSingleElementManipulate($this->_mongoModel->getById($this->_resourceName, $id));
|
||||
}
|
||||
|
||||
public function insertSingleElement($dati)
|
||||
{
|
||||
return $this->_mongoModel->insert($this->_resourceName, $dati);
|
||||
}
|
||||
|
||||
public function updateSingleElement($id, $dati)
|
||||
{
|
||||
return $this->_mongoModel->update($this->_resourceName, $id, $dati);
|
||||
}
|
||||
|
||||
public function deleteSingleElement($id)
|
||||
{
|
||||
return $this->_mongoModel->delete($this->_resourceName, $id);
|
||||
}
|
||||
|
||||
//##################################### HELPERS FUNCTIONS ###################################################
|
||||
|
||||
public function getSingleElementManipulate($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function preInsertElement($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function afterInsertElement($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function preUpdateElement($data, $id)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function afterUpdateElement($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function handleGetListFilters($where){
|
||||
return $where;
|
||||
}
|
||||
|
||||
//##################################### GENERIC FUNCTIONS ##########################################################
|
||||
|
||||
public function sendResponse()
|
||||
{
|
||||
|
||||
if (!$this->_status) {
|
||||
$message = (!$this->_responseData->message) ? "Errore non identificato sul web service risorsa: '$this->_resourceName'" : $this->_responseData->message;
|
||||
$errorCode = (!$this->_responseData->errorCode) ? App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR : $this->_responseData->errorCode;
|
||||
|
||||
$this->sendErrorResponse($message, $errorCode);
|
||||
}
|
||||
|
||||
if (isset($this->_responseData->data) && is_array($this->_responseData->data)) {
|
||||
$this->_responseData->totalItems = $this->_mongoModel->getCountTotal($this->_resourceName);
|
||||
|
||||
if (Zend_Registry::isRegistered(App_Model_Mongo_Client::WHERE_MONGO_REG_NAME)) {
|
||||
$this->_responseData->currentItemsCount = $this->_mongoModel->getCountFilteredTotal($this->_resourceName, Zend_Registry::get(App_Model_Mongo_Client::WHERE_MONGO_REG_NAME));
|
||||
} else {
|
||||
$this->_responseData->currentItemsCount = $this->_responseData->totalItems;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->_inArray) {
|
||||
$content = $this->_responseData->data;
|
||||
$this->getResponse()
|
||||
->setHeader('X-Page', $this->getParam('page'))
|
||||
->setHeader('X-Count', $this->getParam('count'))
|
||||
->setHeader('X-Tot-Filtered', $this->_responseData->currentItemsCount)
|
||||
->setHeader('X-Tot-Items', $this->_responseData->totalItems);
|
||||
} else {
|
||||
$content = ($this->_responseData->data);
|
||||
}
|
||||
|
||||
$this->getResponse()
|
||||
->setHeader('Content-Type', 'application/json;charset=utf-8')
|
||||
->setBody($this->_helper->Globalfunction->safeJsonEncode($content))
|
||||
->sendResponse();
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
public function sendErrorResponse($message, $errorCode, $dbName = null)
|
||||
{
|
||||
|
||||
$message = (!$message) ? "Errore non identificato sul web service risorsa: '$this->_resourceName'" : $message;
|
||||
$errorCode = (!$errorCode) ? App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR : $errorCode;
|
||||
|
||||
throw new App_Controller_Errors_WebServiceError(utf8_encode($message), $dbName, $errorCode);
|
||||
}
|
||||
|
||||
public function disableCallAction()
|
||||
{
|
||||
// Disabilito la risorsa
|
||||
$this->sendErrorResponse("Funzione non disponibile", App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_NOPERMISSION);
|
||||
}
|
||||
|
||||
protected function getAddFormForResource()
|
||||
{
|
||||
|
||||
$class = implode('_', array(
|
||||
'Application_Form',
|
||||
strtoupper($this->getRequest()->getModuleName()),
|
||||
ucfirst($this->_resourceName),
|
||||
'Add'));
|
||||
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Classe '$class' potrebbe non esistere");
|
||||
}
|
||||
|
||||
return new $class();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class App_Controller_Sections_AbstractSection
|
||||
* Versione: 1.0.0
|
||||
* Data Ultimo Update: 13/01/2021
|
||||
*
|
||||
* Questa classe astratta serve a definire le funzioni generiche per ogni sezione che si vuole creare nell'admin andando ad ereditare
|
||||
* tutti le funzioni crud di base
|
||||
*
|
||||
* lista | get | save | delete | deleteSelect | setstate | setstateSelect
|
||||
*/
|
||||
|
||||
abstract class App_Controller_Sections_AbstractSection
|
||||
{
|
||||
const COOKIE_BASE_STRING_VARIABLE_NAME = "#resource#_#module#_#site#_";
|
||||
|
||||
private $_COUNT_VARIABLE_NAME;
|
||||
private $_ORDER_VARIABLE_NAME;
|
||||
private $_ORDERTYPE_VARIABLE_NAME;
|
||||
private $_SEARCHPARAMS_VARIABLE_NAME;
|
||||
|
||||
private $_COOKIE_EXPIRE_TIME;
|
||||
|
||||
protected $_controller;
|
||||
public $_model;
|
||||
|
||||
protected $_resourceName;
|
||||
|
||||
protected $_enableModalFilter = false;
|
||||
protected $_enableModalDetail = true;
|
||||
protected $_enableNewInsert = true;
|
||||
|
||||
public $_joinData = null;
|
||||
public $_groupBy = null;
|
||||
|
||||
public $_defaultCount = '50';
|
||||
|
||||
public $_SEARCH_PARAMS;
|
||||
public $_PAGE;
|
||||
public $_COUNT;
|
||||
public $_ORDERLIST;
|
||||
public $_ORDERLIST_TYPE;
|
||||
|
||||
protected $_customJsSectionScripts;
|
||||
protected $_customCssSectionScripts;
|
||||
protected $_angularModuleName;
|
||||
|
||||
public function __construct(App_Controller_Sections_Section $controller)
|
||||
{
|
||||
$this->_controller = $controller;
|
||||
$this->_model = $controller->getMainModel();
|
||||
|
||||
if (!($this->_controller->_configs instanceof App_Service_ConfigManager))
|
||||
throw new Exception("E' necessario instanziare nella classe " . get_class($this->_controller) . " la proprietà '_configs' come App_Service_ConfigManager");
|
||||
|
||||
$this->_COOKIE_EXPIRE_TIME = time() + (86400 * 30);
|
||||
|
||||
$BASE_COOKIE_STRING = str_replace('#module#', strtolower($this->_controller->getRequest()->getModuleName()),
|
||||
str_replace('#site#', strtolower(Zend_Registry::get('ENVIROMENTS')->get('site_short_id')),
|
||||
str_replace('#resource#', strtolower($this->_resourceName), self::COOKIE_BASE_STRING_VARIABLE_NAME)));
|
||||
|
||||
$this->_COUNT_VARIABLE_NAME = $BASE_COOKIE_STRING . "count";
|
||||
$this->_ORDER_VARIABLE_NAME = $BASE_COOKIE_STRING . "order";
|
||||
$this->_ORDERTYPE_VARIABLE_NAME = $BASE_COOKIE_STRING . "ordertype";
|
||||
$this->_SEARCHPARAMS_VARIABLE_NAME = $BASE_COOKIE_STRING . "searchparams";
|
||||
}
|
||||
|
||||
/***************************************************************************************************************
|
||||
************************************** FUNZIONI CRUD ***********************************************
|
||||
**************************************************************************************************************/
|
||||
|
||||
public function lista()
|
||||
{
|
||||
|
||||
$this->listPreDispatch();
|
||||
|
||||
$this->handleSearchListParams();
|
||||
|
||||
$this->checkIfSetJoinData($this->_SEARCH_PARAMS);
|
||||
$this->checkIfSetGroupBy($this->_SEARCH_PARAMS);
|
||||
|
||||
$orderString = $this->_ORDERLIST . ' ' . $this->_ORDERLIST_TYPE;
|
||||
|
||||
$where = $this->_controller->getHelper('FilterFunctions')->direct($this->_SEARCH_PARAMS, true);
|
||||
$list = $this->_model->getList($this->_resourceName, $this->_PAGE, $this->_COUNT, $where, $orderString, '*', $this->_joinData, $this->_groupBy);
|
||||
|
||||
if ($list instanceof Zend_Paginator) {
|
||||
$list->setPageRange(5);
|
||||
$this->_controller->view->totFiltrati = $list->getTotalItemCount();
|
||||
} else {
|
||||
$this->_controller->view->totFiltrati = count($list);
|
||||
}
|
||||
|
||||
$this->_controller->view->totElementi = $this->_model->getCountTotal($this->_resourceName);
|
||||
$this->_controller->view->table = $list;
|
||||
|
||||
$this->listPostDispatch();
|
||||
}
|
||||
|
||||
public function get()
|
||||
{
|
||||
$this->_controller->getHelper('layout')->disableLayout();
|
||||
$this->_controller->getHelper('viewRenderer')->setNoRender();
|
||||
|
||||
if ($this->_controller->getRequest()->isXmlHttpRequest()) {
|
||||
if (!$this->_controller->getParam('id')) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => false, 'message' => 'Id non ricevuto')));
|
||||
}
|
||||
$element = $this->_model->getById($this->_resourceName, $this->_controller->getParam('id'));
|
||||
if (!$element) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => false, 'message' => $this->_resourceName . ' non trovato'), false));
|
||||
}
|
||||
|
||||
if (method_exists($this, 'getElement')) {
|
||||
$element = $this->getElement($element);
|
||||
}
|
||||
|
||||
$response = Zend_Json::encode(array_merge($element, array('success' => true)));
|
||||
$this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody($response);
|
||||
}
|
||||
}
|
||||
|
||||
public function save()
|
||||
{
|
||||
$this->_controller->getHelper('layout')->disableLayout();
|
||||
$this->_controller->getHelper('viewRenderer')->setNoRender();
|
||||
|
||||
if ($this->_controller->getRequest()->isXmlHttpRequest()) {
|
||||
|
||||
if (!$this->_controller->getRequest()->isPost()) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => FALSE, 'message' => 'Errore durante la richiesta.')));
|
||||
}
|
||||
|
||||
$form = $this->getDefaultSaveFormClassName();
|
||||
if (!$form->isValid($_POST)) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => 'invalid',
|
||||
'message' => 'Controllare i dati inseriti nei campi sono presenti errori.',
|
||||
'errors' => $form->getMessages())));
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$dati = $form->getValues();
|
||||
$id = $this->_controller->getParam('id');
|
||||
$op = $this->_controller->getParam('op');
|
||||
|
||||
$response = array();
|
||||
$response['id'] = $id;
|
||||
$response['op'] = $op;
|
||||
|
||||
if ($op == 'insert') {
|
||||
$dati = $this->preInsertFunction($dati);
|
||||
|
||||
$dati['id'] = $this->insertFunction($dati);
|
||||
|
||||
$dati = $this->afterInsertFunction($dati);
|
||||
} else {
|
||||
|
||||
if (!$id) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody(Zend_Json::encode(array('success' => FALSE,
|
||||
'message' => 'Errore id non ricevuto')));
|
||||
}
|
||||
|
||||
$dati = $this->preUpdateFunction($dati, $id);
|
||||
|
||||
$this->updateFunction($id, $dati);
|
||||
$dati['id'] = $id;
|
||||
|
||||
$dati = $this->afterUpdateFunction($dati, $id);
|
||||
}
|
||||
|
||||
$this->_controller->view->assign($dati);
|
||||
$this->_controller->render(strtolower($this->_resourceName) . '/td');
|
||||
|
||||
$response['text'] = $this->_controller->getResponse()->getBody();
|
||||
$response['data'] = $dati;
|
||||
|
||||
$response['success'] = true;
|
||||
$this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode($response));
|
||||
} catch (Exception $e) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('stato' => false,
|
||||
'shortMessage' => 'Si è verificato un errore durante il salvataggio dei dati',
|
||||
'message' => $e->getMessage())
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function delete()
|
||||
{
|
||||
if ($this->_controller->getRequest()->isXmlHttpRequest()) {
|
||||
|
||||
$this->_controller->getHelper('layout')->disableLayout();
|
||||
$this->_controller->getHelper('viewRenderer')->setNoRender();
|
||||
|
||||
if (!$this->_controller->getParam('id') || !$this->_controller->getParam('cod')) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody(Zend_Json::encode(array('success' => false,
|
||||
'message' => 'Id o codice non trovato.')));
|
||||
}
|
||||
|
||||
try {
|
||||
$this->deleteSingleElement($this->_controller->getParam('id'));
|
||||
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody(Zend_Json::encode(array('success' => true)));
|
||||
} catch (Exception $e) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody(Zend_Json::encode(array('success' => false,
|
||||
'message' => 'Si è verificato un errore durante l\'eliminazione.' . $e->getMessage())));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteSelect()
|
||||
{
|
||||
$this->_controller->getHelper('layout')->disableLayout();
|
||||
$this->_controller->getHelper('viewRenderer')->setNoRender();
|
||||
if ($this->_controller->getRequest()->isXmlHttpRequest()) {
|
||||
if ($this->_controller->getParam('data')) {
|
||||
$data = $this->_controller->getParam('data');
|
||||
if (count($data) <= 0) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody(Zend_Json::encode(array('success' => FALSE, 'message' => 'Nessun elemento selezionato')));
|
||||
}
|
||||
$response['success'] = 'TRUE';
|
||||
$response['id'] = array();
|
||||
foreach ($data as $key => $value) {
|
||||
array_push($response['id'], $value);
|
||||
$this->deleteSingleElement($value);
|
||||
}
|
||||
} else {
|
||||
$response['success'] = FALSE;
|
||||
$response['message'] = "Si è verificato un errore durante l'eliminazione";
|
||||
}
|
||||
$response = Zend_Json::encode($response);
|
||||
$this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody($response);
|
||||
}
|
||||
}
|
||||
|
||||
public function setstate()
|
||||
{
|
||||
if ($this->_controller->getRequest()->isXmlHttpRequest()) {
|
||||
|
||||
$this->_controller->getHelper('layout')->disableLayout();
|
||||
$this->_controller->getHelper('viewRenderer')->setNoRender();
|
||||
|
||||
if (!$this->_controller->getParam('id')) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => FALSE, 'message' => 'Id non trovato.')));
|
||||
}
|
||||
|
||||
try {
|
||||
$this->_model->update('Errorlog', $this->_controller->getParam('id'), array('state' => $this->_controller->getParam('state')));
|
||||
|
||||
$this->_controller->view->assign($this->_model->getById('Errorlog', $this->_controller->getParam('id')));
|
||||
|
||||
$this->_controller->render('errorlog/td');
|
||||
$response['text'] = $this->_controller->getResponse()->getBody();
|
||||
$response['success'] = true;
|
||||
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody(Zend_Json::encode($response));
|
||||
} catch (Exception $e) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => FALSE, 'message' => 'Si è verificato un errore durante l\'eliminazione.')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function setstateSelect()
|
||||
{
|
||||
|
||||
$this->_controller->getHelper('layout')->disableLayout();
|
||||
$this->_controller->getHelper('viewRenderer')->setNoRender();
|
||||
|
||||
if ($this->_controller->getRequest()->isXmlHttpRequest()) {
|
||||
|
||||
if ($this->_controller->getParam('data')) {
|
||||
|
||||
$data = $this->_controller->getParam('data');
|
||||
|
||||
if (count($data) <= 0) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => FALSE, 'message' => 'Nessun elemento selezionato')));
|
||||
}
|
||||
|
||||
$state = $this->_controller->getParam('state');
|
||||
if (!$state) {
|
||||
return $this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')
|
||||
->setBody(Zend_Json::encode(array('success' => FALSE, 'message' => 'Stato da impostare non selezionato')));
|
||||
}
|
||||
|
||||
$response['rows'] = array();
|
||||
foreach ($data as $key => $value) {
|
||||
|
||||
$this->_controller->getResponse()->setBody("");
|
||||
|
||||
$this->_model->update($this->_resourceName, $value, array('state' => $state));
|
||||
|
||||
$this->_controller->view->assign($this->_model->getById($this->_resourceName, $value));
|
||||
|
||||
$this->_controller->render('errorlog/td');
|
||||
$tdRow = array(
|
||||
'id' => $value,
|
||||
'tdRow' => $this->_controller->getResponse()->getBody()
|
||||
);
|
||||
|
||||
array_push($response['rows'], $tdRow);
|
||||
}
|
||||
|
||||
$response['success'] = true;
|
||||
|
||||
} else {
|
||||
$response['success'] = FALSE;
|
||||
$response['message'] = "Si è verificato un errore durante l'aggiornamento dei dati";
|
||||
}
|
||||
|
||||
$response = Zend_Json::encode($response);
|
||||
$this->_controller->getResponse()->setHeader('Content-type', 'application/json;charset=UTF-8')->setBody($response);
|
||||
}
|
||||
}
|
||||
|
||||
/***************************************************************************************************************
|
||||
*********************************** FUNZIONI SPECIALIZZATE *****************************************
|
||||
**************************************************************************************************************/
|
||||
|
||||
/**
|
||||
* Serve a manipolare i search params dopo che sono stati recuperati dallo storage e ad esempio a fissare dei parametri fissi
|
||||
*/
|
||||
public function handleSearchListParams(){
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve a impostare il joinData i params vengono passati per essere utilizzati per eventuali condizioni
|
||||
* @param $params
|
||||
*/
|
||||
public function checkIfSetJoinData($params){
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve a impostare il groupBy i params vengono passati per essere utilizzati per eventuali condizioni
|
||||
* @param $params
|
||||
*/
|
||||
public function checkIfSetGroupBy($params){
|
||||
|
||||
}
|
||||
|
||||
//Funzione di eliminazione singolo elemento personalizzarabile definendo il metodo deleteElement
|
||||
protected function deleteSingleElement($id)
|
||||
{
|
||||
$this->preDeleteFunction($id);
|
||||
|
||||
if (method_exists($this, 'deleteElement')) {
|
||||
$this->deleteElement($id);
|
||||
} else {
|
||||
$this->_model->delete($this->_resourceName, $id);
|
||||
}
|
||||
|
||||
$this->afterDeleteFunction($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione da sovrascrivere che viene eseguita prima l'inserimento dell'elemento nel db; (deve restiuire i dati)
|
||||
* @param $data
|
||||
* @return mixed
|
||||
*/
|
||||
public function preInsertFunction($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione che effettua il singolo inserimento dell'elemento
|
||||
*
|
||||
* @param array $dati
|
||||
* @return mixed
|
||||
*/
|
||||
public function insertFunction(array $dati){
|
||||
return $this->_model->insert($this->_resourceName, $dati);
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione da sovrascrivere che viene eseguita dopo l'inserimento dell'elemento nel db; (deve restiuire i dati)
|
||||
* @param $data
|
||||
* @return mixed
|
||||
*/
|
||||
public function afterInsertFunction($data)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione da sovrascrivere che viene eseguita prima l'aggiornamento dei dati nel db; (deve restiuire i dati)
|
||||
* @param $data
|
||||
* @return mixed
|
||||
*/
|
||||
public function preUpdateFunction($data, $id)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione che effettua il singolo update dell'elemento
|
||||
* @param $id
|
||||
* @param array $dati
|
||||
*/
|
||||
public function updateFunction($id, array $dati){
|
||||
$this->_model->update($this->_resourceName, $id, $dati);
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione da sovrascrivere che viene eseguita dopo l'aggiornamento dei dati nel db; (deve restiuire i dati)
|
||||
* @param $data
|
||||
* @return mixed
|
||||
*/
|
||||
public function afterUpdateFunction($data, $id)
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione da sovrascrivere che viene eseguita prima dell'eliminazione dell'elemento nel db; (più che altro è una funzione di controllo)
|
||||
* @param $id
|
||||
* @return mixed
|
||||
*/
|
||||
public function preDeleteFunction($id)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Funzione che viene eseguita appena dopo l'eliminazione
|
||||
* @param $id
|
||||
* @return null
|
||||
*/
|
||||
public function afterDeleteFunction($id)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*
|
||||
* Restituisce la classe Form generica "Add" per la sezione
|
||||
*/
|
||||
public function getDefaultSaveFormClassName()
|
||||
{
|
||||
$class = implode('_', array(
|
||||
'Application',
|
||||
'Form',
|
||||
ucfirst($this->_controller->getRequest()->getModuleName()),
|
||||
ucfirst($this->_controller->getRequest()->getControllerName()),
|
||||
$this->_resourceName,
|
||||
'Add'));
|
||||
return new $class();
|
||||
}
|
||||
|
||||
private function listPreDispatch()
|
||||
{
|
||||
|
||||
$this->_controller->view->resourceName = strtolower($this->_resourceName);
|
||||
$this->_controller->view->isActiveModalDetail = $this->_enableModalDetail;
|
||||
$this->_controller->view->isActiveFilterModal = $this->_enableModalFilter;
|
||||
$this->_controller->view->isActiveNewInsert = $this->_enableNewInsert;
|
||||
$this->_controller->view->customJsScript = $this->_customJsSectionScripts;
|
||||
$this->_controller->view->customCssScript = $this->_customCssSectionScripts;
|
||||
|
||||
$count = $this->_controller->getParam('count');
|
||||
if ($count !== null && intval($count) != 0) {
|
||||
$this->_COUNT = intval($count);
|
||||
setcookie($this->_COUNT_VARIABLE_NAME, intval($count), $this->_COOKIE_EXPIRE_TIME, "/");
|
||||
} else {
|
||||
if (isset($_COOKIE[$this->_COUNT_VARIABLE_NAME])) {
|
||||
$this->_COUNT = intval($_COOKIE[$this->_COUNT_VARIABLE_NAME]);
|
||||
} else {
|
||||
$this->_COUNT = $this->_defaultCount;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->_controller->getParam('reset')) {
|
||||
$this->_PAGE = 1;
|
||||
//$this->_COUNT = $this->_defaultCount;
|
||||
$this->_ORDERLIST = $this->_model->getResource($this->_resourceName)->getDefaultOrder();
|
||||
$this->_ORDERLIST_TYPE = $this->_model->getResource($this->_resourceName)->getDefaultTipoOrder();
|
||||
$this->_SEARCH_PARAMS = array();
|
||||
|
||||
//Resetto anche i cookie
|
||||
//setcookie($this->_COUNT_VARIABLE_NAME, intval($this->_COUNT), $this->_COOKIE_EXPIRE_TIME, "/");
|
||||
setcookie($this->_ORDER_VARIABLE_NAME, $this->_ORDERLIST, $this->_COOKIE_EXPIRE_TIME, "/");
|
||||
setcookie($this->_ORDERTYPE_VARIABLE_NAME, $this->_ORDERLIST_TYPE, $this->_COOKIE_EXPIRE_TIME, "/");
|
||||
setcookie($this->_SEARCHPARAMS_VARIABLE_NAME, Zend_Json::encode($this->_SEARCH_PARAMS), $this->_COOKIE_EXPIRE_TIME, "/");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->_PAGE = $this->_controller->getParam('page', 1);
|
||||
|
||||
if (isset($_COOKIE[$this->_ORDER_VARIABLE_NAME]) && !$this->_controller->getParam('order')) {
|
||||
$this->_ORDERLIST = $_COOKIE[$this->_ORDER_VARIABLE_NAME];
|
||||
//Zend_Registry::get('log')->info(print_r("ORDERLIST_COOKIE_PARAM: ".$this->_ORDERLIST,true));
|
||||
} else {
|
||||
$this->_ORDERLIST = $this->_controller->getParam('order', $this->_model->getResource($this->_resourceName)->getDefaultOrder());
|
||||
//Zend_Registry::get('log')->info(print_r("ORDERLIST_NEW_PARAM: ".$this->_ORDERLIST,true));
|
||||
setcookie($this->_ORDER_VARIABLE_NAME, $this->_ORDERLIST, $this->_COOKIE_EXPIRE_TIME, "/");
|
||||
}
|
||||
|
||||
if (isset($_COOKIE[$this->_ORDERTYPE_VARIABLE_NAME]) && !$this->_controller->getParam('tipoOrder')) {
|
||||
$this->_ORDERLIST_TYPE = $_COOKIE[$this->_ORDERTYPE_VARIABLE_NAME];
|
||||
//Zend_Registry::get('log')->info(print_r("ORDERLISTTYPE_COOKIE_PARAM: ".$this->_ORDERLIST_TYPE,true));
|
||||
} else {
|
||||
$this->_ORDERLIST_TYPE = $this->_controller->getParam('tipoOrder', $this->_model->getResource($this->_resourceName)->getDefaultTipoOrder());
|
||||
//Zend_Registry::get('log')->info(print_r("ORDERLISTTYPE_NEW_PARAM: ".$this->_ORDERLIST_TYPE,true));
|
||||
setcookie($this->_ORDERTYPE_VARIABLE_NAME, $this->_ORDERLIST_TYPE, $this->_COOKIE_EXPIRE_TIME, "/");
|
||||
}
|
||||
|
||||
if (isset($_COOKIE[$this->_SEARCHPARAMS_VARIABLE_NAME])) {
|
||||
$this->_SEARCH_PARAMS = Zend_Json::Decode($_COOKIE[$this->_SEARCHPARAMS_VARIABLE_NAME]);
|
||||
} else {
|
||||
$this->_SEARCH_PARAMS = array();
|
||||
}
|
||||
|
||||
//Aggiungo eventuali nuovi parametri
|
||||
$params = $this->_controller->getHelper('FilterFunctions')->cleanParams($this->_controller->getAllParams(), false);
|
||||
|
||||
//Riunisco i parametri gia esistenti con i nuovi
|
||||
$this->_SEARCH_PARAMS = array_replace($this->_SEARCH_PARAMS, $params);
|
||||
}
|
||||
|
||||
private function listPostDispatch()
|
||||
{
|
||||
$this->_controller->view->moduleName = $this->_controller->getRequest()->getModuleName();
|
||||
|
||||
$this->_controller->view->count = $this->_COUNT;
|
||||
$this->_controller->view->page = $this->_PAGE;
|
||||
$this->_controller->view->order = $this->_ORDERLIST;
|
||||
$this->_controller->view->tipoOrder = $this->_ORDERLIST_TYPE;
|
||||
$this->_controller->view->search_params = $this->_SEARCH_PARAMS;
|
||||
|
||||
//Elimino i parametri vuoti dalle searchparams
|
||||
$this->_SEARCH_PARAMS = $this->_controller->getHelper('FilterFunctions')->cleanParams($this->_controller->getAllParams());
|
||||
|
||||
setcookie($this->_SEARCHPARAMS_VARIABLE_NAME, Zend_Json::encode($this->_SEARCH_PARAMS), $this->_COOKIE_EXPIRE_TIME, '/');
|
||||
|
||||
//Cambio il nome dello script view in 'list'
|
||||
Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setScriptAction(strtolower($this->_resourceName) . '/list');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
|
||||
class App_Controller_Sections_Section extends Zend_Controller_Action
|
||||
{
|
||||
protected $_sections = [];
|
||||
|
||||
public function __call($methodName, $args)
|
||||
{
|
||||
$actionName = $this->getRequest()->getActionName();
|
||||
$sectionName = null;
|
||||
try {
|
||||
|
||||
if (preg_match("/^list/", $actionName)) {
|
||||
$sectionName = preg_replace("/list/", "", $actionName);
|
||||
return $this->generaSectionClass($sectionName)->lista();
|
||||
}
|
||||
|
||||
if (preg_match("/^get/", $actionName)) {
|
||||
$sectionName = preg_replace("/get/", "", $actionName);
|
||||
return $this->generaSectionClass($sectionName)->get();
|
||||
}
|
||||
|
||||
if (preg_match("/^save|^salva/", $actionName)) {
|
||||
$sectionName = preg_replace("/save|salva/", "", $actionName);
|
||||
return $this->generaSectionClass($sectionName)->save();
|
||||
}
|
||||
|
||||
if (preg_match("/^(?=.*?delete)(?!.*?select).*$/", $actionName)) {
|
||||
$sectionName = preg_replace("/delete/", "", $actionName);
|
||||
return $this->generaSectionClass($sectionName)->delete();
|
||||
}
|
||||
|
||||
if (preg_match("/^deleteselect/", $actionName)) {
|
||||
$sectionName = preg_replace("/deleteselect/", "", $actionName);
|
||||
return $this->generaSectionClass($sectionName)->deleteSelect();
|
||||
}
|
||||
|
||||
if (preg_match("/^(?=.*?setstate)(?!.*?select).*$/", $actionName)) {
|
||||
$sectionName = preg_replace("/setstate/", "", $actionName);
|
||||
return $this->generaSectionClass($sectionName)->setstate();
|
||||
}
|
||||
|
||||
if (preg_match("/^setstateselect/", $actionName)) {
|
||||
$sectionName = preg_replace("/setstateselect/", "", $actionName);
|
||||
return $this->generaSectionClass($sectionName)->setstateSelect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gestisce le funzione custom di un report se vengono separate dal trattino
|
||||
* con la stringa composta cosi: "<sectionName>-<functionName>"
|
||||
*/
|
||||
if (preg_match("/-/", $actionName)) {
|
||||
|
||||
$sectionName = explode('-', $actionName)[0];
|
||||
$functionName = explode('-', $actionName)[1];
|
||||
|
||||
// non funzionante con php 5
|
||||
// [$sectionName, $functionName] = explode('-', $actionName);
|
||||
|
||||
return $this->generaSectionClass($sectionName)->$functionName();
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
try {
|
||||
parent::__call($actionName, null);
|
||||
} catch (Exception $e2) {
|
||||
throw new Exception($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function generaSectionClass($sectionName)
|
||||
{
|
||||
if (!isset($this->_sections[$sectionName])) {
|
||||
$className = $this->getSectionClassName($sectionName);
|
||||
$this->_sections[$sectionName] = new $className($this);
|
||||
}
|
||||
return $this->_sections[$sectionName];
|
||||
}
|
||||
|
||||
private function getSectionClassName($sectionName)
|
||||
{
|
||||
return implode('_', array(
|
||||
'Application',
|
||||
'ControllerSection',
|
||||
ucfirst($this->getRequest()->getModuleName()),
|
||||
ucfirst($this->getRequest()->getControllerName()),
|
||||
ucfirst($sectionName)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
class App_Exception_MessageException extends Zend_Exception
|
||||
{
|
||||
protected $_appMessage;
|
||||
protected $_appCode;
|
||||
protected $_type;
|
||||
|
||||
const EXCEPTION_APP_MESSAGE='personalMessage';
|
||||
|
||||
const EXPECTION_FATTURAFE_NOTFOUND_ON2C = "EXPECTION_FATTURAFE_NOTFOUND_ON2C";
|
||||
|
||||
public function __construct($message,$code = null)
|
||||
{
|
||||
$this->message = $message;
|
||||
$this->_appMessage=$message;
|
||||
$this->_appCode=$code;
|
||||
}
|
||||
|
||||
public function getAppMessage(){
|
||||
return $this->_appMessage;
|
||||
}
|
||||
|
||||
public function getAppCode(){
|
||||
return $this->_appCode;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
class App_Exception_ResponseCloudException extends Zend_Rest_Exception
|
||||
{
|
||||
protected $_message;
|
||||
protected $_errorCode;
|
||||
|
||||
public function __construct($message,$errorCode)
|
||||
{
|
||||
parent::__construct($message);
|
||||
$this->_message = $message;
|
||||
$this->_errorCode=$errorCode;
|
||||
}
|
||||
|
||||
public function getMyMessage(){
|
||||
return $this->_message;
|
||||
}
|
||||
|
||||
public function getErrorCode(){
|
||||
return $this->_errorCode;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
class App_Form_Filters_MongoFormatBoolean implements Zend_Filter_Interface
|
||||
{
|
||||
public function filter($value)
|
||||
{
|
||||
$valueFiltered = 0;
|
||||
if($value === true || $value == '1' || $value == 1){
|
||||
$valueFiltered = 1;
|
||||
}
|
||||
|
||||
return $valueFiltered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
class App_Form_Filters_MongoFormatDatetime implements Zend_Filter_Interface
|
||||
{
|
||||
|
||||
public function filter($data)
|
||||
{
|
||||
|
||||
//Zend_Registry::get('log')->info(print_r('FormatData: '.$data,true));
|
||||
|
||||
$dateValidatorSlash = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy'));
|
||||
$dateValidatorSlashWithTime = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy HH:ii:ss'));
|
||||
$dateValidatorTrattino = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd'));
|
||||
|
||||
if($dateValidatorSlashWithTime->isValid($data)){
|
||||
$data = explode(' ', $data);
|
||||
$dataString = implode('-', array_reverse(explode("/", $data[0]))) ." ".$data[1];
|
||||
}else if ($dateValidatorSlash->isValid($data)) {
|
||||
$dataString = implode('-', array_reverse(explode("/", $data))) . $this->checkTimeString($data);
|
||||
}else if($dateValidatorTrattino->isValid($data)){
|
||||
$dataString = $data.$this->checkTimeString($data);
|
||||
}else{
|
||||
return $data;
|
||||
}
|
||||
|
||||
$orig_date = new DateTime($dataString);
|
||||
return new MongoDB\BSON\UTCDateTime($orig_date->getTimestamp() * 1000);
|
||||
}
|
||||
|
||||
//Controlla se aggiungere o no l'ora alla stringa
|
||||
private function checkTimeString($data)
|
||||
{
|
||||
return (preg_match('/[0-9]{2}:[0-9]{2}:[0-9]{2}/', $data)) ? '' : " 00:00:00";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
class App_Form_Filters_MongoFormatTimezone implements Zend_Filter_Interface
|
||||
{
|
||||
|
||||
public function filter($data)
|
||||
{
|
||||
|
||||
$dateValidatorSlash = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy'));
|
||||
$dateValidatorSlashWithTime = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy HH:ii:ss'));
|
||||
$dateValidatorTrattino = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd'));
|
||||
|
||||
if($dateValidatorSlashWithTime->isValid($data)){
|
||||
$data = explode(' ', $data);
|
||||
$dataString = implode('-', array_reverse(explode("/", $data[0]))) ." ".$data[1];
|
||||
}else if ($dateValidatorSlash->isValid($data)) {
|
||||
$dataString = implode('-', array_reverse(explode("/", $data))) . " 00:00:00";
|
||||
}else if($dateValidatorTrattino->isValid($data)){
|
||||
$dataString = $data." 00:00:00";
|
||||
}else{
|
||||
return $data;
|
||||
}
|
||||
|
||||
$orig_date = new DateTime($dataString);
|
||||
//Zend_Registry::get('log')->info(print_r($orig_date,true));
|
||||
return new MongoDB\BSON\Timestamp(1,$orig_date->getTimestamp());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
class App_Form_Filters_MyBoolean implements Zend_Filter_Interface
|
||||
{
|
||||
public function filter($value)
|
||||
{
|
||||
$valueFiltered = 0;
|
||||
if($value === true || $value == '1' || $value == 1){
|
||||
$valueFiltered = 1;
|
||||
}
|
||||
|
||||
return $valueFiltered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
class App_Form_Filters_MyFloatNumber implements Zend_Filter_Interface
|
||||
{
|
||||
|
||||
// se passato un valore non numerico o vuoto resitiuisce zero di default altrimenti null se abilitato
|
||||
private $_enableNull;
|
||||
|
||||
public function __construct($options = null)
|
||||
{
|
||||
$this->_enableNull = false;
|
||||
if (is_array($options) && array_key_exists('enable_null', $options)) {
|
||||
$this->_enableNull = $options['enable_null'];
|
||||
}
|
||||
}
|
||||
|
||||
public function filter($value)
|
||||
{
|
||||
if(!is_numeric($value)){
|
||||
return ($this->_enableNull) ? null : 0;
|
||||
}
|
||||
|
||||
return floatval($value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
class App_Form_Filters_MyFormatData implements Zend_Filter_Interface
|
||||
{
|
||||
|
||||
public function filter($data)
|
||||
{
|
||||
|
||||
$dateValidatorSlash = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy'));
|
||||
$dateValidatorSlashWithTime = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy HH:ii:ss'));
|
||||
$dateValidatorTrattino = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd'));
|
||||
|
||||
switch (true){
|
||||
case ($dateValidatorSlashWithTime->isValid($data) && !$this->isTimestamp($data)):
|
||||
$data = explode(' ',$data);
|
||||
$date = $data[0];
|
||||
$time = $data[1];
|
||||
return implode('-', array_reverse(explode("/", $date))) . " ". $time;
|
||||
case ($dateValidatorSlash->isValid($data) && !$this->isTimestamp($data)):
|
||||
return implode('-', array_reverse(explode("/", $data)));
|
||||
/*case ($this->isTimestamp($data)):
|
||||
$data = new DateTime('@' . $data);
|
||||
return $data->format('Y-m-d H:i:s');*/
|
||||
case ($dateValidatorTrattino->isValid($data) && !$this->isTimestamp($data)):
|
||||
default:
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
private function isTimestamp($string)
|
||||
{
|
||||
try {
|
||||
new DateTime('@' . $string);
|
||||
} catch(Exception $e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
class App_Form_Filters_MyJsonEncode implements Zend_Filter_Interface
|
||||
{
|
||||
public function filter($value)
|
||||
{
|
||||
$valueFiltered = "";
|
||||
if(is_array($value) || is_object($value)){
|
||||
$valueFiltered = json_encode($value);
|
||||
}
|
||||
|
||||
return $valueFiltered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
class App_Form_Filters_MySqlsrvFormatData implements Zend_Filter_Interface
|
||||
{
|
||||
|
||||
public function filter($data)
|
||||
{
|
||||
if(is_array($data)){
|
||||
//Zend_Registry::get('log')->info($data);
|
||||
$data = new DateTime($data['date']);
|
||||
return $data -> format("Y-m-d");
|
||||
}elseif(is_string($data)){
|
||||
$dateValidatorSlash = new Zend_Validate_Date(array('format' => 'dd/mm/yyyy'));
|
||||
$dateValidatorTrattino = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd'));
|
||||
if ($dateValidatorSlash->isValid($data)) {
|
||||
return implode('-', array_reverse(explode("/", $data)));
|
||||
}else if($dateValidatorTrattino->isValid($data)){
|
||||
return $data;
|
||||
}else{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
class App_Form_Validators_EmailPec extends Zend_Validate_Abstract
|
||||
{
|
||||
const EMAIL_NULL='is_empty';
|
||||
const EMAIL_ISPEC='is_pec';
|
||||
private $_PEC_DOMAINS = array('pec.it','arubapec.it','legalmail.it');
|
||||
|
||||
|
||||
protected $_messageTemplates = array(
|
||||
self::EMAIL_NULL=>'Valore non presente ',
|
||||
self::EMAIL_ISPEC=>"L'Email inserita sembra essere una PEC, si prega di inserire un email privata"
|
||||
);
|
||||
|
||||
public function isValid($value)
|
||||
{
|
||||
$this->_setValue($value);
|
||||
|
||||
$isValid = true;
|
||||
|
||||
if ($value === ''){
|
||||
$this->_error(self::EMAIL_NULL);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
$domain = explode('@',$value);
|
||||
$domain = $domain[1];
|
||||
|
||||
if(in_array($domain,$this->_PEC_DOMAINS)){
|
||||
$this->_error(self::EMAIL_ISPEC);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
return $isValid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
class App_Form_Validators_InDomain extends Zend_Validate_Abstract
|
||||
{
|
||||
const DOMAIN_NULL = 'no_domain';
|
||||
const DOMAIN_NO_VALUE = 'no_domain_value';
|
||||
|
||||
protected $_messageTemplates = array(
|
||||
self::DOMAIN_NULL => 'Dominio non specificato',
|
||||
self::DOMAIN_NO_VALUE => "Il valore non è compreso nel dominio specificato"
|
||||
);
|
||||
|
||||
protected $_domain;
|
||||
protected $_domainName;
|
||||
|
||||
public function __construct($domainName)
|
||||
{
|
||||
$this->_domainName = $domainName;
|
||||
$this->setDomain($domainName);
|
||||
}
|
||||
|
||||
public function isValid($value)
|
||||
{
|
||||
$this->_setValue($value);
|
||||
|
||||
$isValid = true;
|
||||
if (!in_array($value, $this->_domain)) {
|
||||
$this->_error(self::DOMAIN_NO_VALUE);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
return $isValid;
|
||||
}
|
||||
|
||||
private function setDomain($domainName)
|
||||
{
|
||||
|
||||
if (!$domainName) {
|
||||
throw new Zend_Validate_Exception('Nome di dominio non specificato');
|
||||
}
|
||||
|
||||
$this->_domain = array_keys(App_Constants_Domains::DOMAINS[$domainName]);
|
||||
|
||||
if(!$this->_domain){
|
||||
throw new Zend_Validate_Exception('Nome di dominio non trovato');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
class App_Form_Validators_MongoBooleanRequired extends Zend_Validate_Abstract
|
||||
{
|
||||
const REQUIRED_VALUE = 'required_mongo_boolean_value';
|
||||
|
||||
protected $_messageTemplates = array(
|
||||
self::REQUIRED_VALUE=> "Il campo deve essere di true o false"
|
||||
);
|
||||
|
||||
public function isValid($value)
|
||||
{
|
||||
$this->_setValue($value);
|
||||
|
||||
$isValid = true;
|
||||
|
||||
if($value !== true && $value !== false){
|
||||
$this->_error(self::REQUIRED_VALUE);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
return $isValid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
class App_Form_Validators_MyData extends Zend_Validate_Abstract
|
||||
{
|
||||
const INVALID_DATA_FORMAT = 'invalid_data_format';
|
||||
|
||||
protected $_messageTemplates = array(
|
||||
self::INVALID_DATA_FORMAT=>'Formato data non valido'
|
||||
);
|
||||
|
||||
public function isValid($value)
|
||||
{
|
||||
$this->_setValue($value);
|
||||
|
||||
$isValid = true;
|
||||
|
||||
$dateValidatorTrattino = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd'));
|
||||
if(!$dateValidatorTrattino->isValid($value)){
|
||||
$this->_error(self::INVALID_DATA_FORMAT);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
return $isValid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
class App_Form_Validators_Piva extends Zend_Validate_Abstract
|
||||
{
|
||||
const PIVA_NULL='is_empty';
|
||||
const PIVA_LENGHT='min_lenght';
|
||||
const PIVA_MATCH='preg_match';
|
||||
const PIVA_INVALID='invalid';
|
||||
const PIVA_INVALID_ME='invalid_me';
|
||||
const PIVA_INVALID_ZERO='invalid_zero';
|
||||
|
||||
protected $_messageTemplates = array(
|
||||
self::PIVA_NULL=>'Valore non presente ',
|
||||
self::PIVA_LENGHT=>'La lunghezza della partita iva "%value%" non è corretta: la partita IVA dovrebbe essere lunga esattamente 11 caratteri',
|
||||
self::PIVA_MATCH=>'La partita iva "%value%" contiene dei caratteri non ammessi: la partita IVA dovrebbe contenere solo cifre',
|
||||
self::PIVA_INVALID=>'La partita iva "%value%" non è valida',
|
||||
self::PIVA_INVALID_ME=>'La partita iva "%value%" non è valida: non puoi inserire la nostra p.iva',
|
||||
self::PIVA_INVALID_ZERO=>'Sei sicuro che "%value%" sia la tua partita iva?',
|
||||
);
|
||||
|
||||
public function isValid($value,$checkPivaInterna = true)
|
||||
{
|
||||
$this->_setValue($value);
|
||||
|
||||
$isValid = true;
|
||||
|
||||
if ($value === ''){
|
||||
$this->_error(self::PIVA_NULL);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
if(strlen($value) != 11){
|
||||
$this->_error(self::PIVA_LENGHT);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
/*Controllo personalizzato sulla propria partita iva */
|
||||
if ($value === '01999590688' && $checkPivaInterna){
|
||||
$this->_error(self::PIVA_INVALID_ME);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
if ($value === '00000000000'){
|
||||
$this->_error(self::PIVA_INVALID_ZERO);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
if(preg_match("/^[0-9]+\$/", $value) != 1){
|
||||
$this->_error(self::PIVA_MATCH);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
$s = 0;
|
||||
for ($i = 0; $i <= 9; $i += 2)
|
||||
$s += ord($value[$i]) - ord('0');
|
||||
|
||||
for ($i = 1; $i <= 9; $i += 2) {
|
||||
$c = 2 * (ord($value[$i]) - ord('0'));
|
||||
if ($c > 9)
|
||||
$c = $c - 9;
|
||||
$s += $c;
|
||||
}
|
||||
|
||||
if ((10 - $s % 10) % 10 != ord($value[10]) - ord('0')){
|
||||
$this->_error(self::PIVA_INVALID);
|
||||
$isValid = false;
|
||||
}
|
||||
|
||||
return $isValid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Classe generica che si interfaccia con le varie classi di risorsa da utilizzare con le funzione generiche delle query
|
||||
*
|
||||
* Versione: 1.0.2
|
||||
* Data Update: 16/02/2021
|
||||
*
|
||||
* Elenco Funzionalità implementate:
|
||||
*
|
||||
* - countTotal
|
||||
* - getList con paginazione
|
||||
* - getList con ricerche complete di parametri ORWHERE e ANDORWHERE
|
||||
* - getList con gestione completa dell'ordinamento in base alla stringa passata anche con valori multipli | array (rimane intatto)
|
||||
* - getList con selectList (opzionele) | '*'
|
||||
* - getList con joinData (opzionale) inclusa anche la possibilità di inserire join multipli nell'array
|
||||
* - getList con groupBy (opzionale)
|
||||
* # Per utilizzare getList e groupBy bisogna fare l'overload delle funzioni checkIfSetJoinData | checkIfSetGroupBy nel controller della risorsa
|
||||
* - countFiltered() non utilizza il getList
|
||||
* - getByColumnName()
|
||||
* - customQuery()
|
||||
* - inserito l'overload della funzione getList che ora è utilizzabile con due intestazioni di metodo "classica" o "con array di parametri"
|
||||
* - inserita la gestione dell'having per la getList
|
||||
*
|
||||
* Class App_Model_AbstractGeneric
|
||||
*/
|
||||
abstract class App_Model_AbstractGeneric
|
||||
{
|
||||
protected $_resources = array();
|
||||
|
||||
const JOIN_TABLE_NAME = "JOIN_TABLE_NAME";
|
||||
const JOIN_CONDITION_NAME = "JOIN_CONDITION_NAME";
|
||||
const JOIN_COLUMNS_NAME = "JOIN_COLUMNS_NAME";
|
||||
const JOIN_TYPE = "JOIN_TYPE";
|
||||
const JOIN_FUNCTION_NAME_ALLOWED = array('join', 'joinInner', 'joinLeft', 'joinRight', 'joinFull', 'joinCross', 'joinNatural');
|
||||
|
||||
const ALLOWED_GETLIST_ARRAY_OPTIONS = array('page', 'count', 'where', 'order', 'selectList', 'joinOptions', 'groupBy', 'fetchRow', 'having');
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return App_Model_Resource_Abstract
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function getResource($name)
|
||||
{
|
||||
|
||||
if (!isset($this->_resources[$name])) {
|
||||
$class = implode('_', array(
|
||||
$this->_getNamespace(),
|
||||
'Model_Resources',
|
||||
ucfirst($name)));
|
||||
|
||||
//Controllo l'esistenza della classe
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Errore generazione la classe risorsa '$class' potrebbe non esistere");
|
||||
}
|
||||
|
||||
$this->_resources[$name] = new $class();
|
||||
}
|
||||
|
||||
return $this->_resources[$name];
|
||||
}
|
||||
|
||||
private function _getNamespace()
|
||||
{
|
||||
$ns = explode('_', get_class($this));
|
||||
return $ns[0];
|
||||
}
|
||||
|
||||
/*====================================================================================================
|
||||
*======================= FUNZIONI GENERICHE PER OGNI TABELLA ==========================
|
||||
*====================================================================================================*/
|
||||
|
||||
/**
|
||||
* @param $resourceName
|
||||
* @param $info
|
||||
* @return mixed
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function insert($resourceName, $info)
|
||||
{
|
||||
|
||||
return $this->getResource($resourceName)->insert($info);
|
||||
}
|
||||
|
||||
public function update($resourceName, $id, $info)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
$idString = (is_int($id)) ? " = $id" : " = '$id'";
|
||||
return $resource->update($info, $resource->getPrimaryKey() . $idString);
|
||||
}
|
||||
|
||||
public function updateWhere($resourceName, $condition, $info)
|
||||
{
|
||||
//Se passo un array di condizioni viene construita la stringa
|
||||
if (is_array($condition)) {
|
||||
$last_key = key(array_slice($condition, -1, 1, TRUE));
|
||||
$str = "";
|
||||
foreach ($condition as $key => $val) {
|
||||
$str .= str_replace('?', $val, $key);
|
||||
if ($key != $last_key) $str .= " AND ";
|
||||
}
|
||||
$condition = $str;
|
||||
}
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->update($info, $condition);
|
||||
}
|
||||
|
||||
public function delete($resourceName, $id)
|
||||
{
|
||||
$resource = $this->getResource($resourceName);
|
||||
$idString = (is_int($id)) ? " = $id" : " = '$id'";
|
||||
return $resource->delete($resource->getPrimaryKey() . $idString);
|
||||
}
|
||||
|
||||
public function deleteWhere($resourceName, $condition)
|
||||
{
|
||||
//Se passo un array di condizioni viene construita la stringa
|
||||
if (is_array($condition)) {
|
||||
$last_key = key(array_slice($condition, -1, 1, TRUE));
|
||||
$str = "";
|
||||
foreach ($condition as $key => $val) {
|
||||
$str .= str_replace('?', $val, $key);
|
||||
if ($key != $last_key) $str .= " AND ";
|
||||
}
|
||||
$condition = $str;
|
||||
}
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->delete($condition);
|
||||
}
|
||||
|
||||
public function getById($resourceName, $id)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->getAdapter()->query('SELECT * FROM ' . $resource->getTableName() . ' WHERE ' . $resource->getPrimaryKey() . ' = ?', array($id))->fetch();
|
||||
}
|
||||
|
||||
public function getLastId($resourceName)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->getAdapter()->query('SELECT id FROM ' . $resource->getTableName() . ' ORDER BY ' . $resource->getPrimaryKey() . ' DESC LIMIT 1')->fetchColumn(0);
|
||||
}
|
||||
|
||||
public function getCountTotal($resourceName)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
return $resource->getAdapter()->query('SELECT COUNT(*) as num FROM ' . $resource->getTableName())->fetchColumn(0);
|
||||
}
|
||||
|
||||
// FUNZIONE GET LIST CON OVERLOAD
|
||||
|
||||
public function getList()
|
||||
{
|
||||
$args = func_get_args();
|
||||
$functionName = (func_num_args() === 2 && is_array($args[1])) ? 'getListOptions' : 'getListDefault';
|
||||
return call_user_func_array(array(&$this, $functionName), $args);
|
||||
}
|
||||
|
||||
/**
|
||||
* #Overload
|
||||
* Funzione get list che accetta i parametri inseriti in un array in modo da non dover più rispettare l'ordine di inserimento
|
||||
*
|
||||
* @param $resourceName
|
||||
* @param array $options
|
||||
* @return Zend_Paginator
|
||||
* @throws Zend_Exception
|
||||
* @throws Zend_Paginator_Exception
|
||||
*/
|
||||
public function getListOptions($resourceName, array $options = [])
|
||||
{
|
||||
foreach ($options as $optionKey => $val) {
|
||||
if (!in_array($optionKey, self::ALLOWED_GETLIST_ARRAY_OPTIONS)) {
|
||||
throw new App_Controller_Errors_WebServiceError("'$optionKey' non e' una opzione valida per la funzione getList()");
|
||||
}
|
||||
}
|
||||
|
||||
return $this->getListDefault($resourceName,
|
||||
$options['page'], $options['count'], $options['where'],
|
||||
$options['order'], $options['selectList'], $options['joinOptions'],
|
||||
$options['groupBy'], $options['fetchRow'], $options['having']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Funzione getList completa (può sostituire anche la funzione getFilteredList)
|
||||
*
|
||||
* @param $resourceName
|
||||
* @param null $paged
|
||||
* @param null $count
|
||||
* @param array $where
|
||||
* @param null $order
|
||||
* @param string $selectList
|
||||
* @param null $joinData
|
||||
* @param null $groupBy
|
||||
* @param bool $fetchRow
|
||||
* @return Zend_Paginator
|
||||
* @throws Zend_Exception
|
||||
* @throws Zend_Paginator_Exception
|
||||
*/
|
||||
public function getListDefault($resourceName, $paged = null, $count = null, $where = array(), $order = null, $selectList = '*', $joinData = null, $groupBy = null, $fetchRow = false, $having = false)
|
||||
{
|
||||
$resource = $this->getResource($resourceName);
|
||||
|
||||
// definizione della select list
|
||||
$selectList = (!is_null($selectList)) ? $selectList : $resource->getDefaultSelectColumns();
|
||||
if (is_string($selectList)) {
|
||||
$selectList = explode(',', $selectList);
|
||||
}
|
||||
$select = $resource->getAdapter()->select()->from($resource->getTableName(), $selectList);
|
||||
|
||||
//Gestione dell'eventuale Join
|
||||
$joinData = (!is_null($joinData)) ? $joinData : $resource->getDefaultJoinData();
|
||||
if (is_array($joinData)) {
|
||||
$select = $this->applicateJoinData($select, $joinData);
|
||||
}
|
||||
|
||||
//gestione dei parametri di ricerca
|
||||
if (is_array($where)) {
|
||||
foreach ($where as $key => $value) {
|
||||
// se trovo l'operatore '#OR' o '#ANDOR' significa che devo applicare l'or per gli elementi passati nel campo value, NB: il value deve essere una string separata da virgole
|
||||
if (preg_match("/#OR/", $key)) { // #ANDOR accoda la query es: WHERE ... OR (nome_campo = ?)
|
||||
$select = $this->applicateOrWhere($select, $key, $value, '#OR');
|
||||
} else if (preg_match("/#ANDOR/", $key)) { // #ANDOR compone la query es: WHERE ... AND ( campo1 = ? OR campo2 = ?)
|
||||
|
||||
//salvo le condizioni presenti e resetto temporaneamente le condizini
|
||||
$oldWhereConditions = $select->getPart(Zend_Db_Select::WHERE);
|
||||
$select->reset(Zend_Db_Select::WHERE);
|
||||
|
||||
// genero le condizioni or
|
||||
$select = $this->applicateOrWhere($select, $key, $value, '#ANDOR');
|
||||
|
||||
// recupero le condizioni or generate e resetto di nuovo tutte le condizioni
|
||||
$orWhereConditions = $select->getPart(Zend_Db_Select::WHERE);
|
||||
$select->reset(Zend_Db_Select::WHERE);
|
||||
|
||||
// reimposto le vecchie condizioni e accodo le nuove condizioni or
|
||||
if ($oldWhereConditions) $select->where(implode(' ', $oldWhereConditions));
|
||||
$select->where(implode(' ', $orWhereConditions));
|
||||
|
||||
} else {
|
||||
//Di default utilizzo where con la AND
|
||||
$select->where($key, $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Gestione dell'eventuale grouBy
|
||||
if ($groupBy) {
|
||||
$select->group($groupBy);
|
||||
}
|
||||
|
||||
//gestione dell'ordinamento
|
||||
$order = (!$order) ? $resource->getDefaultOrder() : $order;
|
||||
if (is_string($order)) {
|
||||
$tmpOrder = explode(',', $order);
|
||||
foreach ($tmpOrder as &$ord) {
|
||||
// il '.' serve a definire il nome della tabella altrimenti imposto quella di default della risorsa che chiama la query
|
||||
if (!preg_match("/\./", $ord)) {
|
||||
$ord = $resource->getTableName() . "." . trim($ord);
|
||||
}
|
||||
|
||||
// Se non esiste un verso di ordinamento assegno quello di default della risorsa per ogni campo ordinamento passato
|
||||
if (!preg_match("/(ASC|DESC|desc|asc)$/", $ord)) {
|
||||
$ord = explode(' ', trim($ord))[0] . ' ' . strtoupper($resource->getDefaultTipoOrder());
|
||||
}
|
||||
}
|
||||
|
||||
$order = $tmpOrder;
|
||||
}
|
||||
|
||||
$select->order($order);
|
||||
|
||||
//Gestione dell'eventuale grouBy
|
||||
if ($having && is_array($having)) {
|
||||
foreach (array_keys($having) as $key) {
|
||||
$select->having($key, $having[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($select->__toString(), true));
|
||||
|
||||
//Esecuzione della query di ricerca
|
||||
if (null !== $paged && null !== $count) {
|
||||
$adapter = new Zend_Paginator_Adapter_DbSelect($select);
|
||||
$paginator = new Zend_Paginator($adapter);
|
||||
$paginator->setItemCountPerPage($count)->setCurrentPageNumber((int)$paged);
|
||||
|
||||
return $paginator;
|
||||
}
|
||||
$stmt = $resource->getAdapter()->query($select->__toString());
|
||||
|
||||
//Gestione del Fetch
|
||||
if ($fetchRow)
|
||||
return $stmt->fetch();
|
||||
else
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $resourceName
|
||||
* @param $where
|
||||
* @param null $order
|
||||
* @param null $selectList
|
||||
* @param null $joinData
|
||||
* @param null $groupBy
|
||||
* @return Zend_Paginator
|
||||
* @throws Zend_Exception
|
||||
* @throws Zend_Paginator_Exception
|
||||
*/
|
||||
public function getFiltered($resourceName, $where, $order = null, $selectList = null, $joinData = null, $groupBy = null)
|
||||
{
|
||||
return $this->getList($resourceName, null, null, $where, $order, $selectList, $joinData, $groupBy, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Con questa funzione posso recuperare il numero di elementi di una tabella in base a parametri
|
||||
* @param $resourceName
|
||||
* @param $where
|
||||
*
|
||||
* @return Zend_Paginator
|
||||
*/
|
||||
public function countFiltered($resourceName, $where)
|
||||
{
|
||||
//Definizione della risorsa
|
||||
$resource = $this->getResource($resourceName);
|
||||
$select = $resource->getAdapter()->select()->from($resource->getTableName(), 'COUNT(*) as num');
|
||||
|
||||
//Applico le eventuali condizioni di ricerca
|
||||
foreach ($where as $key => $value) {
|
||||
$select->where($key, $value);
|
||||
}
|
||||
|
||||
$stmt = $resource->getAdapter()->query($select->__toString());
|
||||
|
||||
return $stmt->fetchColumn(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Questa funzione passato il nome della colonna su cui cercare cerca il valore scelto;
|
||||
* l'operatore di default è 'uguale'
|
||||
* altriemnti è possibile specificarne un altro trimete il parametro @op
|
||||
*
|
||||
* @param $resourceName
|
||||
* @param $columnName
|
||||
* @param $value
|
||||
* @param $fetchRow | Se impostato a true ritorna la riga come oggetto
|
||||
* @param $op
|
||||
* @param $joinData | per eseguire un join con altre tabelle
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getByColumnName($resourceName, $columnName, $value, $op = "=", $fetchRow = false, $order = null, $joinData = null)
|
||||
{
|
||||
|
||||
$resource = $this->getResource($resourceName);
|
||||
|
||||
//GESTIONE OPERATORI
|
||||
switch ($op) {
|
||||
case'LIKE':
|
||||
$value = "%" . $value . "%";
|
||||
break;
|
||||
case'LIKEPRE':
|
||||
$value = "%" . $value;
|
||||
break;
|
||||
case'LIKEPOST':
|
||||
$value = $value . "%";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
$select = $resource->getAdapter()->select()->from($resource->getTableName());
|
||||
|
||||
//Gestione dell'eventuale Join
|
||||
if (is_array($joinData)) {
|
||||
$select = $this->applicateJoinData($select, $joinData);
|
||||
}
|
||||
|
||||
$select->where($columnName . ' ' . $op . ' ?', $value);
|
||||
|
||||
if ($order != null && (is_array($order) || is_string($order))) {
|
||||
$select->order($order);
|
||||
}
|
||||
|
||||
if ($fetchRow) {
|
||||
if ($order != null && (is_array($order) || is_string($order))) {
|
||||
return $resource->fetchRow($resource->select()->where($columnName . ' ' . $op . ' ?', $value)->order($order));
|
||||
} else {
|
||||
return $resource->fetchRow($resource->select()->where($columnName . ' ' . $op . ' ?', $value));
|
||||
}
|
||||
} else {
|
||||
return $resource->getAdapter()->query($select->__toString())->fetch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $query
|
||||
* @param null $params
|
||||
* @param bool $fetchRow
|
||||
* @return mixed
|
||||
*
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function customQuery($query, $params = null, $fetchRow = false)
|
||||
{
|
||||
|
||||
$resource = $this->getResource('Abstract');
|
||||
$stmt = $resource->getAdapter()->query($query, $params);
|
||||
|
||||
//Gestione del Fetch
|
||||
if ($fetchRow)
|
||||
return $stmt->fetch();
|
||||
else
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $select
|
||||
* @param $joinData
|
||||
* @return mixed
|
||||
*
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
private function applicateJoinData($select, $joinData)
|
||||
{
|
||||
|
||||
if (!isset($joinData[0])) {
|
||||
if (!array_key_exists(self::JOIN_TABLE_NAME, $joinData))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome tabella per il join non trovato");
|
||||
|
||||
if (!array_key_exists(self::JOIN_CONDITION_NAME, $joinData))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome del campo di condizione per il join non trovato");
|
||||
|
||||
$colonne = (!$joinData[self::JOIN_COLUMNS_NAME]) ? array('*') : $joinData[self::JOIN_COLUMNS_NAME];
|
||||
$joinFunctionName = (in_array($joinData[self::JOIN_TYPE], self::JOIN_FUNCTION_NAME_ALLOWED)) ? $joinData[self::JOIN_TYPE] : 'join';
|
||||
|
||||
return $select->$joinFunctionName($joinData[self::JOIN_TABLE_NAME], $joinData[self::JOIN_CONDITION_NAME], $colonne);
|
||||
} else { // Gestione di più join contemporanei
|
||||
foreach ($joinData as $key => $join) {
|
||||
if (!array_key_exists(self::JOIN_TABLE_NAME, $join))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome tabella per il join non trovato per il join index: [$key]");
|
||||
|
||||
if (!array_key_exists(self::JOIN_CONDITION_NAME, $join))
|
||||
throw new App_Controller_Errors_WebServiceError("Nome del campo di condizione per il join non trovato per il join index: [$key]");
|
||||
|
||||
$colonne = (!$join[self::JOIN_COLUMNS_NAME]) ? array('*') : $join[self::JOIN_COLUMNS_NAME];
|
||||
$joinFunctionName = (in_array($join[self::JOIN_TYPE], self::JOIN_FUNCTION_NAME_ALLOWED)) ? $join[self::JOIN_TYPE] : 'join';
|
||||
|
||||
$select->$joinFunctionName($join[self::JOIN_TABLE_NAME], $join[self::JOIN_CONDITION_NAME], $colonne);
|
||||
}
|
||||
return $select;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function applicateOrWhere($select, string $keyNomeCampo, $valoriOr, string $op = '#OR')
|
||||
{
|
||||
|
||||
$valueOrDaApplicare = null;
|
||||
if (is_string($valoriOr))
|
||||
$valueOrDaApplicare = explode(',', $valoriOr);
|
||||
elseif (is_array($valoriOr))
|
||||
$valueOrDaApplicare = $valoriOr;
|
||||
|
||||
if (!$valueOrDaApplicare) {
|
||||
throw new App_Controller_Errors_WebServiceError("Valori per la condizione '$op' non validi per generare la query", App_Controller_Errors_WebServiceError::WEBSERVICE_GENERIC_ERROR);
|
||||
}
|
||||
|
||||
$keyDaApplicare = str_replace($op, '=', $keyNomeCampo);
|
||||
|
||||
if (is_array($valueOrDaApplicare) && count($valueOrDaApplicare) > 0) {
|
||||
foreach ($valueOrDaApplicare as $val) {
|
||||
$select->orwhere($keyDaApplicare, $val);
|
||||
}
|
||||
}
|
||||
|
||||
return $select;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
abstract class App_Model_AbstractRest
|
||||
{
|
||||
protected $_resources = array();
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return Application_Model_RestResources_Generic
|
||||
*/
|
||||
public function getResource($name)
|
||||
{
|
||||
|
||||
if (!isset($this->_resources[$name])) {
|
||||
$class = implode('_', array(
|
||||
$this->_getNamespace(),
|
||||
'Model',
|
||||
'RestResources',
|
||||
ucfirst($name)));
|
||||
|
||||
//Controllo l'esistenza della classe [commentato perchè genera errore su alcune risorse]
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Errore di generazione per la classe risorsa rest '$class'. Potrebbe non esistere!");
|
||||
}
|
||||
|
||||
$this->_resources[$name] = new $class();
|
||||
}
|
||||
|
||||
return $this->_resources[$name];
|
||||
}
|
||||
|
||||
private function _getNamespace()
|
||||
{
|
||||
$ns = explode('_', get_class($this));
|
||||
return $ns[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $results
|
||||
* @param $page
|
||||
* @param $count
|
||||
* @return Zend_Paginator
|
||||
*
|
||||
* Questa funzione pasato un array lo converte in un oggetto Zend Paginator
|
||||
*/
|
||||
public function converResultsToZendPaginator($results,$page,$count){
|
||||
$dati = $this->getOffsetPaginatedArray($results['data'],$results['totalItem'],$page,$count);
|
||||
$results = Zend_Paginator::factory($dati);
|
||||
$results->setItemCountPerPage($count);
|
||||
$results->setCurrentPageNumber($page);
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $results
|
||||
* @param $totalItems
|
||||
* @param $page
|
||||
* @param $count
|
||||
* @return array
|
||||
* Funzione che crea un offset di oggetti per far si che il paginator conosca il numero totale di elemnti presenti
|
||||
*/
|
||||
public function getOffsetPaginatedArray($results,$totalItems,$page,$count){
|
||||
$dati = array();
|
||||
$rangeStart = (($page * $count) - $count) + 1;
|
||||
$rangeEnd = $page * $count;
|
||||
$rangeX = 0;
|
||||
|
||||
for($i = 0; $i < $totalItems ;$i++){
|
||||
if($i >= $rangeStart -1 && $i <= $rangeEnd -1){
|
||||
$dati[$i] = $results[$rangeX];
|
||||
$rangeX++;
|
||||
}else{
|
||||
$dati[$i] = array();
|
||||
}
|
||||
}
|
||||
|
||||
return $dati;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Acl_Acl extends Zend_Acl
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
// ACL for default role
|
||||
$this->addRole(new Zend_Acl_Role('unregistered'))
|
||||
->add(new Zend_Acl_Resource('default'))
|
||||
->add(new Zend_Acl_Resource('auth'))
|
||||
->add(new Zend_Acl_Resource('v1'))
|
||||
->allow('unregistered', array('default', 'auth', 'v1'));
|
||||
|
||||
// ACL for user
|
||||
$this->addRole(new Zend_Acl_Role('user'), 'unregistered')
|
||||
->add(new Zend_Acl_Resource('user'))
|
||||
->allow('user', array('user'));
|
||||
|
||||
// ACL for administrator
|
||||
$this->addRole(new Zend_Acl_Role('admin'), array('user'))
|
||||
->add(new Zend_Acl_Resource('admin'))
|
||||
->add(new Zend_Acl_Resource('monitoring'))
|
||||
->allow('admin', array('admin', 'monitoring'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Acl_AclRestV1 extends Zend_Acl
|
||||
{
|
||||
/**
|
||||
* ACL che controlla in base al role dell'user se puo accedere a un determinato controller del web seervices
|
||||
*
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
// ACL for default role
|
||||
$this->addRole(new Zend_Acl_Role('unregistered'))
|
||||
->add(new Zend_Acl_Resource('index'))
|
||||
->add(new Zend_Acl_Resource('error'))
|
||||
->add(new Zend_Acl_Resource('services'))
|
||||
->allow('unregistered', array('index','error','services'));
|
||||
|
||||
// ACL for user
|
||||
$this->addRole(new Zend_Acl_Role('user'), 'unregistered')
|
||||
->add(new Zend_Acl_Resource('emails'))
|
||||
->allow('user', array('emails'));
|
||||
|
||||
// ACL for administrator
|
||||
$this->addRole(new Zend_Acl_Role('admin'), 'user')
|
||||
->add(new Zend_Acl_Resource('users'))
|
||||
->allow('admin', array('users'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
|
||||
class App_Model_CurlHttpClient
|
||||
{
|
||||
|
||||
protected $_httpClient = null;
|
||||
protected $_urlNameServices;
|
||||
|
||||
public function __construct($urlName){
|
||||
|
||||
$this->_urlNameServices = $urlName;
|
||||
|
||||
$this->_httpClient = new Zend_Http_Client($urlName);
|
||||
$this->_httpClient->setConfig(array(
|
||||
'adapter' => 'Zend_Http_Client_Adapter_Curl',
|
||||
'maxredirects' => 0,
|
||||
'timeout' => 60,
|
||||
'ssltransport' => 'ssl'
|
||||
));
|
||||
}
|
||||
|
||||
/***** METODI COMUNI DELLE CHIMATE *****/
|
||||
|
||||
public function getCall($params){
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function postCall($dati,$formatJson = false){
|
||||
$this->_httpClient->setMethod('POST');
|
||||
if($formatJson)
|
||||
$this->_httpClient->setRawData(json_encode($dati),'application/json;charset=utf-8');
|
||||
else
|
||||
$this->_httpClient->setParameterPost($dati);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function putCall($dati,$formatJson = false){
|
||||
$this->_httpClient->setMethod('PUT');
|
||||
if($formatJson)
|
||||
$this->_httpClient->setRawData(json_encode($dati),'application/json;charset=utf-8');
|
||||
else
|
||||
$this->_httpClient->setParameterPost($dati);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function deleteCall($params){
|
||||
$this->_httpClient->setMethod('DELETE');
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
/***** METODI PRIVATI PER GESTIRE LE CHIAMATE *****/
|
||||
|
||||
private function executeCall(){
|
||||
$httpResponse = $this->_httpClient->request();
|
||||
$headerResponse = $httpResponse->getHeaders();
|
||||
|
||||
if(preg_match('/application\/json/',$headerResponse['Content-type'])){
|
||||
$httpResponseBody = json_decode($httpResponse->getBody(),1);
|
||||
|
||||
if(json_last_error() !== JSON_ERROR_NONE){
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore codifica JSON:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse,true));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!$httpResponseBody['status'] && !$httpResponseBody['success']) {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore 'httpResponse' no status or success code:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponseBody,true));
|
||||
throw new Exception($httpResponseBody['message'],$httpResponseBody['errorCode']);
|
||||
}
|
||||
}else{
|
||||
$httpResponseBody = $httpResponse->getBody();
|
||||
}
|
||||
|
||||
return $httpResponseBody;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
|
||||
abstract class App_Model_FcmFirebase
|
||||
{
|
||||
|
||||
const BASE_API_URL = "https://fcm.googleapis.com";
|
||||
const API_VERSION = "fcm";
|
||||
const SECRET_ID = "AAAAfg7FWPQ:APA91bHte0qwGR5J8wdfuUWJhU6-ehj_xXH6cOV6s2IFabm-86wBIwwUJsvwPmKD65PQ2HEl8SRzcy6EOl3GCc9K_StPgNpG8t84Zz5j7_uFKPCiHvblAb0xLk2eYYDsim4eBhvokv0s";
|
||||
|
||||
protected $_httpClient = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
if ($this->_httpClient instanceof Zend_Http_Client) {
|
||||
//$this->_httpClient = $this->_httpClient;
|
||||
} else {
|
||||
$this->_httpClient = new Zend_Http_Client();
|
||||
$this->_httpClient->setConfig(array(
|
||||
'adapter' => 'Zend_Http_Client_Adapter_Curl',
|
||||
'maxredirects' => 0,
|
||||
'timeout' => 60,
|
||||
'ssltransport' => 'ssl'
|
||||
));
|
||||
$this->_httpClient->setHeaders('Authorization', 'key=' . self::SECRET_ID);
|
||||
}
|
||||
}
|
||||
|
||||
/***** METODI COMUNI DELLE CHIMATE *****/
|
||||
|
||||
public function postCall($dati)
|
||||
{
|
||||
$this->_httpClient->setMethod('POST');
|
||||
$this->_httpClient->setUri($this->getBaseUrl() . '/send');
|
||||
$this->_httpClient->setRawData(Zend_Json::encode($dati), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
/***** METODI PRIVATI PER GESTIRE LE CHIAMATE *****/
|
||||
|
||||
private function getBaseUrl()
|
||||
{
|
||||
return self::BASE_API_URL . "/" . self::API_VERSION;
|
||||
}
|
||||
|
||||
private function executeCall()
|
||||
{
|
||||
$httpResponse = $this->_httpClient->request();
|
||||
|
||||
/*if($this->_ipManager->allowedIp()){
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse,true));
|
||||
}*/
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($this->_httpClient->getLastRequest(), true));
|
||||
|
||||
$httpResponseEncoded = json_decode($httpResponse->getBody(), 1);
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($httpResponseEncoded, true));
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore codifica JSON:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse, true));
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->_httpClient->getLastResponse()->getStatus() != '200' || $httpResponseEncoded['status'] == 'error') {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore status response " . $this->_httpClient->getLastResponse()->getStatus());
|
||||
Zend_Registry::get('log')->info(print_r($httpResponseEncoded, true));
|
||||
throw new App_Exception_ResponseCloudException($httpResponseEncoded['message'], $httpResponseEncoded['errorCode']);
|
||||
}
|
||||
|
||||
return $httpResponseEncoded;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Mail extends Zend_Mail
|
||||
{
|
||||
/**
|
||||
* Sets the HTML body for the message
|
||||
*
|
||||
* @param string $html
|
||||
* @param string $charset
|
||||
* @param string $encoding
|
||||
* @return Zend_Mail Provides fluent interface
|
||||
*/
|
||||
public function setBodyHtml($html, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE, $preload_images = true)
|
||||
{
|
||||
$preload_images = false;
|
||||
try {
|
||||
if ($preload_images) {
|
||||
|
||||
$this->setType(Zend_Mime::MULTIPART_RELATED);
|
||||
|
||||
$dom = new DOMDocument(null, $this->getCharset());
|
||||
@$dom->loadHTML($html);
|
||||
|
||||
$images = $dom->getElementsByTagName('img');
|
||||
|
||||
for ($i = 0; $i < $images->length; $i++) {
|
||||
$img = $images->item($i);
|
||||
$url = $img->getAttribute('src');
|
||||
|
||||
$image_http = new Zend_Http_Client($url);
|
||||
$image_http->setAdapter('Zend_Http_Client_Adapter_Curl');
|
||||
|
||||
$response = $image_http->request();
|
||||
|
||||
if ($response->getStatus() == 200) {
|
||||
$image_content = $response->getBody();
|
||||
|
||||
$pathinfo = pathinfo($url);
|
||||
$mime_type = $response->getHeader('Content-Type');
|
||||
|
||||
$mime = new Zend_Mime_Part($image_content);
|
||||
$mime->id = $url;
|
||||
$mime->location = $url;
|
||||
$mime->type = $mime_type;
|
||||
$mime->disposition = Zend_Mime::DISPOSITION_INLINE;
|
||||
$mime->encoding = Zend_Mime::ENCODING_BASE64;
|
||||
$mime->filename = $pathinfo['basename'];
|
||||
|
||||
$this->addAttachment($mime);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ZendException $e) {
|
||||
Zend_Registry::get('error_log')->setEventItem('url', $this->getRequest()->getRequestUri())->setEventItem('trace', Zend_Json::encode($e->getTrace()))->setEventItem('params', Zend_Json::encode($this->getRequest()->getParams()))->info($e->getMessage());
|
||||
}
|
||||
|
||||
return parent::setBodyHtml($html, $charset, $encoding);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Mongo_Adapter
|
||||
{
|
||||
|
||||
const MONGO_DB_ADAPTER_REG_NAME = 'MONGO_DB_ADAPTER_REG_NAME';
|
||||
const MONGO_DB_NAME = 'MONGO_DB_NAME';
|
||||
|
||||
protected $_username = null;
|
||||
protected $_password = null;
|
||||
protected $_host = '127.0.0.1';
|
||||
protected $_port = '27017';
|
||||
|
||||
protected $_connectionUri = null;
|
||||
protected $_dbname = null;
|
||||
|
||||
protected $_mongoClient;
|
||||
|
||||
public function __construct(array $connectionData = array())
|
||||
{
|
||||
//Default Mongo Uri
|
||||
$this->_connectionUri = "mongodb://$this->_host:$this->_port";
|
||||
|
||||
//Autenticazione mongoDB
|
||||
if ($connectionData['user'] && ['password']) {
|
||||
|
||||
$this->_username = $connectionData['user'];
|
||||
$this->_password = $connectionData['password'];
|
||||
|
||||
$this->_host = ($connectionData['host']) ? $connectionData['host'] : $this->_host;
|
||||
$this->_port = ($connectionData['port']) ? $connectionData['port'] : $this->_port;
|
||||
|
||||
$mongoAuth = "$this->_username:$this->_password";
|
||||
$mongoHost = "$this->_host:$this->_port";
|
||||
|
||||
//AuthMongoUri
|
||||
$this->_connectionUri = "mongodb://$mongoAuth@$mongoHost";
|
||||
}
|
||||
|
||||
if($connectionData['dbname']){
|
||||
$this->_dbname = $connectionData['dbname'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \MongoDB\Client
|
||||
*/
|
||||
public function getMongoClient(): \MongoDB\Client
|
||||
{
|
||||
if(!$this->_mongoClient){
|
||||
$this->_mongoClient = new MongoDB\Client($this->_connectionUri);
|
||||
}
|
||||
return $this->_mongoClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDbname(): string
|
||||
{
|
||||
return $this->_dbname;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $dbname
|
||||
*/
|
||||
public function setDbname(string $dbname): void
|
||||
{
|
||||
$this->_dbname = $dbname;
|
||||
Zend_Registry::set(self::MONGO_DB_ADAPTER_REG_NAME,$this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
<?php
|
||||
|
||||
class App_Model_Mongo_Client
|
||||
{
|
||||
|
||||
const WHERE_MONGO_REG_NAME = 'WHERE_MONGO_REG_NAME';
|
||||
|
||||
protected $_config;
|
||||
protected $_mongoClient = null;
|
||||
protected $_db = null;
|
||||
|
||||
public function __construct($connectionUrl = 'mongodb://127.0.0.1:27017')
|
||||
{
|
||||
if (Zend_Registry::isRegistered(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME)) {
|
||||
$mongoAdapter = Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_ADAPTER_REG_NAME);
|
||||
} else {
|
||||
$mongoAdapter = new App_Model_Mongo_Adapter();
|
||||
$mongoAdapter->setDbname(Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_NAME));
|
||||
}
|
||||
|
||||
$this->_mongoClient = $mongoAdapter->getMongoClient();
|
||||
$dbName = $mongoAdapter->getDbname();
|
||||
|
||||
$this->_db = $this->_mongoClient->selectDatabase($dbName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return App_Model_MongoResource_Abstract
|
||||
* @throws App_Controller_Errors_WebServiceError
|
||||
*/
|
||||
public function getResource($name)
|
||||
{
|
||||
|
||||
if (!isset($this->_resources[$name])) {
|
||||
$class = implode('_', array(
|
||||
'Application',
|
||||
'Model',
|
||||
'MongoResources',
|
||||
ucfirst($name)));
|
||||
|
||||
//Controllo l'esistenza della classe
|
||||
if (!class_exists($class)) {
|
||||
throw new App_Controller_Errors_WebServiceError("Errore generazione la classe risorsa mongo '$class' potrebbe non esistere");
|
||||
}
|
||||
|
||||
$this->_resources[$name] = new $class();
|
||||
}
|
||||
|
||||
return $this->_resources[$name];
|
||||
}
|
||||
|
||||
public function test()
|
||||
{
|
||||
return $this->_mongoClient->test;
|
||||
}
|
||||
|
||||
public function setDatabase($dbName)
|
||||
{
|
||||
return $this->_db = $this->_mongoClient->selectDatabase($dbName);
|
||||
}
|
||||
|
||||
public function listDatabases()
|
||||
{
|
||||
return $this->_mongoClient->listDatabases();
|
||||
}
|
||||
|
||||
public function getDatabase()
|
||||
{
|
||||
return $this->_db;
|
||||
}
|
||||
|
||||
public function deleteDatabase()
|
||||
{
|
||||
return $this->_mongoClient->dropDatabase($this->getDatabase());
|
||||
}
|
||||
|
||||
public function getCollection($resourceName)
|
||||
{
|
||||
$collection = $this->getResource($resourceName)->getCollectionName();
|
||||
return $this->getDatabase()->$collection;
|
||||
}
|
||||
|
||||
public function emptyCollection($resourceName)
|
||||
{
|
||||
return $this->getCollection($resourceName)->deleteMany(['id' => array('$gt'=>0)]);
|
||||
}
|
||||
|
||||
// FUNZIONI PER INTERROGARE IL DB
|
||||
|
||||
public function getById($name, $id)
|
||||
{
|
||||
$optionsParams['projection'] = ['_id' => 0];
|
||||
return $this->getCollection($name)->findOne([$this->getResource($name)->getPrimaryKey() => $id], $optionsParams);
|
||||
}
|
||||
|
||||
public function insert($name, $data)
|
||||
{
|
||||
$id = uniqid();
|
||||
$this->getCollection($name)->insertOne(array_merge([$this->getResource($name)->getPrimaryKey() => $id], $data));
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function update($name, $id, $data)
|
||||
{
|
||||
return $this->getCollection($name)->updateOne([$this->getResource($name)->getPrimaryKey() => $id], ['$set' => $data]);
|
||||
}
|
||||
|
||||
public function delete($name, $id)
|
||||
{
|
||||
return $this->getCollection($name)->deleteOne([$this->getResource($name)->getPrimaryKey() => $id]);
|
||||
}
|
||||
|
||||
public function getCountTotal($name)
|
||||
{
|
||||
return $this->getCollection($name)->countDocuments();
|
||||
}
|
||||
|
||||
public function getCountFilteredTotal($name, $filter)
|
||||
{
|
||||
return $this->getCollection($name)->countDocuments($filter);
|
||||
}
|
||||
|
||||
public function getList($name, $paged = null, $count = null, $where = null, $order = null, $projection = null)
|
||||
{
|
||||
$findParams = array();
|
||||
|
||||
if (null !== $paged && null !== $count && $count > 0 && $paged > 0) {
|
||||
if ($paged > 1) $findParams['skip'] = (($paged - 1) * $count);
|
||||
$findParams['limit'] = $count;
|
||||
}
|
||||
|
||||
$order = (!$order) ? $this->getResource($name)->getDefaultOrder($order) : $order;
|
||||
if ($order && is_array($order)) {
|
||||
$findParams['sort'] = $order;
|
||||
}
|
||||
|
||||
$projection = (!$projection) ? $this->getResource($name)->getDefaultProjection($projection) : $projection;
|
||||
if ($projection && is_array($projection)) {
|
||||
$findParams['projection'] = $projection;
|
||||
}
|
||||
|
||||
if ($where === null) $where = array();
|
||||
|
||||
$cursor = $this->getCollection($name)->find($where, $findParams);
|
||||
|
||||
return $cursor->toArray();
|
||||
}
|
||||
|
||||
public function getListAggregation($name, $paged = null, $count = null, $where = null, $order = null, $projection = null, $addFields = null, $extraAggregation = null)
|
||||
{
|
||||
$aggregations = array();
|
||||
|
||||
if ($where === null) $where = array();
|
||||
if (count($where) > 0) {
|
||||
array_push($aggregations, ['$match' => $where]);
|
||||
}
|
||||
|
||||
$order = $this->getResource($name)->getDefaultOrder($order);
|
||||
if ($order && is_array($order)) {
|
||||
array_push($aggregations, ['$sort' => $order]);
|
||||
}
|
||||
|
||||
if (null !== $paged && null !== $count && $count > 0 && $paged > 0) {
|
||||
if ($paged > 1)
|
||||
array_push($aggregations, ['$skip' => (($paged - 1) * $count)]);
|
||||
array_push($aggregations, ['$limit' => $count]);
|
||||
}
|
||||
|
||||
$projection = $this->getResource($name)->getDefaultProjection($projection);
|
||||
if ($projection && is_array($projection)) {
|
||||
array_push($aggregations, ['$project' => $projection]);
|
||||
}
|
||||
|
||||
//$totElements = $this->getCountTotal($name);
|
||||
$addFields = $this->getResource($name)->getDefaultAddFields();
|
||||
if ($addFields && is_array($addFields)) {
|
||||
|
||||
/*if($totElements <= 0){
|
||||
unset($addFields['Data']);
|
||||
}*/
|
||||
|
||||
array_push($aggregations, ['$addFields' => $addFields]);
|
||||
}
|
||||
|
||||
if ($extraAggregation && is_array($extraAggregation)) {
|
||||
if(count($extraAggregation) > 1){
|
||||
$aggregations = array_merge($aggregations, $extraAggregation);
|
||||
}else{
|
||||
array_push($aggregations, $extraAggregation);
|
||||
}
|
||||
}
|
||||
|
||||
// Zend_Registry::get('log')->info(print_r($aggregations,true));
|
||||
|
||||
$cursor = $this->getCollection($name)->aggregate($aggregations);
|
||||
|
||||
return $cursor->toArray();
|
||||
}
|
||||
|
||||
public function getByColumnName($name, $columnName, $value, $op = "=", $all = false)
|
||||
{
|
||||
|
||||
switch ($op) {
|
||||
case'=':
|
||||
default:
|
||||
$params = array($columnName => $value);
|
||||
break;
|
||||
case 'LIKE':
|
||||
$params = array($columnName => ['$regex' => $value, '$options' => 'i']);
|
||||
break;
|
||||
}
|
||||
|
||||
if ($all) {
|
||||
return $this->getCollection($name)->find($params)->toArray();
|
||||
} else {
|
||||
return $this->getCollection($name)->findOne($params);
|
||||
}
|
||||
}
|
||||
|
||||
public function find($name, $params = array())
|
||||
{
|
||||
return $this->getCollection($name)->find($params)->toArray();
|
||||
}
|
||||
|
||||
public function aggregate($name, $aggregate)
|
||||
{
|
||||
return $this->getCollection($name)->aggregate($aggregate);
|
||||
}
|
||||
|
||||
// CRUD FUNCTION WITH OBJECTID
|
||||
|
||||
public function getByObjectId($name, $id)
|
||||
{
|
||||
return $this->getCollection($name)->find([$this->getResource($name)->getPrimaryKey() => new MongoDB\BSON\ObjectID($id)])->toArray();
|
||||
}
|
||||
|
||||
public function insertWithObjectId($name, $data)
|
||||
{
|
||||
unset($data['_id']);
|
||||
return $this->getCollection($name)->insertOne($data);
|
||||
}
|
||||
|
||||
public function updateByObjectId($name, $id, $data)
|
||||
{
|
||||
return $this->getCollection($name)->updateOne([$this->getResource($name)->getPrimaryKey() => new MongoDB\BSON\ObjectID($id)], ['$set' => $data]);
|
||||
}
|
||||
|
||||
public function deleteByObjectId($name, $id)
|
||||
{
|
||||
return $this->getCollection($name)->deleteOne([$this->getResource($name)->getPrimaryKey() => new MongoDB\BSON\ObjectID($id)]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @see Zend_Paginator_Adapter_Interface
|
||||
*/
|
||||
require_once 'Zend/Paginator/Adapter/Interface.php';
|
||||
|
||||
class App_Model_Mongo_PaginatorAdapter implements Zend_Paginator_Adapter_Interface
|
||||
{
|
||||
|
||||
protected $_cursor = null;
|
||||
|
||||
|
||||
public function __construct(MongoDB\Driver\Cursor $cursor)
|
||||
{
|
||||
$this->_cursor = $cursor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an cursor limited to items for a page.
|
||||
*
|
||||
* @param integer $offset Page offset
|
||||
* @param integer $itemCountPerPage Number of items per page
|
||||
* @return MongoDB\Driver\Cursor
|
||||
*/
|
||||
public function getItems($offset, $itemCountPerPage)
|
||||
{
|
||||
$cursor = $this->_cursor->skip($offset)->limit($itemCountPerPage);
|
||||
return $cursor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total number of rows in the cursor.
|
||||
*
|
||||
* @return integer
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
return count($this->_cursor->toArray());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
|
||||
class App_Model_MongoResource_Abstract extends Zend_Db_Table_Abstract
|
||||
{
|
||||
|
||||
protected $_defaultOrder; // Formato classico '<NOMECAMPO> <DESC | ASC>'
|
||||
protected $_defaultTipoOrder;
|
||||
|
||||
public $_defaultProjection; // array di projection mongo db
|
||||
public $_defaultAddFields; // array di addFileds con el regole di mongoDb
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if(!$this->_defaultOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultOrder' non definito per la risorsa ". get_class($this));
|
||||
}
|
||||
|
||||
if(!$this->_defaultTipoOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultTipoOrder' non definito per la risorsa " . get_class($this));
|
||||
}
|
||||
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
//Funzione che restituisce il nome della collezione
|
||||
public function getCollectionName()
|
||||
{
|
||||
return $this->_name;
|
||||
}
|
||||
|
||||
//Funzione che restituisce la chiave primaria sicura
|
||||
public function getPrimaryKey()
|
||||
{
|
||||
if (is_array($this->_primary)) return $this->_primary[1];
|
||||
return $this->_primary;
|
||||
}
|
||||
|
||||
//Funzione che restituisce il campo ordinamento di default
|
||||
public function getDefaultOrder($order)
|
||||
{
|
||||
$order = (!$order) ? $this->_defaultOrder : $order;
|
||||
|
||||
if (!is_array($order)) {
|
||||
$order = explode(',', $order);
|
||||
}
|
||||
|
||||
$sort = array();
|
||||
if (count($order) > 0)
|
||||
foreach ($order as $val) {
|
||||
$tmp = explode(' ', trim($val));
|
||||
$orderType = strtoupper(trim($tmp[1]));
|
||||
$orderType = ($tmp[1] && ($orderType == 'ASC' || $orderType == 'DESC')) ? $orderType : 'ASC';
|
||||
$sort[trim($tmp[0])] = ($orderType == 'ASC') ? 1 : -1;
|
||||
}
|
||||
return $sort;
|
||||
}
|
||||
|
||||
//Funzione che restituisce il tipo di ordinamento di default
|
||||
public function getDefaultTipoOrder()
|
||||
{
|
||||
if (isset($this->_defaultTipoOrder) && $this->_defaultTipoOrder) return $this->_defaultTipoOrder;
|
||||
return "ASC";
|
||||
}
|
||||
|
||||
public function getDefaultAddFields()
|
||||
{
|
||||
if($this->_defaultAddFields) return $this->_defaultAddFields;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getDefaultProjection($projection, $defaultProjection = null, $hideObjectId = true)
|
||||
{
|
||||
$defaultProjection = ($this->_defaultProjection === null) ? (($hideObjectId) ? ['_id'=>0] : []) : $this->_defaultProjection;
|
||||
$projectionArray = ($hideObjectId) ? ['_id'=>0] : [];
|
||||
|
||||
if (is_null($projection) || $projection === '*' || (is_array($projection) && count($projection) <= 0)) {
|
||||
return $defaultProjection;
|
||||
}
|
||||
|
||||
if (is_string($projection)) {
|
||||
$projection = explode(',', $projection);
|
||||
}
|
||||
|
||||
// aggiungendo '#0' tra i valori della proiezione eseguo la proiezione negativa
|
||||
$projectionType = in_array('#0', $projection) ? 0 : 1;
|
||||
|
||||
if (is_array($projection) && count($projection) > 0) {
|
||||
foreach ($projection as $column) {
|
||||
$projectionArray[$column] = $projectionType;
|
||||
}
|
||||
}
|
||||
|
||||
return $projectionArray;
|
||||
}
|
||||
|
||||
public function getDefaultOrderString()
|
||||
{
|
||||
return $this->getDefaultOrder() . ' ' . $this->getDefaultTipoOrder();
|
||||
}
|
||||
|
||||
//--------------- FUNZIONI PER LA GESTIONE DI DATABASE MULTIPLI ------------------------------------------
|
||||
|
||||
public function _setDbName($nomedb)
|
||||
{
|
||||
Zend_Registry::set(App_Model_Mongo_Adapter::MONGO_DB_NAME, $nomedb);
|
||||
}
|
||||
|
||||
public function getDbName()
|
||||
{
|
||||
return Zend_Registry::get(App_Model_Mongo_Adapter::MONGO_DB_NAME);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class App_Model_Resource_Abstract
|
||||
*/
|
||||
class App_Model_Resource_Abstract extends Zend_Db_Table_Abstract
|
||||
{
|
||||
|
||||
protected $_defaultOrder; // [obbligatorio]
|
||||
protected $_defaultTipoOrder; // [obbligatorio]
|
||||
protected $_defaultSelectColumns; // [opzionale]
|
||||
protected $_defaultJoinData; // [opzionale] può essere un array singolo o multiplo per applicare più join insieme
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if(!$this->_defaultOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultOrder' non definito per la risorsa ". get_class($this));
|
||||
}
|
||||
|
||||
if(!$this->_defaultTipoOrder){
|
||||
throw new App_Controller_Errors_WebServiceError("'_defaultTipoOrder' non definito per la risorsa " . get_class($this));
|
||||
}
|
||||
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
//Funzione che restituisce il nome della tabella
|
||||
public function getTableName()
|
||||
{
|
||||
return $this->_name;
|
||||
}
|
||||
|
||||
//Funzione che restituisce la chiave primaria sicura
|
||||
public function getPrimaryKey()
|
||||
{
|
||||
if (is_array($this->_primary)) return $this->_primary[1];
|
||||
return $this->_primary;
|
||||
}
|
||||
|
||||
//Funzione che restituisce il campo ordinamento di default
|
||||
public function getDefaultOrder()
|
||||
{
|
||||
if (isset($this->_defaultOrder) && $this->_defaultOrder) return $this->_defaultOrder;
|
||||
return $this->getPrimaryKey();
|
||||
}
|
||||
|
||||
//Funzione che restituisce il tipo di ordinamento di default
|
||||
public function getDefaultTipoOrder()
|
||||
{
|
||||
if (isset($this->_defaultTipoOrder) && $this->_defaultTipoOrder) return $this->_defaultTipoOrder;
|
||||
return "ASC";
|
||||
}
|
||||
|
||||
//Funzione che restituisce il tipo di select default
|
||||
public function getDefaultSelectColumns()
|
||||
{
|
||||
if (isset($this->_defaultSelectColumns) && $this->_defaultSelectColumns) return $this->_defaultSelectColumns;
|
||||
return "*";
|
||||
}
|
||||
|
||||
//Funzione che restituisce il campo joinData di default
|
||||
public function getDefaultJoinData()
|
||||
{
|
||||
if (isset($this->_defaultJoinData) && $this->_defaultJoinData) return $this->_defaultJoinData;
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getDefaultOrderString()
|
||||
{
|
||||
return $this->getDefaultOrder() . ' ' . $this->getDefaultTipoOrder();
|
||||
}
|
||||
|
||||
//--------------- FUNZIONI PER LA GESTIONE DI DATABASE MULTIPLI ------------------------------------------
|
||||
|
||||
public function _setDbName($nomedb)
|
||||
{
|
||||
$dbparam = $this->_db->getConfig();
|
||||
$dbparam['dbname'] = $nomedb;
|
||||
$this->_db = Zend_Db::factory('Pdo_Mysql', $dbparam);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Zend_Db_Adapter_Abstract
|
||||
*/
|
||||
public function getDbAdapter()
|
||||
{
|
||||
return $this->_db;
|
||||
}
|
||||
|
||||
public function setDBConnection($nomeDB)
|
||||
{
|
||||
$this->_db->query('USE ' . $nomeDB);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
class App_Model_RestResource_Abstract
|
||||
{
|
||||
|
||||
const METHOD_BY_ID = 1;
|
||||
const METHOD_ALL_LIST = 2;
|
||||
const METHOD_FILTER = 3;
|
||||
const METHOD_GENERIC = 4;
|
||||
const METHOD_BY_COLUMNNAME = 5;
|
||||
const METHOD_CUSTOM_URL = 6;
|
||||
|
||||
protected $_apiUrl;
|
||||
protected $_apiVersion = "v1";
|
||||
protected $_secretId = false;
|
||||
protected $_testHeader = false;
|
||||
|
||||
protected $_httpClient = null;
|
||||
protected $_risorsa;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
if (!$this->_risorsa || !$this->_apiUrl || !$this->_apiVersion)
|
||||
throw new Exception("Non sono stati specificati tutti i parametri necessari alla risorsa (_risorsa,_apiUrl,_apiVersion)");
|
||||
|
||||
if ($this->_httpClient instanceof Zend_Http_Client) {
|
||||
//$this->_httpClient = $this->_httpClient;
|
||||
} else {
|
||||
$this->_httpClient = new Zend_Http_Client();
|
||||
$this->_httpClient->setConfig(array(
|
||||
'adapter' => 'Zend_Http_Client_Adapter_Curl',
|
||||
'maxredirects' => 0,
|
||||
'timeout' => 60,
|
||||
'ssltransport' => 'ssl'
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/***** METODI COMUNI DELLE CHIMATE *****/
|
||||
|
||||
public function postCall($dati)
|
||||
{
|
||||
$this->_httpClient->setMethod('POST');
|
||||
$this->_httpClient->setUri($this->getBaseUrl());
|
||||
$this->_httpClient->setRawData(json_encode($dati), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function updateById($id, $item)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('PUT');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_ID, array('id' => $id)));
|
||||
$this->_httpClient->setRawData(json_encode($item), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function deleteById($id)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('DELETE');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_ID, array('id' => $id)));
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getById($id)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_ID, array('id' => $id)));
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getByColumnName($column, $value)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_BY_COLUMNNAME, array('colname' => $column, 'value' => $value)));
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getList($paged = null, $count = null, $order = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_ALL_LIST));
|
||||
$this->_httpClient->setParameterGet(array('page' => $paged, 'count' => $count, 'order' => $order));
|
||||
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getFiltered($paged = null, $count = null, $order = null, $where = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
|
||||
if (is_array($order)) {
|
||||
$orderStr = "";
|
||||
$last_key = key(array_slice($order, -1, 1, TRUE));
|
||||
foreach ($order as $k => $val) {
|
||||
$orderStr .= $val;
|
||||
if ($k !== $last_key) $orderStr .= ",";
|
||||
}
|
||||
}
|
||||
if ($orderStr) $order = $orderStr;
|
||||
|
||||
$this->_httpClient->setParameterGet(array('page' => $paged, 'count' => $count, 'order' => $order));
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_FILTER, $where));
|
||||
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getByMethod($method, $params = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_GENERIC, $method));
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function getByCustomUrl($url, $params = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('GET');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_CUSTOM_URL, $url));
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
public function postByCustomUrl($url, $dati = null)
|
||||
{
|
||||
$this->_httpClient->resetParameters();
|
||||
$this->_httpClient->setMethod('POST');
|
||||
$this->_httpClient->setUri($this->getMethodUrl(self::METHOD_CUSTOM_URL, $url));
|
||||
$this->_httpClient->setRawData(json_encode($dati), 'application/json;charset=utf-8');
|
||||
return $this->executeCall();
|
||||
}
|
||||
|
||||
/***** METODI PRIVATI PER GESTIRE LE CHIAMATE *****/
|
||||
|
||||
private function getMethodUrl($method, $params = null)
|
||||
{
|
||||
$url = $this->getBaseUrl(!(self::METHOD_CUSTOM_URL === $method));
|
||||
switch ($method) {
|
||||
case self::METHOD_BY_ID:
|
||||
if (!isset($params['id'])) throw new Exception("Id Richiesto");
|
||||
$url .= "/" . $params['id'];
|
||||
break;
|
||||
case self::METHOD_ALL_LIST:
|
||||
break;
|
||||
case self::METHOD_FILTER:
|
||||
$url .= "/method/filtra";
|
||||
$this->_httpClient->setParameterGet($params);
|
||||
break;
|
||||
case self::METHOD_GENERIC:
|
||||
if (!$params) throw new Exception("Nome del metodo non valido");
|
||||
$url .= "/method/$params";
|
||||
break;
|
||||
case self::METHOD_BY_COLUMNNAME:
|
||||
if (!isset($params['colname'])) throw new Exception("Nome Colonna Richiesto");
|
||||
if (!isset($params['value'])) throw new Exception("Valore Richiesto");
|
||||
$url .= "/method/bycolumn/colname/" . $params['colname'] . "/val/" . $params['value'];
|
||||
break;
|
||||
case self::METHOD_CUSTOM_URL:
|
||||
if (!$params) throw new Exception("Nome dell'url non valido");
|
||||
$url .= "$params";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
|
||||
private function getBaseUrl($withResouces = true)
|
||||
{
|
||||
if ($withResouces) {
|
||||
return $this->_apiUrl . "/" . $this->_apiVersion . "/" . strtolower($this->_risorsa);
|
||||
} else {
|
||||
return $this->_apiUrl . "/" . $this->_apiVersion;
|
||||
}
|
||||
}
|
||||
|
||||
private function executeCall()
|
||||
{
|
||||
|
||||
if ($this->_secretId) {
|
||||
$this->_httpClient->setHeaders('Authorization', $this->_secretId);
|
||||
}
|
||||
|
||||
if ($this->_testHeader) {
|
||||
$this->_httpClient->setHeaders('X-As-Dev-On', '1');
|
||||
}
|
||||
|
||||
$httpResponse = $this->_httpClient->request();
|
||||
|
||||
//Zend_Registry::get('log')->info(print_r($this->_httpClient->getLastRequest(),true));
|
||||
//Zend_Registry::get('log')->info(print_r($httpResponse,true));
|
||||
|
||||
$httpResponseEncoded = json_decode($httpResponse->getBody(), 1);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore codifica JSON:");
|
||||
Zend_Registry::get('log')->info(print_r($httpResponse, true));
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->_httpClient->getLastResponse()->getStatus() != '200') {
|
||||
Zend_Registry::get('log')->info($this->_httpClient->getUri());
|
||||
Zend_Registry::get('log')->info("Errore status response " . $this->_httpClient->getLastResponse()->getStatus());
|
||||
Zend_Registry::get('log')->info(print_r($httpResponseEncoded, true));
|
||||
throw new App_Exception_ResponseCloudException($httpResponseEncoded['message'], $httpResponseEncoded['errorCode']);
|
||||
}
|
||||
|
||||
return $httpResponseEncoded;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
use PayPal\Auth\OAuthTokenCredential;
|
||||
use PayPal\Rest\ApiContext;
|
||||
use PayPal\Api\WebProfile;
|
||||
use PayPal\Api\Presentation;
|
||||
use PayPal\Api\InputFields;
|
||||
|
||||
class App_PayPal_PayPalApi
|
||||
{
|
||||
const LOGO_URL_IMAGE = "";
|
||||
const WEBPROFILE_NAME = '';
|
||||
|
||||
//Parametri test dell'account SANDBOX info-facilitator@adriaticasistemi.it
|
||||
const TEST_CLIENT_ID = '';
|
||||
const TEST_CLIENT_SECRET = '';
|
||||
|
||||
//Parametri per l'account LIVE info@adriaticasistemi.it
|
||||
const CLIENT_ID = '';
|
||||
const CLIENT_SECRET = '';
|
||||
|
||||
protected $_configs;
|
||||
protected $_ipManager;
|
||||
protected $_apiContext;
|
||||
protected $_apiPayPalTestAccount;
|
||||
|
||||
//Parametri di Default per la chiamata LIVE
|
||||
protected $_apiMode = "live";
|
||||
protected $_clientId = self::CLIENT_ID;
|
||||
protected $_clientSecret = self::CLIENT_SECRET;
|
||||
|
||||
//Parametri per il LOG di Default per la chiamata LIVE
|
||||
protected $_logEnabled = false;
|
||||
protected $_logFileName = APPLICATION_PATH . '/../log/PayPal.log';
|
||||
protected $_logLevel = "INFO";
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->_configs = new App_Service_ConfigManager();
|
||||
$this->_ipManager = new App_Service_IpManager();
|
||||
|
||||
//La modalita Test o Sandbox viene impostata dal parametro delle configurazioni e solo se la chiamata avviene da un IP abilitato
|
||||
$this->_apiPayPalTestAccount = false;
|
||||
if($this->_ipManager->allowedDevMode()){
|
||||
$this->_apiPayPalTestAccount = ($this->_configs->get('interrutore_paypal_test') == 'on') ? 1:0;
|
||||
}
|
||||
|
||||
if($this->_apiPayPalTestAccount){
|
||||
$this->_apiMode = "sandbox";
|
||||
$this->_logLevel = "DEBUG";
|
||||
$this->_clientId = self::TEST_CLIENT_ID;
|
||||
$this->_clientSecret = self::TEST_CLIENT_SECRET;
|
||||
}
|
||||
|
||||
//Controlla se il log è abilitato che esista anche il file su cui salvare altrimenti lo disabilita
|
||||
if($this->_logEnabled)
|
||||
$this->_logEnabled = file_exists($this->_logFileName);
|
||||
|
||||
$this->_apiContext = $this->setApiContext($this->_clientId, $this->_clientSecret);
|
||||
}
|
||||
|
||||
public function getPayPalContext()
|
||||
{
|
||||
return $this->_apiContext;
|
||||
}
|
||||
|
||||
public function getWebProfile(){
|
||||
|
||||
$webProfile = new WebProfile();
|
||||
|
||||
try {
|
||||
$webProfileList = $webProfile->get_list($this->_apiContext);
|
||||
} catch (Exception $ex) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//Controlla se gia esiste un web profile con il nome assegnato
|
||||
if($webProfileList){
|
||||
foreach($webProfileList as $profile){
|
||||
if($profile->name == self::WEBPROFILE_NAME){
|
||||
$webProfile = $profile;
|
||||
return $webProfile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Altrimenti lo creo con questi parametri specifici
|
||||
$webProfile->setName(self::WEBPROFILE_NAME);
|
||||
$webProfile->setTemporary(false);
|
||||
|
||||
$presentation = new Presentation();
|
||||
$presentation->setLogoImage(self::LOGO_URL_IMAGE);
|
||||
$webProfile->setPresentation($presentation);
|
||||
|
||||
$inputFields = new InputFields();
|
||||
$inputFields->setNoShipping(1);
|
||||
$webProfile->setInputFields($inputFields);
|
||||
|
||||
try {
|
||||
$webProfile = $webProfile->create($this->_apiContext);
|
||||
} catch (Exception $ex) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $webProfile;
|
||||
|
||||
}
|
||||
|
||||
public function deleteWebProfile(){
|
||||
|
||||
$webProfile = $this->getWebProfile();
|
||||
//Elimina questo web profile
|
||||
try {
|
||||
$webProfileRes = $webProfile->delete($this->_apiContext);
|
||||
} catch (Exception $ex) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
ResultPrinter::printResult("", "WebProfile", "", $webProfile, $webProfileRes);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function setApiContext($clientId, $clientSecret)
|
||||
{
|
||||
|
||||
$apiContext = new ApiContext(
|
||||
new OAuthTokenCredential(
|
||||
$clientId,
|
||||
$clientSecret
|
||||
)
|
||||
);
|
||||
|
||||
$apiContext->setConfig(
|
||||
array(
|
||||
'mode' => $this->_apiMode,
|
||||
'log.LogEnabled' => $this->_logEnabled,
|
||||
'log.FileName' => $this->_logFileName,
|
||||
'log.LogLevel' => $this->_logLevel,
|
||||
'cache.enabled' => true
|
||||
)
|
||||
);
|
||||
|
||||
return $apiContext;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
use \Stripe\Stripe;
|
||||
use \Stripe\Charge;
|
||||
use \Stripe\Token;
|
||||
|
||||
use \Stripe\Error\Card;
|
||||
|
||||
class App_Stripe_StripeApi
|
||||
{
|
||||
//Parametri test dell'account TEST STRIPE info@adriaticasistemi.it
|
||||
const TEST_SECRECT_KEY = '';
|
||||
const TEST_PUBLISHABLE_KEY = '';
|
||||
|
||||
//Parametri per l'account LIVE
|
||||
const LIVE_SECRET_KEY = '';
|
||||
const LIVE_PUBLISHABLE_KEY = '';
|
||||
|
||||
const DEFAULT_DESCRIPTION_TEXT = "";
|
||||
|
||||
protected $_apiStripeTestAccount;
|
||||
protected $_configs;
|
||||
protected $_ipManager;
|
||||
|
||||
protected $_secretKey;
|
||||
protected $_publishableKey;
|
||||
protected $_currency;
|
||||
|
||||
protected $_Stripe;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
$this->_currency = 'eur';
|
||||
$this->_configs = new App_Service_ConfigManager();
|
||||
$this->_ipManager = new App_Service_IpManager();
|
||||
|
||||
$this->_apiStripeTestAccount = false;
|
||||
if($this->_ipManager->allowedDevMode()){
|
||||
$this->_apiStripeTestAccount = ($this->_configs->get('interrutore_stripe_test') == 'on') ? 1:0;
|
||||
}
|
||||
|
||||
if ($this->_apiStripeTestAccount){
|
||||
$this->_secretKey = self::TEST_SECRECT_KEY;
|
||||
$this->_publishableKey = self::TEST_PUBLISHABLE_KEY;
|
||||
} else{
|
||||
$this->_secretKey = self::LIVE_SECRET_KEY;
|
||||
$this->_publishableKey = self::LIVE_PUBLISHABLE_KEY;
|
||||
}
|
||||
$this->_Stripe = new Stripe();
|
||||
$this->_Stripe->setApiKey($this->_secretKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $number
|
||||
* @param $exp_month
|
||||
* @param $exp_year
|
||||
* @param $cvc
|
||||
* @param null $extraData
|
||||
*
|
||||
* @return \Stripe\ApiOperations\ApiResource
|
||||
*/
|
||||
public function createToken($number, $exp_month, $exp_year, $cvc,$extraData = null)
|
||||
{
|
||||
$card = array(
|
||||
'number' => $number,
|
||||
'exp_month' => $exp_month,
|
||||
'exp_year' => $exp_year,
|
||||
'cvc' => $cvc
|
||||
);
|
||||
|
||||
//Nel caso in cui passo dei dati extra li aggiungo alla chiamata per la creazionde del token
|
||||
if($extraData && (is_array($extraData) || is_object($extraData))){
|
||||
foreach($extraData as $key => $val){
|
||||
$card[$key] = $val;
|
||||
}
|
||||
}
|
||||
|
||||
$token = Token::create(array('card' => $card));
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $amount
|
||||
* @param $token
|
||||
* @param string $description
|
||||
*
|
||||
* @return \Stripe\ApiOperations\ApiResource
|
||||
* @throws Exception
|
||||
*/
|
||||
public function createCharge($amount, $token,$description = self::DEFAULT_DESCRIPTION_TEXT)
|
||||
{
|
||||
|
||||
if(!$token)
|
||||
throw new Exception("Il Token non è stato generato correttamente");
|
||||
|
||||
$charge = Charge::create(array(
|
||||
"amount" => $amount,
|
||||
"currency" => $this->_currency,
|
||||
"card" => $token,
|
||||
"description"=>$description
|
||||
));
|
||||
return $charge;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user