diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 0b31c0ad..6102eccc 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -16,17 +16,15 @@ $routes->get('/', 'Home::index', ['as' => 'home']); $routes->get('lang/{locale}', 'Language::index'); $routes->get('viewmode/(:alpha)', 'Viewmode::index/$1'); +/* URL FOR TESTS */ +$routes->get('test', 'Test::index'); + $routes->group('activity', ['namespace' => 'App\Controllers\Sistema'], function ($routes) { $routes->get('', 'Actividad::index', ['as' => 'activityList']); $routes->post('datatable', 'Actividad::datatable', ['as' => 'activityDT']); }); -$routes->group('settings', ['namespace' => 'App\Controllers\Sistema'], function ($routes) { - $routes->get('', 'Ajustes::settings', ['as' => 'ajustesList']); - $routes->post('', 'Ajustes::settings', ['as' => 'ajustesEdit']); -}); - /* * -------------------------------------------------------------------- diff --git a/ci4/app/Controllers/BaseController.php b/ci4/app/Controllers/BaseController.php index de8b1e4c..3e1c82a1 100755 --- a/ci4/app/Controllers/BaseController.php +++ b/ci4/app/Controllers/BaseController.php @@ -2,8 +2,6 @@ namespace App\Controllers; -use App\Models\NotificationModel; -use App\Models\SettingsModel; use CodeIgniter\Controller; use CodeIgniter\HTTP\CLIRequest; use CodeIgniter\HTTP\IncomingRequest; diff --git a/ci4/app/Controllers/GoBaseController.php b/ci4/app/Controllers/GoBaseController.php index 669b0368..992edbb4 100755 --- a/ci4/app/Controllers/GoBaseController.php +++ b/ci4/app/Controllers/GoBaseController.php @@ -17,10 +17,10 @@ namespace App\Controllers; */ use CodeIgniter\Controller; use CodeIgniter\Database\Query; -use App\Models\NotificationModel; -abstract class GoBaseController extends Controller { +abstract class GoBaseController extends Controller +{ /** * @@ -102,7 +102,7 @@ abstract class GoBaseController extends Controller { * @var array */ public $viewData; - + /** * JJO: Variable para indicar si el controlador hace soft_delete o no @@ -139,14 +139,15 @@ abstract class GoBaseController extends Controller { * * @var array */ - protected $helpers = ['session', 'go_common', 'text', 'general','jwt', 'rbac']; //JJO + protected $helpers = ['session', 'go_common', 'text', 'general', 'jwt', 'rbac']; //JJO public static $queries = []; /** * Constructor. */ - public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) { + public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) + { // Do Not Edit This Line parent::initController($request, $response, $logger); @@ -155,9 +156,9 @@ abstract class GoBaseController extends Controller { //-------------------------------------------------------------------- // E.g.: $this->session = \Config\Services::session(); - - if ((!isset($this->viewData['pageTitle']) || empty($this->viewData['pageTitle']) ) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) { + + if ((!isset($this->viewData['pageTitle']) || empty($this->viewData['pageTitle'])) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) { $this->viewData['pageTitle'] = ucfirst(static::$pluralObjectName); } @@ -171,7 +172,7 @@ abstract class GoBaseController extends Controller { if (empty(static::$controllerSlug)) { $reflect = new \ReflectionClass($this); $className = $reflect->getShortName(); - $this->viewData['currentModule'] = slugify(convertToSnakeCase(str_replace('Controller','',$className))); + $this->viewData['currentModule'] = slugify(convertToSnakeCase(str_replace('Controller', '', $className))); } else { $this->viewData['currentModule'] = strtolower(static::$controllerSlug); @@ -185,43 +186,31 @@ abstract class GoBaseController extends Controller { $this->model = &$this->primaryModel; } - // Preload any models, libraries, etc, here. + // Preload any models, libraries, etc, here. + - // Language Validate $language = \Config\Services::language(); $language->setLocale($this->session->lang); // Set TimeZone - if(empty($this->session->get('settings'))){ - $settingsModel = new SettingsModel(); - $settings = $settingsModel->select('default_timezone')->first()??[]; - date_default_timezone_set($this->$settings['default_timezone']??'America/Sao_Paulo'); - }else{ - date_default_timezone_set($this->session->get('settings')['default_timezone']??'America/Sao_Paulo'); + if (empty($this->session->get('settings'))) { + $time_zone = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('default_timezone')->value; + date_default_timezone_set($time_zone ?? 'Europe/Madrid'); + } else { + date_default_timezone_set($this->session->get('settings')['default_timezone'] ?? 'Europe/Madrid'); } - // Get notification - if(!empty($this->session->get('token'))) { - $notificationModel = new NotificationModel(); - $pulse = $notificationModel->where('user_recipient',$this->session->get('token'))->where('is_read',false)->countAllResults() ?? 0; - $notification = $notificationModel->select('token,title,is_read,created_at')->where('user_recipient',$this->session->get('token'))->orderBy('created_at','desc')->findAll(5) ?? []; - $this->session->set('notification', $notification); - $this->session->set('pulse', $pulse); - }else{ - $this->session->set('notification', []); - $this->session->set('pulse', 0); - } - $this->viewData['currentLocale'] = $this->request->getLocale(); } - public function index() { + public function index() + { helper('text'); - if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle']) ) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) { + if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle'])) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) { $this->viewData['boxTitle'] = ucfirst(static::$pluralObjectName); } @@ -236,10 +225,10 @@ abstract class GoBaseController extends Controller { // if $this->currentView is assigned a view name, use it, otherwise assume the view something like 'viewSingleObjectList' $viewFilePath = static::$viewPath . (empty($this->currentView) ? 'view' . ucfirst(static::$singularObjectNameCc) . 'List' : $this->currentView); - + echo view($viewFilePath, $this->viewData); - - + + } /** @@ -248,12 +237,13 @@ abstract class GoBaseController extends Controller { * @param null $objId * @return string */ - protected function displayForm($forMethod, $objId = null) { + protected function displayForm($forMethod, $objId = null) + { helper('form'); $this->viewData['usingSelect2'] = true; - - $validation = \Config\Services::validation(); + + $validation = \Config\Services::validation(); $action = str_replace(static::class . '::', '', $forMethod); $actionSuffix = ' '; @@ -270,13 +260,13 @@ abstract class GoBaseController extends Controller { } if (!isset($this->viewData['formAction'])) { - $this->viewData['formAction'] = base_url(strtolower($this->viewData['currentModule']) . '/' . $action . '/' . $formActionSuffix); + $this->viewData['formAction'] = base_url(strtolower($this->viewData['currentModule']) . '/' . $action . '/' . $formActionSuffix); } - if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle']) ) && isset(static::$singularObjectName) && !empty(static::$singularObjectName)) { + if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle'])) && isset(static::$singularObjectName) && !empty(static::$singularObjectName)) { $this->viewData['boxTitle'] = ucfirst($action) . $actionSuffix . ucfirst(static::$singularObjectName); } - + $this->viewData['validation'] = $validation; $viewFilePath = static::$viewPath . 'view' . ucfirst(static::$singularObjectNameCc) . 'Form'; @@ -284,7 +274,8 @@ abstract class GoBaseController extends Controller { return view($viewFilePath, $this->viewData); } - protected function redirect2listView($flashDataKey = null, $flashDataValue = null) { + protected function redirect2listView($flashDataKey = null, $flashDataValue = null) + { if (!empty($this->indexRoute)) { $uri = base_url(route_to($this->indexRoute)); @@ -304,9 +295,9 @@ abstract class GoBaseController extends Controller { } else { $getHandlingRoutes = $routes->getRoutes('get'); - $indexMethod = array_search('\\App\\Controllers\\'.$className.'::index', $getHandlingRoutes); + $indexMethod = array_search('\\App\\Controllers\\' . $className . '::index', $getHandlingRoutes); if ($indexMethod) { - $uri = route_to('App\\Controllers\\'.$className.'::index'); + $uri = route_to('App\\Controllers\\' . $className . '::index'); } else { $uri = base_url(static::$controllerSlug); } @@ -315,7 +306,7 @@ abstract class GoBaseController extends Controller { $uri = base_url($className); } } - + if ($flashDataKey != null && $flashDataValue != null) { return redirect()->to($uri)->with($flashDataKey, $flashDataValue); } else { @@ -323,10 +314,11 @@ abstract class GoBaseController extends Controller { } } - public function delete($requestedId, bool $deletePermanently = true) { + public function delete($requestedId, bool $deletePermanently = true) + { - if (is_string($requestedId)) : - if (is_numeric($requestedId)) : + if (is_string($requestedId)): + if (is_numeric($requestedId)): $id = filter_var($requestedId, FILTER_SANITIZE_NUMBER_INT); else: $onlyAlphaNumeric = true; @@ -338,64 +330,66 @@ abstract class GoBaseController extends Controller { $id = intval($requestedId); endif; - if (empty($id) || $id === 0) : + if (empty($id) || $id === 0): $error = 'Invalid identifier provided to delete the object.'; endif; $rawResult = null; - if (!isset($error)) : + if (!isset($error)): try { - if ($deletePermanently && !$this->soft_delete) : - if (is_numeric($id)) : - $rawResult = $this->primaryModel->delete($id); - else: - $rawResult = $this->primaryModel->where($this->primaryModel->getPrimaryKeyName(), $id)->delete(); - endif; - elseif ($this->soft_delete): - $datetime = (new \CodeIgniter\I18n\Time("now")); - $rawResult = $this->primaryModel->where('id',$id) - ->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'), - 'is_deleted' => $this->delete_flag]) - ->update(); + if ($deletePermanently && !$this->soft_delete): + if (is_numeric($id)): + $rawResult = $this->primaryModel->delete($id); + else: + $rawResult = $this->primaryModel->where($this->primaryModel->getPrimaryKeyName(), $id)->delete(); + endif; + elseif ($this->soft_delete): + $datetime = (new \CodeIgniter\I18n\Time("now")); + $rawResult = $this->primaryModel->where('id', $id) + ->set([ + 'deleted_at' => $datetime->format('Y-m-d H:i:s'), + 'is_deleted' => $this->delete_flag + ]) + ->update(); - else: - $rawResult = $this->primaryModel->update($id, ['deleted' => true]); - endif; + else: + $rawResult = $this->primaryModel->update($id, ['deleted' => true]); + endif; } catch (\Exception $e) { - log_message('error', "Exception: Error deleting object named '".(static::$singularObjectName ?? 'unknown')."' with $id :\r\n".$e->getMessage()); + log_message('error', "Exception: Error deleting object named '" . (static::$singularObjectName ?? 'unknown') . "' with $id :\r\n" . $e->getMessage()); } endif; $ar = $this->primaryModel->db->affectedRows(); - + try { $dbError = $this->primaryModel->db->error(); } catch (\Exception $e2) { if ($e2->getMessage() != "Trying to get property 'errno' of non-object") { - log_message('error', $e2->getCode() . ' : ' . $e2->getMessage()) ; + log_message('error', $e2->getCode() . ' : ' . $e2->getMessage()); } } if (isset($dbError['code']) && isset($dbError['message'])) { - log_message('error', $dbError['code'].' '.$dbError['message']); + log_message('error', $dbError['code'] . ' ' . $dbError['message']); } else { - $dbError = ['code' => '', 'message'=>'']; + $dbError = ['code' => '', 'message' => '']; } - $result = ['persisted'=>$ar>0, 'ar'=>$ar, 'persistedId'=>null, 'affectedRows'=>$ar, 'errorCode'=>$dbError['code'], 'error'=>$dbError['message']]; - + $result = ['persisted' => $ar > 0, 'ar' => $ar, 'persistedId' => null, 'affectedRows' => $ar, 'errorCode' => $dbError['code'], 'error' => $dbError['message']]; + $nameOfDeletedObject = static::$singularObjectNameCc; - - if ($ar < 1) : + + if ($ar < 1): $errorMessage = lang('Basic.global.deleteError', [$nameOfDeletedObject]); // 'No ' . static::$singularObjectName . ' was deleted now, because it probably had already been deleted.'; - $fdKey = isset($this->viewData['usingSweetAlert'] ) && $this->viewData['usingSweetAlert'] ? 'sweet-error' : 'errorMessage'; + $fdKey = isset($this->viewData['usingSweetAlert']) && $this->viewData['usingSweetAlert'] ? 'sweet-error' : 'errorMessage'; $errorMessage = str_replace("'", "\'", $errorMessage); return $this->redirect2listView($fdKey, str_replace("'", '', $errorMessage)); else: $message = lang('Basic.global.deleteSuccess', [$nameOfDeletedObject]); // 'The ' . static::$singularObjectName . ' was successfully deleted.'; - $fdKey = isset($this->viewData['usingSweetAlert'] ) && $this->viewData['usingSweetAlert'] ? 'sweet-success' : 'successMessage'; - if ($result['affectedRows']>1) : - log_message('warning', "More than one row has been deleted in attempt to delete row for object named '".(static::$singularObjectName ?? 'unknown')."' with id: $id"); + $fdKey = isset($this->viewData['usingSweetAlert']) && $this->viewData['usingSweetAlert'] ? 'sweet-success' : 'successMessage'; + if ($result['affectedRows'] > 1): + log_message('warning', "More than one row has been deleted in attempt to delete row for object named '" . (static::$singularObjectName ?? 'unknown') . "' with id: $id"); endif; $message = str_replace("'", "\'", $message); return $this->redirect2listView($fdKey, $message); @@ -403,7 +397,7 @@ abstract class GoBaseController extends Controller { } - /** + /** * Convenience method to validate form submission * @return bool */ @@ -416,14 +410,15 @@ abstract class GoBaseController extends Controller { return true; } - $validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;; + $validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null; + ; if ($validationErrorMessages != null) { $valid = $this->validate($validationRules, $validationErrorMessages); } else { $valid = $this->validate($validationRules); } - + $this->validationErrors = $valid ? '' : $this->validator->getErrors(); /* @@ -443,7 +438,8 @@ abstract class GoBaseController extends Controller { * @param array|null $postData * @return array */ - protected function sanitized(array $postData = null, bool $nullIfEmpty = false) { + protected function sanitized(array $postData = null, bool $nullIfEmpty = false) + { if ($postData == null) { $postData = $this->request->getPost(); } @@ -462,29 +458,31 @@ abstract class GoBaseController extends Controller { * Convenience method for common exception handling * @param \Exception $e */ - protected function dealWithException(\Exception $e) { + protected function dealWithException(\Exception $e) + { // using another try / catch block to prevent to avoid CodeIgniter bug throwing trivial exceptions for querying DB errors try { $query = $this->model->db->getLastQuery(); $queryStr = !is_null($query) ? $query->getQuery() : ''; $dbError = $this->model->db->error(); $userFriendlyErrMsg = lang('Basic.global.persistErr1', [static::$singularObjectNameCc]); - if (isset($dbError['code']) && $dbError['code'] == 1062) : - $userFriendlyErrMsg .= PHP_EOL.lang('Basic.global.persistDuplErr', [static::$singularObjectNameCc]); + if (isset($dbError['code']) && $dbError['code'] == 1062): + $userFriendlyErrMsg .= PHP_EOL . lang('Basic.global.persistDuplErr', [static::$singularObjectNameCc]); endif; // $userFriendlyErrMsg = str_replace("'", "\'", $userFriendlyErrMsg); // Uncomment if experiencing unescaped single quote errors - log_message('error', $userFriendlyErrMsg.PHP_EOL.$e->getMessage().PHP_EOL.$queryStr); - if (isset($dbError['message']) && !empty($dbError['message'])) : - log_message('error', $dbError['code'].' : '.$dbError['message']); + log_message('error', $userFriendlyErrMsg . PHP_EOL . $e->getMessage() . PHP_EOL . $queryStr); + if (isset($dbError['message']) && !empty($dbError['message'])): + log_message('error', $dbError['code'] . ' : ' . $dbError['message']); endif; $this->viewData['errorMessage'] = $userFriendlyErrMsg; } catch (\Exception $e2) { - log_message('debug', 'You can probably safely ignore this: In attempt to check DB errors, CodeIgniter threw: '.PHP_EOL.$e2->getMessage()); + log_message('debug', 'You can probably safely ignore this: In attempt to check DB errors, CodeIgniter threw: ' . PHP_EOL . $e2->getMessage()); } } // Collect the queries so something can be done with them later. - public static function collect(Query $query) { + public static function collect(Query $query) + { static::$queries[] = $query; } @@ -495,7 +493,8 @@ abstract class GoBaseController extends Controller { * @param object $sourceObject * @return object */ - function cast($destination, $sourceObject) { + function cast($destination, $sourceObject) + { if (is_string($destination)) { $destination = new $destination(); } diff --git a/ci4/app/Controllers/Integration.php b/ci4/app/Controllers/Integration.php deleted file mode 100755 index fc72033b..00000000 --- a/ci4/app/Controllers/Integration.php +++ /dev/null @@ -1,518 +0,0 @@ -user_model = new UserModel(); - $this->settings_model = new SettingsModel(); - $this->pass_recovery_model = new PasswordRecoveryModel(); - $this->template_model = new TemplateModel(); - $this->activity_model = new ActivityModel(); - $this->id_user = session()->get('id_user'); - $this->token_user = session()->get('token'); - } - - public function index() - { - echo view(getenv('theme.path').'main/header'); - echo view(getenv('theme.path').'form/dashboard/index'); - echo view(getenv('theme.path').'main/footer'); - } - - public function send_email($email='',$subject='',$body='',$key='',$json=false){ - if(empty($email)){ - return $json ? json_encode(["return" => false]) : false; - } - $phpass = new PasswordHash(8, true); - if(!$phpass->CheckPassword(MD5($email), $key)){ - return $json ? json_encode(["return" => false]) : false; - } - $user = $this->user_model->where('email',$email??null)->first(); - if(!empty($user)){ - foreach (keywordEmail()??[] as $item){ - $field = str_replace(['[','user_',']'],'',$item); - if(str_contains($body, $field)){ - $body = str_replace('['.$item.']',$user->{$field},$body); - } - } - } - - if($this->sendMail($subject,unescape($body),$email)){ - return $json ? json_encode(["return" => true]) : true; - }else{ - return $json ? json_encode(["return" => false]) : false; - } - } - - public function send_email_test($email=''){ - $token = session()->get('token')??''; - if(!empty($token)){ - if(empty($email)){ - return $this->response->setJSON(["return" => false]); - } - $subject = "Email Test"; - $body = "Email working successfully!"; - if($this->sendMail($subject,unescape($body),$email)){ - return $this->response->setJSON(["return" => true]); - }else{ - return $this->response->setJSON(["return" => false]); - } - }else{ - return $this->response->setJSON(["return" => false]); - } - } - - - public function reset_password(){ - $session = session(); - $settings = $session->get('settings'); - helper('text'); - - if($listPost = $this->request->getPost()){ - - // Captcha Validation - if($settings['captcha_recovery']??false){ - if($settings['captcha_gateway'] == 'recaptcha'){ - if(isset($listPost['g-recaptcha-response'])){ - $captcha = $listPost['g-recaptcha-response']; - $url = 'https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha); - $response = file_get_contents($url); - $responseKeys = json_decode($response,true); - if(!$responseKeys["success"]) { - $session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]); - return redirect()->to('/login/forgot_password'); - } - }else{ - $session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]); - return redirect()->to('/login/forgot_password'); - } - } - if($settings['captcha_gateway'] == 'hcaptcha'){ - if(isset($listPost['h-captcha-response'])){ - $captcha = $listPost['h-captcha-response']; - $url = 'https://hcaptcha.com/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']; - $response = file_get_contents($url); - $responseKeys = json_decode($response,true); - if(!$responseKeys["success"]) { - $session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]); - return redirect()->to('/login/forgot_password'); - } - }else{ - $session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]); - return redirect()->to('/login/forgot_password'); - } - } - } - - $user = $this->user_model->where('email',$listPost['email']??null)->first(); - - if(empty($user)){ - $session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_user_not_found")]); - return redirect()->to('/login/forgot_password'); - } - - $template = $this->template_model->where('id_template',1)->first(); - - foreach (keywordEmail()??[] as $item){ - $field = str_replace(['[','user_',']'],'',$item); - $template = str_replace('['.$item.']',$user->$field ?? "",$template); - } - - $token = random_string("alnum", 50); - $url = base_url().'login/recovery/'.$token; - - $this->pass_recovery_model->save([ - 'user' => $user->token, - 'token' => $token - ]); - - $title = $template['subject']??''; - $msg = $template['body']??''; - $msg = str_replace('[recovery_password]',$url,$msg); - $email = $user->email; - - $this->setLog('recovery','recovery-password',$user->token); - $send = $this->sendMail($title,$msg,$email); - if($send){ - $session->setFlashdata('toast', ['success',lang("App.login_alert_send"),lang("App.login_alert_send_pass")]); - return redirect()->to('/login/forgot_password'); - }else{ - $session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_error_email")]); - return redirect()->to('/login/forgot_password'); - } - }else{ - $session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_error_pass")]); - return redirect()->to('/login/forgot_password'); - } - } - - public function setLog($level,$event,$user='') - { - $request = \Config\Services::request(); - $ip = $request->getIPAddress(); - $agent = $request->getUserAgent(); - - if ($agent->isBrowser()) - { - $currentAgent = $agent->getBrowser().' '.$agent->getVersion(); - } - elseif ($agent->isRobot()) - { - $currentAgent = $this->agent->robot(); - } - elseif ($agent->isMobile()) - { - $currentAgent = $agent->getMobile(); - } - else - { - $currentAgent = 'Unidentified User Agent'; - } - - $this->activity_model->save([ - 'user' => $this->token_user??$user, - 'level' => $level, - 'event' => $event, - 'ip' => $ip, - 'os' => $agent->getPlatform(), - 'browser' => $currentAgent, - 'detail' => $agent - ]); - } - - private function sendMail($subject,$body,$recipient) - { - $config = $this->settings_model->first(); - $gateway = $config['email_gateway']; - $body = html_entity_decode($body); - - if($gateway == 'smtp'){ - try { - //https://codeigniter.com/user_guide/libraries/email.html - $email = \Config\Services::email(); - $config['protocol'] = $config['email_gateway']; - $config['SMTPHost'] = $config['email_smtp']; - $config['SMTPUser'] = $config['email_address']; - $config['SMTPPass'] = $config['email_pass']; - $config['SMTPPort'] = $config['email_port']; - $config['SMTPCrypto'] = $config['email_cert']=='none'?'':$config['email_cert']; - $config['SMTPTimeout'] = 15; - $config['mailType'] = 'html'; - $config['wordWrap'] = true; - - $email->initialize($config); - - $email->setFrom($config['email_address'], $config['email_name']); - $email->setTo($recipient); - - $email->setSubject($subject); - $email->setMessage($body); - - if (!$email->send()) - { - return false; - }else{ - return true; - } - } catch (\Exception $ex) { - return false; - } - } - return false; - } - - public function saveStorage($file=null,$path='',$allow=[]){ - $config = $this->settings_model->first(); - $gateway = $config['storage_gateway']; - - switch ($gateway) { - case "local": - try { - $ext = $file ? $file->getExtension() : ''; - if (in_array(strtolower($ext), $allow)) { - if(strtolower(PHP_OS) == 'linux'){ - $pathServer = $path; - }else{ - $pathServer = str_replace('/','\\',$path); - } - if ($file->isValid()) { - $name = $file->getName(); - $rename = $file->getRandomName(); - $file->move($pathServer,$rename); - return $path.$rename; - } - } - return null; - } catch (\Exception $ex) { - return null; - } - - case "aws": - case "minio": - $aws_endpoint = $config['aws_endpoint']; - $aws_key = $config['aws_key']; - $aws_secret = $config['aws_secret']; - $aws_region = $config['aws_region']; - $aws_bucket = $config['aws_bucket']; - - try { - $ext = $file ? $file->getExtension() : ''; - if (in_array(strtolower($ext), $allow)) { - - if($gateway=="minio"){ - $s3Client = new \Aws\S3\S3Client([ - 'version' => 'latest', - 'region' => $aws_region, - 'endpoint' => $aws_endpoint, - 'use_path_style_endpoint' => true, - 'credentials' => [ - 'key' => $aws_key, - 'secret' => $aws_secret - ] - ]); - }else{ - $s3Client = new \Aws\S3\S3Client([ - 'version' => 'latest', - 'region' => $aws_region, - 'credentials' => [ - 'key' => $aws_key, - 'secret' => $aws_secret - ] - ]); - } - - try { - $rename = $file->getRandomName(); - $file->move(WRITEPATH.'uploads',$rename); - if(strtolower(PHP_OS) == 'linux'){ - $file_Path = WRITEPATH.'uploads/'. $rename; - }else{ - $file_Path = WRITEPATH.'uploads\\'. $rename; - } - $result = $s3Client->putObject([ - 'Bucket' => $aws_bucket, - 'Key' => $rename, - 'Body' => fopen($file_Path, 'r') - ]); - unlink($file_Path); - if($result['@metadata']['statusCode'] == 200){ - return $result['@metadata']['effectiveUri']; - }else{ - return null; - } - } catch (\Aws\S3\Exception\S3Exception $e) { - return null; - } - } - return null; - } catch (\Exception $ex) { - return null; - } - default: - return null; - } - } - - public function saveStorageBackup($file=null,$name=null){ - $config = $this->settings_model->first(); - $gateway = $config['backup_storage']; - - switch ($gateway) { - case "local": - try { - return $file; - } catch (\Exception $ex) { - return null; - } - - case "aws": - case "minio": - $aws_endpoint = $config['aws_endpoint']; - $aws_key = $config['aws_key']; - $aws_secret = $config['aws_secret']; - $aws_region = $config['aws_region']; - $aws_bucket = $config['aws_bucket']; - - try { - if($gateway=="minio"){ - $s3Client = new \Aws\S3\S3Client([ - 'version' => 'latest', - 'region' => $aws_region, - 'endpoint' => $aws_endpoint, - 'use_path_style_endpoint' => true, - 'credentials' => [ - 'key' => $aws_key, - 'secret' => $aws_secret - ] - ]); - }else{ - $s3Client = new \Aws\S3\S3Client([ - 'version' => 'latest', - 'region' => $aws_region, - 'credentials' => [ - 'key' => $aws_key, - 'secret' => $aws_secret - ] - ]); - } - - try { - $result = $s3Client->putObject([ - 'Bucket' => $aws_bucket, - 'Key' => $name, - 'Body' => fopen($file, 'r') - ]); - unlink($file); - if($result['@metadata']['statusCode'] == 200){ - return $result['@metadata']['effectiveUri']; - }else{ - return null; - } - } catch (\Aws\S3\Exception\S3Exception $e) { - return null; - } - } catch (\Exception $ex) { - return null; - } - default: - return null; - } - } - - public function create_backup($download=false) - { - //Demo Mode - if(env('demo.mode')??false){ - if($download==true){ - session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]); - return redirect()->to('/settings'); - }else{ - die(); - } - } - $settings = $this->settings_model->first()??[]; - if($settings['backup_automatic']){ - helper('text'); - $db = db_connect('default'); - try { - $all = false; - $tables = explode(',',$settings['backup_table']??''); - foreach ($tables as $item){ - if ($item == 'all'){ - $all = true; - } - } - $token = random_string("alnum", 10); - $name ='mysql_'.$token.'_'.date("YmdHis").'.sql'; - if(strtolower(PHP_OS) == 'linux'){ - $file_Path = WRITEPATH.'uploads/'.$name; - }else{ - $file_Path = WRITEPATH.'uploads\\'.$name; - } - if($all){ - \Spatie\DbDumper\Databases\MySql::create() - ->setHost(getenv('database.default.hostname')) - ->setDbName(getenv('database.default.database')) - ->setUserName(getenv('database.default.username')) - ->setPassword(getenv('database.default.password')) - ->setDumpBinaryPath(getenv('database.default.dump')) - ->dumpToFile($file_Path); - }else{ - \Spatie\DbDumper\Databases\MySql::create() - ->setHost(getenv('database.default.hostname')) - ->setDbName(getenv('database.default.database')) - ->setUserName(getenv('database.default.username')) - ->setPassword(getenv('database.default.password')) - ->setDumpBinaryPath(getenv('database.default.dump')) - ->includeTables($tables) - ->dumpToFile($file_Path); - } - $file = $this->saveStorageBackup($file_Path,$name); - $db->query("INSERT INTO backup VALUES (NULL,'".$file."','',NOW(),NOW())"); - if($settings['backup_notification_email']){ - $send = $this->send_email($settings['backup_email'],$settings['title']." (BACKUP)",lang("App.crontab_backup_success").date("Y-m-d H:i:s")); - if(!$send){ - $db->query("INSERT INTO backup VALUES (NULL,'','".lang("App.crontab_email_error")."',NOW(),NOW())"); - } - } - if($download){ - $this->download_backup($file,$name); - } - } catch (\Spatie\DbDumper\Exceptions\DumpFailed $e) { - $error = str_replace("'","\'",$e->getMessage()); - $db->query("INSERT INTO backup VALUES (NULL,'','".$error."',NOW(),NOW())"); - if($settings['backup_notification_email']){ - $send = $this->send_email($settings['backup_email'],$settings['title']." (BACKUP ERROR)",'Error: '.$e->getMessage()); - if(!$send){ - $db->query("INSERT INTO backup VALUES (NULL,'','".lang("App.crontab_email_error")."',NOW(),NOW())"); - } - } - if($download){ - session()->setFlashdata('sweet', ['error',lang("App.crontab_backup_error")]); - return redirect()->to('/settings'); - } - } - } - } - - private function download_backup($path=null,$name=null) - { - if (!empty(session()->get('token')??'')){ - set_time_limit(0); - if(!empty($path) && !empty($name) && file_exists($path)){ - header('Content-Description: File Transfer'); - header('Content-Disposition: attachment; filename="'.$name.'"'); - header('Content-Type: application/octet-stream'); - header('Content-Transfer-Encoding: binary'); - header('Content-Length: ' . filesize($path)); - header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); - header('Pragma: public'); - header('Expires: 0'); - readfile($path); - } - }else{ - return redirect()->to('/settings'); - } - } - - public function download_postman() - { - if(!empty(session()->get('token')??'')){ - set_time_limit(0); - $path = WRITEPATH.'postman_collection.json'; - if(file_exists($path)){ - header('Content-Description: File Transfer'); - header('Content-Disposition: attachment; filename="WebGuard ApiRest - postman_collection.json"'); - header('Content-Type: application/octet-stream'); - header('Content-Transfer-Encoding: binary'); - header('Content-Length: ' . filesize($path)); - header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); - header('Pragma: public'); - header('Expires: 0'); - readfile($path); - } - }else{ - return redirect()->to('/settings'); - } - } - -} diff --git a/ci4/app/Controllers/Sistema/Ajustes.php b/ci4/app/Controllers/Sistema/Ajustes.php deleted file mode 100644 index a610783f..00000000 --- a/ci4/app/Controllers/Sistema/Ajustes.php +++ /dev/null @@ -1,111 +0,0 @@ -viewData['pageTitle'] = lang('Provincias.moduleTitle'); - $this->viewData['usingSweetAlert'] = true; - - // Breadcrumbs (IMN) - $this->viewData['breadcrumb'] = [ - ['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false], - ['title' => lang("App.menu_settings"), 'route' => route_to('ajustesList'), 'active' => true] - ]; - - parent::initController($request, $response, $logger); - } - - - public function settings() - { - checkPermission('ajustes.menu'); - - $id = 1; - $settingsEntity = $this->model->find($id); - - if (!$settingsEntity) : - $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Provincias.provincia')), $id]); - return $this->redirect2listView('sweet-error', $message); - endif; - - - if ($this->request->is('post')) : - - $postData = $this->request->getPost(); - - $sanitizedData = $this->sanitized($postData, true); - - $noException = true; - if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : - - - if ($this->canValidate()) : - try { - $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData); - } catch (\Exception $e) { - $noException = false; - $this->dealWithException($e); - } - else: - $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Provincias.provincia'))]); - $this->session->setFlashdata('formErrors', $this->model->errors()); - - endif; - - $settingsEntity->fill($sanitizedData); - - $thenRedirect = false; - endif; - if ($noException && $successfulResult) : - $id = $settingsEntity->id ?? $id; - $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.'; - - if ($thenRedirect) : - if (!empty($this->indexRoute)) : - return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); - else: - return $this->redirect2listView('sweet-success', $message); - endif; - else: - $this->session->setFlashData('sweet-success', $message); - endif; - - endif; // $noException && $successfulResult - endif; // ($requestMethod === 'post') - - $this->viewData['settingsEntity'] = $settingsEntity; - $this->viewData['formAction'] = route_to('settingsEdit'); - - $this->viewData['tables'] = db_connect()->listTables(); - - - return $this->displayForm(__METHOD__, $id); - } // end function settings(...) - - - - - -} diff --git a/ci4/app/Controllers/Soporte/Ticketcontroller.php b/ci4/app/Controllers/Soporte/Ticketcontroller.php index d9b65178..527c83f9 100644 --- a/ci4/app/Controllers/Soporte/Ticketcontroller.php +++ b/ci4/app/Controllers/Soporte/Ticketcontroller.php @@ -2,7 +2,6 @@ namespace App\Controllers\Soporte; -use App\Models\Sistema\SettingsModel; use App\Models\Soporte\TicketModel; use App\Models\CategoriaModel; use App\Models\EstadoModel; diff --git a/ci4/app/Controllers/Test.php b/ci4/app/Controllers/Test.php index 42c01781..7e141456 100755 --- a/ci4/app/Controllers/Test.php +++ b/ci4/app/Controllers/Test.php @@ -14,7 +14,6 @@ use App\Models\Usuarios\GroupModel; use App\Models\Usuarios\PermisosModel; use App\Services\PresupuestoService; use CodeIgniter\Shield\Entities\User; -use App\Models\Sistema\SettingsModel; class Test extends BaseController @@ -31,11 +30,9 @@ class Test extends BaseController public function index() { - $clienteModel = model('App\Models\Clientes\ClienteModel'); - $datos = $clienteModel->getResumenPagos(1870); - echo '
'; - var_dump($datos); - echo ''; + $emailService = service('emailService'); + + return $emailService->send("Hola mundo", "Hola mundo", "imnavajas@coit.es"); } diff --git a/ci4/app/Helpers/go_common_helper.php b/ci4/app/Helpers/go_common_helper.php index 7adcc2be..8d249e1d 100755 --- a/ci4/app/Helpers/go_common_helper.php +++ b/ci4/app/Helpers/go_common_helper.php @@ -172,9 +172,6 @@ if (!function_exists('getSystemSettings')) { { // Get Settings $session = session(); - $settingsBase = new \App\Models\Sistema\SettingsModel(); - $settings = $settingsBase->asArray()->first() ?? []; - $session->set('settings', $settings); if (empty($session->get('lang'))) { $session->set('lang', 'es'); } diff --git a/ci4/app/Models/Clientes/ClienteModel.php b/ci4/app/Models/Clientes/ClienteModel.php index f2d19bbb..12df2831 100755 --- a/ci4/app/Models/Clientes/ClienteModel.php +++ b/ci4/app/Models/Clientes/ClienteModel.php @@ -573,10 +573,14 @@ class ClienteModel extends \App\Models\BaseModel $result['total_pedidos_finalizados'] = round(floatval(($data && $data[0]->total != null) ? $data[0]->total : 0), 2); + $result['pendiente_old_erp'] = + round(floatval($this->getTotalPendienteOldERP($cliente_id)), 2); + $result['total_pendiente'] = $result['total_facturas_sin_pagar'] + $result['total_pedidos_produccion'] - + $result['total_pedidos_finalizados']; + + $result['total_pedidos_finalizados'] + + $result['pendiente_old_erp']; $result['total_pendiente'] = round(floatval($result['total_pendiente']), 2); $result['limite_credito'] = $this->db->table('clientes') diff --git a/ci4/app/Models/Configuracion/PapelImpresionModel.php b/ci4/app/Models/Configuracion/PapelImpresionModel.php index 0ab2ac45..fc03ccae 100755 --- a/ci4/app/Models/Configuracion/PapelImpresionModel.php +++ b/ci4/app/Models/Configuracion/PapelImpresionModel.php @@ -163,7 +163,6 @@ class PapelImpresionModel extends \App\Models\BaseModel $builder->join("lg_papel_generico t2", "t1.papel_generico_id = t2.id", "left"); $builder->where("t1.is_deleted", 0); - $builder->where("t1.isActivo", 1); if ($generico_id > 0) { $builder->where("t1.papel_generico_id", $generico_id); } diff --git a/ci4/app/Models/Sistema/SettingsModel.php b/ci4/app/Models/Sistema/SettingsModel.php deleted file mode 100644 index 32525a23..00000000 --- a/ci4/app/Models/Sistema/SettingsModel.php +++ /dev/null @@ -1,38 +0,0 @@ -first()->toArray(); - $gateway = $config['email_gateway']; + $settings_model = model('App\Models\Configuracion\ConfigVariableModel'); + $gateway = $settings_model->getVariable('email_protocol')->value; $body = html_entity_decode($body); if ($gateway === 'smtp') { @@ -28,12 +25,12 @@ class EmailService $email = Services::email(); $emailConfig = [ - 'protocol' => $config['email_gateway'], - 'SMTPHost' => $config['email_smtp'], - 'SMTPUser' => $config['email_address'], - 'SMTPPass' => $config['email_pass'], - 'SMTPPort' => (int) $config['email_port'], - 'SMTPCrypto' => $config['email_cert'] === 'none' ? '' : $config['email_cert'], + 'protocol' => $gateway, + 'SMTPHost' => $settings_model->getVariable('email_host')->value, + 'SMTPUser' => $settings_model->getVariable('email_from_address')->value, + 'SMTPPass' => $settings_model->getVariable('email_pass')->value, + 'SMTPPort' => (int) $settings_model->getVariable('email_port')->value, + 'SMTPCrypto' => $settings_model->getVariable('email_cert')->value === 'none' ? '' : $settings_model->getVariable('email_cert')->value, 'SMTPTimeout' => 15, 'mailType' => 'html', 'wordWrap' => true, @@ -41,7 +38,7 @@ class EmailService $email->initialize($emailConfig); - $email->setFrom($config['email_address'], $config['email_name']); + $email->setFrom($settings_model->getVariable('email_from_address')->value, $settings_model->getVariable('email_from_name')->value); $email->setTo($recipient); $email->setSubject($subject); $email->setMessage($body); diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenCreditoItems.php b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenCreditoItems.php index 7eedc88d..bd6dc670 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenCreditoItems.php +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenCreditoItems.php @@ -62,6 +62,14 @@ +