From da379a7af966a6b229a5110605106cf5bf795a54 Mon Sep 17 00:00:00 2001 From: amazuecos Date: Wed, 28 Aug 2024 22:28:34 +0200 Subject: [PATCH] ftp service --- ci4/app/Config/FTP.php | 58 +++ ci4/app/Config/Services.php | 8 + ci4/app/Controllers/Pedidos/Pedido.php | 1 - ci4/app/Helpers/general_helper.php | 683 ------------------------- ci4/app/Services/FTPService.php | 48 ++ ci4/app/Services/PedidoXMLService.php | 8 + 6 files changed, 122 insertions(+), 684 deletions(-) create mode 100644 ci4/app/Config/FTP.php delete mode 100755 ci4/app/Helpers/general_helper.php create mode 100644 ci4/app/Services/FTPService.php diff --git a/ci4/app/Config/FTP.php b/ci4/app/Config/FTP.php new file mode 100644 index 00000000..f3faf0a0 --- /dev/null +++ b/ci4/app/Config/FTP.php @@ -0,0 +1,58 @@ + "sk-ftp", + "user" => "admin", + "password" => "A77h3b0X4OA2rOYAf4w2", + "base_dir" => "/home/admin/safekat" # FTP server directory + ]; + /** + * This database connection is used when + * running PHPUnit database tests. + */ + public array $production = [ + "host" => "sk-ftp", + "user" => "admin", + "password" => "A77h3b0X4OA2rOYAf4w2", + "base_dir" => "/home/admin/safekat" # FTP server directory + ]; + /** + * This database connection is used when + * running PHPUnit database tests. + */ + public array $development = [ + "host" => "sk-ftp", + "port" => "21000", + "user" => "admin", + "password" => "A77h3b0X4OA2rOYAf4w2", + "base_dir" => "/home/admin/safekat" # FTP server directory + + ]; + + public function __construct() + { + parent::__construct(); + + // Ensure that we always set the database group to 'tests' if + // we are currently running an automated test suite, so that + // we don't overwrite live data on accident. + if (ENVIRONMENT === 'development') { + $this->defaultGroup = 'development'; + } + } +} diff --git a/ci4/app/Config/Services.php b/ci4/app/Config/Services.php index df7c8ad0..572aec46 100755 --- a/ci4/app/Config/Services.php +++ b/ci4/app/Config/Services.php @@ -2,6 +2,7 @@ namespace Config; +use App\Services\FTPService; use CodeIgniter\Config\BaseService; /** @@ -29,4 +30,11 @@ class Services extends BaseService * return new \CodeIgniter\Example(); * } */ + public static function ftp(bool $getShared = true): FTPService + { + if ($getShared) { + return static::getSharedInstance('ftp'); + } + return new FTPService(); + } } diff --git a/ci4/app/Controllers/Pedidos/Pedido.php b/ci4/app/Controllers/Pedidos/Pedido.php index af2dbfc7..6ff1ca79 100755 --- a/ci4/app/Controllers/Pedidos/Pedido.php +++ b/ci4/app/Controllers/Pedidos/Pedido.php @@ -328,7 +328,6 @@ class Pedido extends \App\Controllers\BaseResourceController } public function get_xml_pedido($pedido_id) { - $data = PedidoXMLService::generate_xml($pedido_id); // $xml_service = new PedidoXMLService($this->model); return $this->respond($data); diff --git a/ci4/app/Helpers/general_helper.php b/ci4/app/Helpers/general_helper.php deleted file mode 100755 index e0578134..00000000 --- a/ci4/app/Helpers/general_helper.php +++ /dev/null @@ -1,683 +0,0 @@ -$value){ - if($key==$section){ - foreach($value as $item){ - if($item==$method){ - return true; - } - } - } - } - return false; - - /*var_dump($key. ' '. $value[0]); - - echo '
';
-        $rules = 
-        echo '
'; - dd();*/ -} - -function getAllClass($controller = null){ - try { - helper('filesystem'); - helper('directory'); - if(strtolower(PHP_OS) == 'linux'){ - $compatibility = '/'; - }else{ - $compatibility = '\\'; - } - if(empty($controller)){ - $map = directory_map(APPPATH.'Controllers'); - foreach ($map as $key=>$item) - { - if(!strpos(strtolower($key),$compatibility)){ - $name = str_replace('.php', '', $item); - if(!getIgnoreController($name)){ - $controllers[] = [ - 'name' => $name, - 'path' => '', - 'methods' => get_class_methods('App\Controllers\\'.$name) - ]; - } - }else{ - foreach ($item as $subitem){ - $name = str_replace('.php', '', $subitem); - if(!getIgnoreController($name)) { - $controllers[] = [ - 'name' => $name, - 'path' => $key, - 'methods' => get_class_methods('App\Controllers\\' . str_replace('/', '\\', $key) . $name) - ]; - } - } - } - } - }else{ - $array = explode('/',$controller); - $dir = count($array) > 1 ? $array[0] : ''; - $name = count($array) > 1 ? '\\'.$array[1] : $array[0]; - $controllers[] = [ - 'name' => $name, - 'path' => $dir, - 'methods' => get_class_methods('App\Controllers\\'.str_replace('/','\\',$dir).$name) - ]; - } - return $controllers??[]; - } catch (Exception $e) { - return []; - } -} - - -// IMN -function getCurrentLanguageFlag(){ - try { - $session = session(); - - if($session->get('lang') == 'en'){ - return "fi-gb"; - }else{ - return "fi-es"; - } - } catch (Exception $e) { - return "fi-es"; - } -} - - -function getAllClassFolder($folder = null){ - try { - helper('filesystem'); - helper('directory'); - - if(!empty($folder)){ - $map = directory_map(APPPATH.'Controllers'); - foreach ($map as $key=>$item) - { - if(strtolower(PHP_OS) == 'linux'){ - $compatibility = '/'; - }else{ - $compatibility = '\\'; - } - if(str_replace($compatibility,'',strtolower($key)) == strtolower($folder)){ - foreach ($item as $subitem){ - $name = str_replace('.php', '', $subitem); - $controllers[] = [ - 'name' => $name, - 'path' => $key, - 'methods' => get_class_methods('App\Controllers\\'.str_replace('/','\\',$key).$name) - ]; - } - } - } - } - return $controllers??[]; - } catch (Exception $e) { - return []; - } -} - -function getAllFolder(){ - try { - helper('filesystem'); - helper('directory'); - $map = directory_map(APPPATH.'Controllers',1); - if(strtolower(PHP_OS) == 'linux'){ - $compatibility = '/'; - }else{ - $compatibility = '\\'; - } - foreach ($map as $item) { - if(strpos(strtolower($item),$compatibility)){ - $folders[] = str_replace($compatibility,"",$item); - } - } - return $folders??[]; - } catch (Exception $e) { - return []; - } -} - - - -function getIgnoreController($controller) -{ - try { - $loginAuthFilter = new \App\Filters\LoginAuthFilter(); - foreach ($loginAuthFilter->whiteListController() as $item){ - if($controller == $item){ - return true; - } - } - return false; - } catch (Exception $e) { - return []; - } -} - -function getIgnoreMethod($method) -{ - try { - $loginAuthFilter = new \App\Filters\LoginAuthFilter(); - foreach ($loginAuthFilter->whiteListMethod() as $item){ - if($method == $item){ - return true; - } - } - return false; - } catch (Exception $e) { - return []; - } -} - -function getDictionary($word=''){ - try { - $dictionary = [ - 'index' => lang("App.permisos_index"), - 'view' => lang("App.permisos_view"), - 'add' => lang("App.permisos_add"), - 'edit' => lang("App.permisos_editar"), - 'delete' => lang("App.permisos_del"), - 'store' => lang("App.permisos_save"), - 'import' => lang("App.permisos_import"), - 'export' => lang("App.permisos_export"), - - 'Profile' => lang("App.permisos_perfil"), - 'Activity' => lang("App.permisos_actividad"), - 'Settings' => lang("App.permisos_configuracion"), - 'my' => lang("App.permisos_my"), - 'Notification' => lang("App.permisos_notificacion"), - - 'Users' => lang("App.permisos_usuarios"), - 'User' => lang("App.permisos_usuario"), - 'Group' => lang("App.permisos_roles"), - - 'Logistica' => lang("App.permisos_logistica"), - - 'Tarifas' => lang("App.permisos_tarifas"), - 'Tarifapreimpresion' => lang("App.permisos_tarifapreimpresion"), - 'Tarifamanipulado' => lang("App.permisos_tarifamanipulado"), - 'Tarifapapelcompra' => lang("App.permisos_tarifapapelcompra"), - 'Tarifaacabado' => lang("App.permisos_tarifaacabado"), - 'Tarifapapeldefecto' => lang("App.permisos_tarifapapeldefecto"), - 'Tarifaenvio' => lang("App.permisos_tarifaenvio"), - 'Tarifaimpresion' => lang("App.permisos_tarifaimpresion"), - - 'Configuracion' => lang("App.permisos_configuracion"), - 'Tareaservicio' => lang("App.permisos_tareasservicio"), - 'Formaspago' => lang("App.permisos_formaspago"), - 'Papelgenerico' => lang("App.permisos_papelgenerico"), - 'Tiposimpresion' => lang("App.permisos_tiposimpresion"), - 'Trabajo' => lang("App.permisos_trabajo"), - 'Maquina' => lang("App.permisos_maquina"), - 'Tamaniolibros' => lang("App.permisos_tamaniolibros"), - 'Imposiciones' => lang("App.permisos_imposiciones"), - 'Seriefactura' => lang("App.permisos_seriefactura"), - 'Tamanioformatos' => lang("App.permisos_tamanioformatos"), - 'Serviciocliente' => lang("App.permisos_serviciocliente"), - 'Calendario' => lang("App.permisos_calendario"), - 'Correo' => lang("App.permisos_correo"), - 'Paises' => lang("App.permisos_paises"), - 'Tipologias' => lang("App.permisos_tipologias"), - - 'Presupuestos' => lang("App.permisos_presupuestos"), - 'Presupuesto' => lang("App.permisos_presupuestos"), - 'Presupuestomaquetacion' => lang("App.permisos_presupuestomaquetacion"), - - 'Catalogo' => lang("App.permisos_catalogo"), - - 'Cliente' => lang("App.permisos_clientes"), - 'Tarifacliente' => lang("App.permisos_tarifacliente"), - - 'Proveedores' => lang("App.permisos_proveedores"), - 'Proveedor' => lang("App.permisos_proveedores"), - - 'Informes' => lang("App.permisos_informes"), - 'Informe' => lang("App.permisos_informes"), - - 'Facturacion' => lang("App.permisos_facturación"), - 'Albaran' => lang("App.permisos_albaran"), - 'Factura' => lang("App.permisos_facturas"), - - 'Pedidos' => lang("App.permisos_pedidos"), - 'Pedido' => lang("App.permisos_pedidos"), - - 'Serviciosdigitalizacion' => lang("App.permisos_digitalización"), - 'Digitalizacion' => lang("App.permisos_digitalización"), - - 'Produccion' => lang("App.permisos_produccion"), - 'Ordentrabajomaquetacion' => lang("App.permisos_ordentrabajomaquetacion"), - 'Ordenmaquina' => lang("App.permisos_ordenmaquina"), - 'Pedidoproduccion' => lang("App.permisos_pedidoproduccion"), - 'Ordentrabajo' => lang("App.permisos_ordentrabajo"), - - 'oauth' => lang("App.group_rules_label_oauth"), - 'template' => lang("App.group_rules_label_template"), - 'all' => lang("App.group_rules_label_all"), - 'oauth_store' => lang("App.group_rules_label_oauth_store"), - 'template_store' => lang("App.group_rules_label_template_store"), - - ]; - return array_key_exists($word,$dictionary)?$dictionary[$word] : $word; - } catch (Exception $e) { - return ''; - } -} - -function getMenuControl(){ - try { - $getClass = getAllClass(); - $getRules = json_decode(session()->get('rules')??'[]'); - foreach ($getClass as $item){ - foreach ($getRules as $key=>$value){ - if($key == $item['name']){ - $item['methods'] = $value; - $data[] = $item; - } - } - } - return $data??[]; - } catch (Exception $e) { - session()->setFlashdata('alert', 'error_acesso'); - return []; - } -} - -function allowMenuSection(array $array, array $keys, $method){ - try{ - $value = false; - foreach($keys as $key){ - if (count($temp=getArrayItem($array,'name',$key)) > 0){ - if (count(getArrayItem($temp,'methods','index',true)) > 0){ - $value = true; - } - } - } - return $value; - - } catch (Exception $e) { - return []; - } -} - -function getArrayItem(array $array, $key, $word, $isArray=false) -{ - try { - foreach ($array as $item){ - if ($isArray){ - foreach ($item[$key] as $subitem){ - if($subitem == $word){ - $data[]=$subitem; - } - } - }else{ - if($item[$key] == $word){ - $data[]=$item; - } - } - } - return $data??[]; - } catch (Exception $e) { - return []; - } -} - -//////////////////////////////////////////////////// -/// Notification Messages -//////////////////////////////////////////////////// - -function formAlert() -{ - $session = session(); - $alert = $session->getFlashdata('error'); - $validation = \Config\Services::validation()->listErrors(); - if (!empty($alert)){ - return '
'. - ' '. $validation . - '
'; - } -} - -function sweetAlert() -{ - try { - $session = session(); - $alert = $session->getFlashdata('sweet'); - if (count((array)$alert) == 2){ - return ""; - } - if (count((array)$alert) == 4){ - return ""; - } - }catch (Exception $ex){ - } -} - -function toastAlert() -{ - try { - $session = session(); - $alert = $session->getFlashdata('toast'); - if (count((array)$alert) == 3) { - return ""; - } - }catch (Exception $ex){ - } -} - -//////////////////////////////////////////////////// -/// Security -//////////////////////////////////////////////////// - -function generatePassword($length = 8) { - $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_!@#$%&*()-+{[]}'; - $count = mb_strlen($chars); - for ($i = 0, $result = ''; $i < $length; $i++) { - $index = Rand(0, $count - 1); - $result .= mb_substr($chars, $index, 1); - } - return $result; -} - -//////////////////////////////////////////////////// -/// Others -//////////////////////////////////////////////////// - -function now_db() { - $unixdatetime = time(); - return strftime("%Y-%m-%d %H:%M:%S", $unixdatetime); -} - -function escape_value($value='') { - $value = strip_tags(htmlentities($value)); - return filter_var($value, FILTER_SANITIZE_STRING); -} - -function escape_only($value='') { - $value = strip_tags(htmlentities($value), '

'); - return filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS); -} - -function unescape($value='') { - //return html_entity_decode($value,null,'UTF-8');; - return html_entity_decode($value,ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,'UTF-8'); -} - -function redirect_to( $location = NULL ) { - if ($location != NULL) { - header("Location: {$location}"); - exit; - } -} - -function momentDateJS() { - $format = session()->get('settings')['default_date_format']; - switch ($format) { - case "Y-m-d": - return "YYYY-MM-DD"; - case "d-m-Y": - return "DD-MM-YYYY"; - case "d/m/Y": - return "DD/MM/YYYY"; - case "m-d-Y": - return "MM-DD-YYYY"; - case "m/d/Y": - return "MM/DD/YYYY"; - default: - return ""; - } -} - -function momentDateTimeJS() { - $format = session()->get('settings')['default_date_format']; - switch ($format) { - case "Y-m-d": - return "YYYY-MM-DD HH:mm:ss"; - case "d-m-Y": - return "DD-MM-YYYY HH:mm:ss"; - case "d/m/Y": - return "DD/MM/YYYY HH:mm:ss"; - case "m-d-Y": - return "MM-DD-YYYY HH:mm:ss"; - case "m/d/Y": - return "MM/DD/YYYY HH:mm:ss"; - default: - return ""; - } -} - -function dateFormatWeb($date) { - $format = session()->get('settings')['default_date_format']; - switch ($format) { - case "Y-m-d": - return $date; - case "d-m-Y": - case "d/m/Y": - case "m-d-Y": - case "m/d/Y": - $phpDate = strtotime($date); - if(strlen($date) > 10){ - return date( $format.' H:i:s', $phpDate); - }else{ - return date( $format, $phpDate); - } - default: - return null; - } -} - -function dateFormatMysql($date) { - $format = session()->get('settings')['default_date_format']; - switch ($format) { - case "Y-m-d": - return $date; - case "d-m-Y": - $dateTimeSplit = explode(' ',$date); - $dateSplit = explode('-',$dateTimeSplit[0]); - if(count($dateTimeSplit) > 1){ - return $dateSplit[2].'-'.$dateSplit[1].'-'.$dateSplit[0].' '. $dateTimeSplit[1]; - }else{ - return $dateSplit[2].'-'.$dateSplit[1].'-'.$dateSplit[0]; - } - case "d/m/Y": - $dateTimeSplit = explode(' ',$date); - $dateSplit = explode('/',$dateTimeSplit[0]); - if(count($dateTimeSplit) > 1){ - return $dateSplit[2].'-'.$dateSplit[1].'-'.$dateSplit[0].' '. $dateTimeSplit[1]; - }else{ - return $dateSplit[2].'-'.$dateSplit[1].'-'.$dateSplit[0]; - } - case "m-d-Y": - $dateTimeSplit = explode(' ',$date); - $dateSplit = explode('-',$dateTimeSplit[0]); - if(count($dateTimeSplit) > 1){ - return $dateSplit[2].'-'.$dateSplit[0].'-'.$dateSplit[1].' '. $dateTimeSplit[1]; - }else{ - return $dateSplit[2].'-'.$dateSplit[0].'-'.$dateSplit[1]; - } - case "m/d/Y": - $dateTimeSplit = explode(' ',$date); - $dateSplit = explode('/',$dateTimeSplit[0]); - if(count($dateTimeSplit) > 1){ - return $dateSplit[2].'-'.$dateSplit[0].'-'.$dateSplit[1].' '. $dateTimeSplit[1]; - }else { - return $dateSplit[2] . '-' . $dateSplit[0] . '-' . $dateSplit[1]; - } - default: - return null; - } -} - -function langJS() { - $lang = session()->get('lang')??'en'; - switch ($lang) { - case "pt": - return "pt-br"; - default: - return $lang; - } -} - -function socialBG() { - return [ - "facebook" => "bg-facebook", - "linkedin" => "bg-linkedin", - "google" => "bg-google-plus", - "youtube" => "bg-youtube", - "twitter" => "bg-twitter", - "instagram" => "bg-instagram", - "tiktok" => "bg-tiktok", - "whatsapp" => "bg-whatsapp", - "website" => "bg-website", - "api" => "bg-api", - "github" => "bg-github", - "slack" => "bg-slack", - "spotify" => "btn-spotify", - "reddit" => "btn-reddit", - "discord" => "btn-discord", - "dribbble" => "btn-dribbble", - "dropbox" => "btn-dropbox", - "gitlab" => "btn-gitlab", - "tumblr" => "btn-tumblr", - "strava" => "btn-strava", - "twitch" => "btn-twitch", - "vkontakte" => "btn-vk", - "wordpress" => "btn-wordpress", - "yahoo" => "btn-yahoo", - "bitbucket" => "btn-bitbucket", - "wechat" => "btn-wechat", - ]; -} -function keywordEmail() { - return [ - 'user_first_name', - 'user_last_name', - 'user_date_birth', - 'user_address', - 'user_city', - 'user_state', - 'user_country', - 'user_zip_code', - 'user_mobile', - 'user_email', - 'user_picture' - ]; -} - -function templateSelect($templates=[],$name='',$type='') { - foreach ($templates as $item){ - if($item['type'] == $type){ - if($item['name'] == $name){ - return $item; - } - } - } - return null; -} - -function get_filter_datatables_columns($request){ - $columnSearch = array(); - - if ( isset( $request['columns'] ) ) { - for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) { - $requestColumn = $request['columns'][$i]; - - $str = $requestColumn['search']['value']; - - if ( $requestColumn['searchable'] == 'true' && - $str != '' ) { - array_push($columnSearch, [$i, $requestColumn['data'], $str]); - } - } - } - - return $columnSearch; -} - -// Devuelve true si los intervalos (a1,a2) (b1,b2) se solapan -// https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-if-two-ranges-overlap -function check_overlap($a1, $a2, $b1, $b2){ - - if (max($a2, $b2) - min($a1, $b1) <= ($a2 - $a1) + ($b2 - $b1)) - return true; - return false; -} - -function check_overlap_with_extremos($a1, $a2, $b1, $b2){ - - if (max($a2, $b2) - min($a1, $b1) < ($a2 - $a1) + ($b2 - $b1)) - return true; - return false; -} - -function version() { - return "1.2.1"; -} \ No newline at end of file diff --git a/ci4/app/Services/FTPService.php b/ci4/app/Services/FTPService.php new file mode 100644 index 00000000..fa4650cc --- /dev/null +++ b/ci4/app/Services/FTPService.php @@ -0,0 +1,48 @@ +ftp = new FtpClient(); + $this->ftp_config = config("FTP"); + $this->host = $this->ftp_config->host; + $this->username = $this->ftp_config->username; + $this->password = $this->ftp_config->password; + $this->base_dir = $this->ftp_config->base_dir; + } + /** + * Upload the content of $filename to the base directory declared in App\Config\FTP.php + * + * @param string $content + * @param string $filename + * @return boolean + */ + public function uploadXML(string $content, string $filename): bool + { + try { + $remotePath = implode("/", [$this->base_dir, $filename]); + $this->ftp->connect(host: $this->host, port: $this->port); + $this->ftp->login(username: $this->username, password: $this->password); + $this->ftp->putFromString($remotePath, $content); + return true; + } catch (\Throwable $th) { + log_message('error',$th->getMessage()); + return false; + } + } +} diff --git a/ci4/app/Services/PedidoXMLService.php b/ci4/app/Services/PedidoXMLService.php index b09edaa1..3ece7f7c 100644 --- a/ci4/app/Services/PedidoXMLService.php +++ b/ci4/app/Services/PedidoXMLService.php @@ -9,6 +9,7 @@ use App\Models\Pedidos\PedidoLineaModel; use App\Models\Presupuestos\PresupuestoModel; use DOMDocument; use DOMNode; +use FTP; class PedidoXMLService extends BaseService { @@ -168,8 +169,15 @@ class PedidoXMLService extends BaseService $xml_products_el->appendChild($xml->createElement('CommentsClient', $data["pedido_cliente_presupuesto"]->comentarios_cliente)); $xml->appendChild($xml_products_el); $file_has_suffix = hash('sha512',$data["pedido_cliente_presupuesto"]->pedidoId); + $file_name = PedidoXMLService::generate_xml_file_name($file_has_suffix); + $ftp = service('FTPService'); + $ftp->uploadXML($xml->textContent,$file_name); return $data; } + protected static function generate_xml_file_name(string $hash) : string + { + return implode("",["Safekat_",$hash,".xml"]); + } protected static function get_color_interior($pre_linea): ?string { $color_interior = null;