Initial Commit

This commit is contained in:
GiacomoHome
2021-09-17 12:41:45 +02:00
commit 9001e4656e
570 changed files with 31013 additions and 0 deletions
@@ -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;
}
}
+264
View File
@@ -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);
}
}
+572
View File
@@ -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)));
}
}