From 95f8519d5d3cab5b34e92b362b1820eb7f293575 Mon Sep 17 00:00:00 2001 From: Daniel Maya Date: Mon, 22 Jan 2024 17:22:23 +0100 Subject: [PATCH 01/24] #12687 Added import/export prd --- pandora_console/godmode/menu.php | 3 + .../resources/resources_export_import.php | 160 ++++++++++ .../include/ajax/resources.ajax.php | 74 +++++ pandora_console/include/class/Prd.class.php | 281 ++++++++++++++++++ 4 files changed, 518 insertions(+) create mode 100644 pandora_console/godmode/resources/resources_export_import.php create mode 100644 pandora_console/include/ajax/resources.ajax.php create mode 100644 pandora_console/include/class/Prd.class.php diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index a77e63b95b..4f116502e3 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -208,6 +208,9 @@ if ($access_console_node === true) { $sub['godmode/setup/os']['text'] = __('Operating systems'); $sub['godmode/setup/os']['id'] = 'edit_OS'; + + $sub['godmode/resources/resources_export_import']['text'] = __('Resources export/import'); + $sub['godmode/resources/resources_export_import']['id'] = 'resources_export_import'; } if ((bool) check_acl($config['id_user'], 0, 'AW') === true) { diff --git a/pandora_console/godmode/resources/resources_export_import.php b/pandora_console/godmode/resources/resources_export_import.php new file mode 100644 index 0000000000..569c854278 --- /dev/null +++ b/pandora_console/godmode/resources/resources_export_import.php @@ -0,0 +1,160 @@ +id = 'import_data_table'; +$table->class = 'databox filter-table-adv'; +$table->width = '100%'; +$table->data = []; +$table->style = []; +$table->size = []; + +$table->data[0][0] = html_print_label_input_block( + __('Resource importation'), + html_print_input_file('resource_import', true) +); + +$table->data[0][1] = html_print_label_input_block( + __('Group filter'), + html_print_select_groups(false, 'AW', true, 'group', '', '', __('All'), 0, true) +); + +html_print_table($table); + +$table = new stdClass(); +$table->id = 'export_data_table'; +$table->class = 'databox filter-table-adv'; +$table->width = '100%'; +$table->data = []; +$table->style = []; +$table->size = []; +$table->size[0] = '50%'; +$table->size[1] = '50%'; + +// Instance of the prd class. +$prd = new Prd(); + +$export_type = $prd->getTypesPrd(); + +$table->data[0][0] = html_print_label_input_block( + __('Export type'), + html_print_select( + $export_type, + 'export_type', + '', + '', + __('None'), + 0, + true, + false, + true, + 'w40p' + ) +); + +$table->data[1][0] = ''; + +$table->data[2][0] = html_print_button( + __('Export'), + 'export_button', + false, + '', + ['class' => 'flex_justify invisible_important'], + true +); + +html_print_table($table); + +?> + \ No newline at end of file diff --git a/pandora_console/include/ajax/resources.ajax.php b/pandora_console/include/ajax/resources.ajax.php new file mode 100644 index 0000000000..5c6c8ed02d --- /dev/null +++ b/pandora_console/include/ajax/resources.ajax.php @@ -0,0 +1,74 @@ +getOnePrdData($type); + if (empty($check) === false) { + switch ($type) { + case 'visual_console': + $result = html_print_label_input_block( + __('Visual console'), + io_safe_output( + html_print_select_from_sql( + 'SELECT id, name FROM tlayout', + 'select_value', + '', + '', + '', + 0, + true, + false, + true, + false, + false, + false, + GENERIC_SIZE_TEXT, + 'w40p', + ), + ) + ); + break; + + default: + // TODO. + break; + } + } + + echo $result; + return; + } + + if ($exportPrd === true) { + $type = (string) get_parameter('type', ''); + $value = (int) get_parameter('value', 0); + $name = (string) get_parameter('name', ''); + + $prd->exportPrd($type, $value, $name); + } +} diff --git a/pandora_console/include/class/Prd.class.php b/pandora_console/include/class/Prd.class.php new file mode 100644 index 0000000000..faf4a13c28 --- /dev/null +++ b/pandora_console/include/class/Prd.class.php @@ -0,0 +1,281 @@ +prdData = [ + 'visual_console' => [ + 'label' => __('Visual console'), + 'items' => [ + 'table' => 'tlayout', + 'value' => 'id', + 'show' => 'name', + ], + 'data' => [ + [ + 'table' => 'tlayout', + 'ref' => 'id', + ], + [ + 'table' => 'tlayout_data', + 'ref' => 'id_layout', + ], + ], + ], + ]; + + $this->columnRefs = [ + 'tlayout_data' => [ + 'id_agent' => [ + 'table' => 'tagente', + 'id' => 'id_agente', + 'column' => 'nombre', + ], + 'id_agente_modulo' => [ + 'table' => 'tagente_modulo', + 'id' => 'id_agente_modulo', + 'column' => 'nombre', + 'join' => [ + 'id_agente' => [ + 'table' => 'tagente', + 'id' => 'id_agente', + 'column' => 'nombre', + ], + ], + ], + ], + ]; + + $this->jsonRefs = [ + 'twidget_dashboard' => [ + 'options' => [ + 'agent' => [ + 'array' => false, + 'table' => 'tagente', + 'id' => 'id_agente', + 'column' => 'nombre', + ], + 'module' => [ + 'array' => false, + 'table' => 'tagente_modulo', + 'id' => 'id_agente_modulo', + 'column' => 'nombre', + 'join' => [ + 'id_agente' => [ + 'table' => 'tagente', + 'id' => 'id_agente', + 'column' => 'nombre', + ], + ], + ], + ], + ], + ]; + + $this->message = ''; + } + + + /** + * Generates a JSON error. + * + * @param string $msg Error message. + * + * @return void + */ + public function error(string $msg) + { + echo json_encode( + ['error' => $msg] + ); + } + + + /** + * Get $prdData. + * + * @return array + */ + public function getPrdData(): array + { + return $this->prdData; + } + + + /** + * Get one $prdData. + * + * @param string $item Item to be searched in array. + * + * @return boolean|array + */ + public function getOnePrdData(string $item): bool|array + { + if (isset($this->prdData[$item]) === false) { + return false; + } + + return $this->prdData[$item]; + } + + + /** + * Get $columnRefs. + * + * @return array + */ + public function getColumnRefs(): array + { + return $this->columnRefs; + } + + + /** + * Get one $columnRefs. + * + * @param string $item Item to be searched in array. + * + * @return boolean|array + */ + public function getOneColumnRefs(string $item): bool|array + { + if (isset($this->columnRefs[$item]) === false) { + return false; + } + + return $this->columnRefs[$item]; + } + + + /** + * Get $jsonRefs. + * + * @return array + */ + public function getJsonRefs(): array + { + return $this->jsonRefs; + } + + + /** + * Get types of prd. + * + * @return array + */ + public function getTypesPrd(): array + { + $result = []; + foreach ($this->prdData as $key => $value) { + $result[$key] = $value['label']; + } + + return $result; + } + + + /** + * Export prd. + * + * @return array + */ + public function exportPrd(string $type, $value, $name) :array + { + $result = []; + + $prd_data = $this->getOnePrdData($type); + if (empty($prd_data) === false) { + $result['prd_data'] = [ + 'type' => $type, + 'name' => $name, + ]; + + foreach ($prd_data['data'] as $key => $element) { + $sql = sprintf( + 'SELECT * FROM %s WHERE %s = %s', + $element['table'], + $element['ref'], + $value, + ); + + $test = db_get_all_rows_sql($sql); + + // $result[$element['table']] + // hd($test, true); + } + } + + return $result; + + } + + +} From 401b1973bed7bde5e06a680d2d1973f1bb4184d4 Mon Sep 17 00:00:00 2001 From: Daniel Maya Date: Wed, 24 Jan 2024 12:15:16 +0100 Subject: [PATCH 02/24] #12687 Added import/export prd 2 --- .../resources/resources_export_import.php | 28 +- .../include/ajax/resources.ajax.php | 94 ++++-- pandora_console/include/class/Prd.class.php | 318 ++++++++++++++++-- pandora_console/include/constants.php | 3 + 4 files changed, 381 insertions(+), 62 deletions(-) diff --git a/pandora_console/godmode/resources/resources_export_import.php b/pandora_console/godmode/resources/resources_export_import.php index 569c854278..146784f2e4 100644 --- a/pandora_console/godmode/resources/resources_export_import.php +++ b/pandora_console/godmode/resources/resources_export_import.php @@ -114,6 +114,7 @@ html_print_table($table); $("#button-export_button").addClass("invisible_important"); $("#export_data_table-1-0").html(''); } else { + $("#export_data_table-1-0").html(''); $.ajax({ type: "GET", url: "ajax.php", @@ -137,10 +138,18 @@ html_print_table($table); $("#button-export_button").click(function(e) { const value = $("#select_value").val(); if (value !== '0') { + //Show dialog. + confirmDialog({ + title: "", + message: "", + hideCancelButton: true + }, + "downloadDialog" + ); + $.ajax({ type: "GET", url: "ajax.php", - dataType: "html", data: { page: 'include/ajax/resources.ajax', exportPrd: 1, @@ -149,7 +158,24 @@ html_print_table($table); name: $("#select_value").text(), }, success: function(data) { + let a = document.createElement('a'); + const url = '' + data; + a.href = url; + a.download = data; + a.click(); + setTimeout(() => { + $.ajax({ + type: "DELETE", + url: "ajax.php", + data: { + page: 'include/ajax/resources.ajax', + deleteFile: 1, + filename: data, + }, + }); + $("#confirm_downloadDialog").dialog("close"); + }, 3000); }, error: function(data) { console.error("Fatal error in AJAX call to interpreter order", data) diff --git a/pandora_console/include/ajax/resources.ajax.php b/pandora_console/include/ajax/resources.ajax.php index 5c6c8ed02d..379a499407 100644 --- a/pandora_console/include/ajax/resources.ajax.php +++ b/pandora_console/include/ajax/resources.ajax.php @@ -20,6 +20,7 @@ if ((bool) is_ajax() === true) { $getResource = (bool) get_parameter('getResource', false); $exportPrd = (bool) get_parameter('exportPrd', false); + $deleteFile = (bool) get_parameter('deleteFile', false); $prd = new Prd(); @@ -27,37 +28,34 @@ if ((bool) is_ajax() === true) { $type = (string) get_parameter('type', ''); $result = false; - $check = $prd->getOnePrdData($type); - if (empty($check) === false) { - switch ($type) { - case 'visual_console': - $result = html_print_label_input_block( - __('Visual console'), - io_safe_output( - html_print_select_from_sql( - 'SELECT id, name FROM tlayout', - 'select_value', - '', - '', - '', - 0, - true, - false, - true, - false, - false, - false, - GENERIC_SIZE_TEXT, - 'w40p', - ), - ) - ); - break; - - default: - // TODO. - break; - } + $data = $prd->getOnePrdData($type); + if (empty($data) === false) { + $sql = sprintf( + 'SELECT %s FROM %s', + reset($data['items']['value']).', '.reset($data['items']['show']), + $data['items']['table'] + ); + $result = html_print_label_input_block( + $data['label'], + io_safe_output( + html_print_select_from_sql( + $sql, + 'select_value', + '', + '', + '', + 0, + true, + false, + true, + false, + false, + false, + GENERIC_SIZE_TEXT, + 'w40p', + ), + ) + ); } echo $result; @@ -69,6 +67,38 @@ if ((bool) is_ajax() === true) { $value = (int) get_parameter('value', 0); $name = (string) get_parameter('name', ''); - $prd->exportPrd($type, $value, $name); + $data = $prd->exportPrd($type, $value, $name); + + $return = ''; + + if (empty($data) === false) { + $filename = $type.'-'.date('Ymd').'-'.date('His').'.prd'; + $file = $config['attachment_store'].'/'.$filename; + + $file_pointer = fopen($file, 'a'); + if ($file_pointer !== false) { + $write = fwrite($file_pointer, $data); + + if ($write === false) { + $return = -2; + } else { + $return = $filename; + } + + fclose($file_pointer); + } else { + $return = -1; + } + } + + echo $return; + + return; + } + + if ($deleteFile === true) { + $filename = (string) get_parameter('filename', ''); + + unlink($config['attachment_store'].'/'.$filename); } } diff --git a/pandora_console/include/class/Prd.class.php b/pandora_console/include/class/Prd.class.php index faf4a13c28..c115b639a2 100644 --- a/pandora_console/include/class/Prd.class.php +++ b/pandora_console/include/class/Prd.class.php @@ -76,17 +76,219 @@ class Prd 'label' => __('Visual console'), 'items' => [ 'table' => 'tlayout', - 'value' => 'id', - 'show' => 'name', - ], - 'data' => [ - [ - 'table' => 'tlayout', - 'ref' => 'id', + 'value' => ['id'], + 'show' => ['name'], + 'data' => [ + [ + 'table' => 'tlayout_data', + 'ref' => ['id_layout'], + 'value' => ['id'], + ], ], - [ - 'table' => 'tlayout_data', - 'ref' => 'id_layout', + ], + ], + 'custom_report' => [ + 'label' => __('Custom report'), + 'items' => [ + 'table' => 'treport', + 'value' => ['id_report'], + 'show' => ['name'], + 'data' => [ + [ + 'table' => 'treport_content', + 'ref' => ['id_report'], + 'value' => ['id_rc'], + 'data' => [ + [ + 'table' => 'treport_content_item', + 'ref' => ['id_report_content'], + 'value' => ['id'], + ], + [ + 'table' => 'treport_content_sla_combined', + 'ref' => ['id_report_content'], + 'value' => ['id'], + ], + ], + ], + ], + ], + ], + 'policy' => [ + 'label' => __('Policy'), + 'items' => [ + 'table' => 'tpolicies', + 'value' => ['id'], + 'show' => ['name'], + 'data' => [ + [ + 'table' => 'tpolicy_agents', + 'ref' => ['id_policy'], + 'value' => ['id'], + ], + [ + 'table' => 'tpolicy_alerts', + 'ref' => ['id_policy'], + 'value' => ['id'], + 'data' => [ + [ + 'table' => 'tpolicy_alerts_actions', + 'ref' => ['id_policy_alert'], + 'value' => ['id'], + ], + ], + ], + [ + 'table' => 'tpolicy_collections', + 'ref' => ['id_policy'], + 'value' => ['id'], + ], + [ + 'table' => 'tpolicy_group_agents', + 'ref' => ['id_policy'], + 'value' => ['id'], + ], + [ + 'table' => 'tpolicy_groups', + 'ref' => ['id_policy'], + 'value' => ['id'], + ], + [ + 'table' => 'tpolicy_modules', + 'ref' => ['id_policy'], + 'value' => ['id'], + 'data' => [ + [ + 'table' => 'ttag_policy_module', + 'ref' => ['id_policy_module'], + 'value' => [ + 'id_tag', + 'id_policy_module', + ], + ], + [ + 'table' => 'tpolicy_modules_synth', + 'ref' => ['id_agent_module_target'], + 'value' => ['id'], + ], + ], + ], + [ + 'table' => 'tpolicy_modules_inventory', + 'ref' => ['id_policy'], + 'value' => ['id'], + ], + [ + 'table' => 'tpolicy_plugins', + 'ref' => ['id_policy'], + 'value' => ['id'], + ], + ], + ], + ], + 'service' => [ + 'label' => __('Service'), + 'items' => [ + 'table' => 'tservice', + 'value' => ['id'], + 'show' => ['name'], + 'data' => [ + [ + 'table' => 'tservice_element', + 'ref' => ['id_service'], + 'value' => ['id'], + ], + ], + ], + ], + 'network_map' => [ + 'label' => __('Network map'), + 'items' => [ + 'table' => 'tmap', + 'value' => ['id'], + 'show' => ['name'], + 'data' => [ + [ + 'table' => 'titem', + 'ref' => ['id_map'], + 'value' => ['id'], + ], + [ + 'table' => 'trel_item', + 'ref' => ['id_map'], + 'value' => ['id'], + ], + ], + ], + ], + 'gis_map' => [ + 'label' => __('GIS map'), + 'items' => [ + 'table' => 'tgis_map', + 'value' => ['id_tgis_map'], + 'show' => ['map_name'], + 'data' => [ + [ + 'table' => 'tgis_map_layer', + 'ref' => ['tgis_map_id_tgis_map'], + 'value' => ['id_tmap_layer'], + 'data' => [ + [ + 'table' => 'tgis_map_layer_groups', + 'ref' => ['layer_id'], + 'value' => [ + 'layer_id', + 'group_id', + ], + ], + [ + 'table' => 'tgis_map_layer_has_tagente', + 'ref' => ['tgis_map_layer_id_tmap_layer'], + 'value' => [ + 'tgis_map_layer_id_tmap_layer', + 'tagente_id_agente', + ], + ], + ], + ], + [ + 'table' => 'tgis_map_has_tgis_map_con', + 'ref' => ['tgis_map_id_tgis_map'], + 'value' => [ + 'tgis_map_id_tgis_map', + 'tgis_map_con_id_tmap_con', + ], + ], + ], + ], + ], + 'custom_graph' => [ + 'label' => __('Custom graph'), + 'items' => [ + 'table' => 'tgraph', + 'value' => ['id_graph'], + 'show' => ['name'], + 'data' => [ + [ + 'table' => 'tgraph_source', + 'ref' => ['id_graph'], + 'value' => ['id_gs'], + ], + ], + ], + ], + 'dashboard' => [ + 'label' => __('Dashboard'), + 'items' => [ + 'table' => 'tdashboard', + 'value' => ['id'], + 'show' => ['name'], + 'data' => [ + [ + 'table' => 'twidget_dashboard', + 'ref' => ['id_dashboard'], + 'value' => ['id'], + ], ], ], ], @@ -243,38 +445,96 @@ class Prd /** - * Export prd. + * Converts a resource into a string. * - * @return array + * @param string $type Item type. + * @param mixed $id Item value. + * @param string $name Item name. + * + * @return string */ - public function exportPrd(string $type, $value, $name) :array + public function exportPrd(string $type, mixed $id, string $name) :string { - $result = []; + $result = ''; $prd_data = $this->getOnePrdData($type); if (empty($prd_data) === false) { - $result['prd_data'] = [ - 'type' => $type, - 'name' => $name, - ]; + $result .= '[prd_data]'.LINE_BREAK.LINE_BREAK; + $result .= 'type="'.$type.'"'.LINE_BREAK; + $result .= 'name="'.$name.'"'.LINE_BREAK.LINE_BREAK; - foreach ($prd_data['data'] as $key => $element) { - $sql = sprintf( - 'SELECT * FROM %s WHERE %s = %s', - $element['table'], - $element['ref'], - $value, - ); + $result .= '['.$prd_data['items']['table'].']'.LINE_BREAK.LINE_BREAK; - $test = db_get_all_rows_sql($sql); + $sql = sprintf( + 'SELECT * FROM %s WHERE %s = %s', + $prd_data['items']['table'], + reset($prd_data['items']['value']), + $id, + ); - // $result[$element['table']] - // hd($test, true); + $row = db_get_row_sql($sql); + $primary_key = $row[reset($prd_data['items']['value'])]; + foreach ($row as $column => $value) { + $result .= $column.'['.$primary_key.']="'.$value.'"'.LINE_BREAK; + } + + $result .= LINE_BREAK; + + $result .= $this->recursiveExport($prd_data['items']['data'], $id); + } + + return $result; + } + + + /** + * Recursive function to traverse all data + * + * @param mixed $data Data. + * @param mixed $id Id value for search. + * + * @return string + */ + private function recursiveExport($data, $id): string + { + $result = ''; + + foreach ($data as $key => $element) { + $result .= '['.$element['table'].']'.LINE_BREAK.LINE_BREAK; + $sql = sprintf( + 'SELECT * FROM %s WHERE %s = %s', + $element['table'], + reset($element['ref']), + $id, + ); + + $rows = db_get_all_rows_sql($sql); + foreach ($rows as $row) { + if (count($element['value']) > 1) { + $primary_key = ''; + foreach ($element['value'] as $value) { + $primary_key .= $row[$value].'-'; + } + + $primary_key = substr($primary_key, 0, -1); + hd($primary_key, true); + } else { + $primary_key = $row[reset($element['value'])]; + } + + foreach ($row as $column => $value) { + $result .= $column.'['.$primary_key.']="'.$value.'"'.LINE_BREAK; + } + + $result .= LINE_BREAK; + } + + if (isset($element['data']) === true) { + $result .= $this->recursiveExport($element['data'], $primary_key); } } return $result; - } diff --git a/pandora_console/include/constants.php b/pandora_console/include/constants.php index b2ce8d88b4..422c2dcc95 100644 --- a/pandora_console/include/constants.php +++ b/pandora_console/include/constants.php @@ -906,3 +906,6 @@ define('DEMO_SERVICE', 6); define('DEMO_DASHBOARD', 7); define('DEMO_VISUAL_CONSOLE', 8); define('DEMO_PLUGIN', 9); + +// Export resources. +define('LINE_BREAK', "\n"); From e07d89883f1ba7d667c7370bf2228c80d8e75ee9 Mon Sep 17 00:00:00 2001 From: Daniel Maya Date: Mon, 29 Jan 2024 17:38:01 +0100 Subject: [PATCH 03/24] #12687 Added import/export prd 3 --- .../resources/resources_export_import.php | 36 +- pandora_console/include/class/Prd.class.php | 1278 ++++++++++++++++- 2 files changed, 1275 insertions(+), 39 deletions(-) diff --git a/pandora_console/godmode/resources/resources_export_import.php b/pandora_console/godmode/resources/resources_export_import.php index 146784f2e4..d1dcfc2123 100644 --- a/pandora_console/godmode/resources/resources_export_import.php +++ b/pandora_console/godmode/resources/resources_export_import.php @@ -43,6 +43,21 @@ if (check_acl($config['id_user'], 0, 'PM') === false) { require_once $config['homedir'].'/include/class/Prd.class.php'; +// Instance of the prd class. +$prd = new Prd(); + +$msg = ''; +if (isset($_FILES['resource_import']) === true) { + $data = parse_ini_file($_FILES['resource_import']['tmp_name'], true); + if ($data !== false) { + $msg[] = $prd->importPrd($data); + } else { + $msg[] = 'Esto es una prueba'; + } +} + +$msg = json_encode($msg); + $table = new stdClass(); $table->id = 'import_data_table'; $table->class = 'databox filter-table-adv'; @@ -56,12 +71,17 @@ $table->data[0][0] = html_print_label_input_block( html_print_input_file('resource_import', true) ); -$table->data[0][1] = html_print_label_input_block( - __('Group filter'), - html_print_select_groups(false, 'AW', true, 'group', '', '', __('All'), 0, true) +$table->data[0][0] .= html_print_submit_button( + __('Import resource'), + 'upload', + false, + [], + true ); +echo '
'; html_print_table($table); +echo '
'; $table = new stdClass(); $table->id = 'export_data_table'; @@ -73,9 +93,6 @@ $table->size = []; $table->size[0] = '50%'; $table->size[1] = '50%'; -// Instance of the prd class. -$prd = new Prd(); - $export_type = $prd->getTypesPrd(); $table->data[0][0] = html_print_label_input_block( @@ -109,6 +126,12 @@ html_print_table($table); ?> - $name) { - $values['id_report'] = $id; - $result = (bool) db_process_sql_insert('treport_content', $values); - - ui_print_result_message( - $result, - sprintf( - __("Success add '%s' item in report '%s'."), - $values['type'], - $name - ), - sprintf( - __("Error create '%s' item in report '%s'."), - $values['type'], - $name - ) - ); - } -} - - -function process_upload_xml_report($xml, $group_filter=0) -{ - foreach ($xml->xpath('/report') as $reportElement) { - $values = []; - - if (isset($reportElement->name)) { - $values['name'] = $reportElement->name; - - $posible_name = $values['name']; - $exist = true; - $loops = 30; - // Loops to exit or tries. - while ($exist && $loops > 0) { - $exist = (bool) db_get_row_filter( - 'treport', - ['name' => io_safe_input($posible_name)] - ); - - if ($exist) { - $loops--; - $posible_name = $values['name'].' ('.(30 - $loops).')'; - } - } - - if ($exist) { - ui_print_error_message( - sprintf( - __("Error create '%s' report, the name exist and there aren't free name."), - $reportElement->name - ) - ); - break; - } else if ($loops != 30) { - ui_print_warning_message( - sprintf( - __("Warning create '%s' report, the name exist, the report have a name %s."), - $reportElement->name, - $posible_name - ) - ); - } - - $values['name'] = io_safe_input($posible_name); - } else { - ui_print_error_message(__("Error the report haven't name.")); - break; - } - - if (isset($reportElement->group) === true - && empty($reportElement->group) === false - ) { - $id_group = db_get_value( - 'id_grupo', - 'tgrupo', - 'nombre', - $reportElement->group - ); - if ($id_group === false) { - ui_print_error_message(__("Error the report haven't group.")); - break; - } - } - - if (isset($reportElement->description) === true) { - $values['description'] = $reportElement->description; - } - - $id_report = db_process_sql_insert('treport', $values); - - ui_print_result_message( - $id_report, - sprintf(__("Success create '%s' report."), $posible_name), - sprintf(__("Error create '%s' report."), $posible_name) - ); - - if ($id_report) { - db_pandora_audit( - AUDIT_LOG_REPORT_MANAGEMENT, - 'Create report '.$id_report, - false, - false - ); - } else { - db_pandora_audit( - AUDIT_LOG_REPORT_MANAGEMENT, - 'Fail to create report', - false, - false - ); - break; - } - - foreach ($reportElement->item as $item) { - $item = (array) $item; - - $values = []; - $values['id_report'] = $id_report; - if (isset($item['description']) === true) { - $values['description'] = io_safe_input($item['description']); - } - - if (isset($item['period']) === true) { - $values['period'] = io_safe_input($item['period']); - } - - if (isset($item['type']) === true) { - $values['type'] = io_safe_input($item['type']); - } - - $agents_item = []; - if (isset($item['agent']) === true) { - $agents = agents_get_agents( - ['id_grupo' => $group_filter], - [ - 'id_agente', - 'alias', - ] - ); - - $agent_clean = str_replace( - [ - '[', - ']', - ], - '', - io_safe_output($item['agent']) - ); - $regular_expresion = ($agent_clean != $item['agent']); - - foreach ($agents as $agent) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['alias']))) { - $agents_item[$agent['id_agente']]['name'] = $agent['alias']; - } - } else { - if ($agent_clean == io_safe_output($agent['alias'])) { - $agents_item[$agent['id_agente']]['name'] = $agent['alias']; - } - } - } - } - - if (isset($item['module']) === true) { - $module_clean = str_replace(['[', ']'], '', $item['module']); - $regular_expresion = ($module_clean != $item['module']); - - foreach ($agents_item as $id => $agent) { - $modules = db_get_all_rows_filter( - 'tagente_modulo', - ['id_agente' => $id], - [ - 'id_agente_modulo', - 'nombre', - ] - ); - - $agents_item[$id]['modules'] = []; - - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { - $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = $module['nombre']; - } - } else { - if ($module_clean == io_safe_output($module['nombre'])) { - $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = $module['nombre']; - } - } - } - } - } - - switch ($item['type']) { - case 2: - case 'custom_graph': - case 'automatic_custom_graph': - $group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item['graph'])); - $values['id_gs'] = $group; - break; - - case 3: - case 'SLA': - if (isset($item['only_display_wrong'])) { - $values['only_display_wrong'] = (string) $item['only_display_wrong']; - } - - if (isset($item['monday'])) { - $values['monday'] = (string) $item['monday']; - } - - if (isset($item['tuesday'])) { - $values['tuesday'] = (string) $item['tuesday']; - } - - if (isset($item['wednesday'])) { - $values['wednesday'] = (string) $item['wednesday']; - } - - if (isset($item['thursday'])) { - $values['thursday'] = (string) $item['thursday']; - } - - if (isset($item['friday'])) { - $values['friday'] = (string) $item['friday']; - } - - if (isset($item['saturday'])) { - $values['saturday'] = (string) $item['saturday']; - } - - if (isset($item['sunday'])) { - $values['sunday'] = (string) $item['sunday']; - } - - if (isset($item['time_from'])) { - $values['time_from'] = (string) $item['time_from']; - } - - if (isset($item['time_to'])) { - $values['time_to'] = (string) $item['time_to']; - } - - $slas = []; - if (!isset($item['sla'])) { - $item['sla'] = []; - } - - foreach ($item['sla'] as $sla_xml) { - if (isset($sla_xml->agent)) { - $agents = agents_get_agents(['id_grupo' => $group_filter], ['id_agente', 'nombre']); - - $agent_clean = str_replace(['[', ']'], '', $sla_xml->agent); - $regular_expresion = ($agent_clean != $sla_xml->agent); - - foreach ($agents as $agent) { - $id_agent = false; - if ($regular_expresion) { - if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['nombre']))) { - $id_agent = $agent['id_agente']; - } else { - if ($agent_clean == io_safe_output($agent['nombre'])) { - $id_agent = $agent['id_agente']; - } - } - } - - if ($id_agent) { - if (isset($sla_xml->module)) { - $module_clean = str_replace(['[', ']'], '', $sla_xml->module); - $regular_expresion = ($module_clean != $sla_xml->module); - - $modules = db_get_all_rows_filter( - 'tagente_modulo', - ['id_agente' => $id_agent], - [ - 'id_agente_modulo', - 'nombre', - ] - ); - - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { - $slas[] = [ - 'id_agent_module' => $module['id_agente_modulo'], - 'sla_max' => (string) $sla_xml->sla_max, - 'sla_min' => (string) $sla_xml->sla_min, - 'sla_limit' => (string) $sla_xml->sla_limit, - ]; - } - } else { - if ($module_clean == io_safe_output($module['nombre'])) { - $slas[] = [ - 'id_agent_module' => $module['id_agente_modulo'], - 'sla_max' => (string) $sla_xml->sla_max, - 'sla_min' => (string) $sla_xml->sla_min, - 'sla_limit' => (string) $sla_xml->sla_limit, - ]; - } - } - } - } - } - } - } - } - break; - - case 'text': - $values['text'] = io_safe_input($item['text']); - break; - - case 'sql': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['external_source'] = io_safe_input($item['sql']); - break; - - case 'sql_graph_pie': - case 'sql_graph_vbar': - case 'sql_graph_hbar': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['external_source'] = io_safe_input($item['sql']); - break; - - case 'event_report_group': - $values['id_agent'] = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item->group)); - break; - - case 'url': - $values['external_source'] = io_safe_input($item['url']); - break; - - case 'database_serialized': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['line_separator'] = io_safe_input($item['line_separator']); - $values['column_separator'] = io_safe_input($item['column_separator']); - break; - - case 1: - case 'simple_graph': - case 'simple_baseline_graph': - case 6: - case 'monitor_report': - case 7: - case 'avg_value': - case 8: - case 'max_value': - case 9: - case 'min_value': - case 10: - case 'sumatory': - case 'event_report_module': - case 'alert_report_module': - case 'alert_report_agent': - case 'alert_report_group': - case 'agent_detailed_event': - case 'event_report_agent': - default: - // Do nothing. - break; - } - - if (empty($agents_item) === true) { - $id_content = db_process_sql_insert('treport_content', $values); - ui_print_result_message( - $id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type']) - ); - - if ($item['type'] == 'SLA') { - foreach ($slas as $sla) { - $sla['id_report_content'] = $id_content; - $result = db_process_sql_insert('treport_content_sla_combined', $sla); - ui_print_result_message( - $result, - sprintf(__("Success add '%s' SLA."), $sla['id_agent_module']), - sprintf(__("Error add '%s' SLA."), $sla['id_agent_module']) - ); - } - } - } else { - foreach ($agents_item as $id_agent => $agent) { - if (empty($agent['modules'])) { - $values['id_agent'] = $id_agent; - $id_content = db_process_sql_insert('treport_content', $values); - ui_print_result_message( - $id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type']) - ); - } else { - foreach ($agent['modules'] as $id_module => $module) { - $values['id_agent_module'] = $id_module; - $values['id_agent'] = $id_agent; - - $id_content = db_process_sql_insert('treport_content', $values); - ui_print_result_message( - $id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type']) - ); - } - } - } - } - } - } -} - - -function process_upload_xml_visualmap($xml, $filter_group=0) -{ - global $config; - - foreach ($xml->xpath('/visual_map') as $visual_map) { - if (isset($visual_map->name)) { - $values['name'] = (string) $visual_map->name; - } else { - ui_print_error_message( - __("Error create '%s' visual map, lost tag name.") - ); - break; - } - - $values['id_group'] = 0; - if (isset($visual_map->group)) { - $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($visual_map->group)); - if ($id_group !== false) { - $values['id_group'] = $id_group; - } - } - - if (isset($visual_map->background)) { - $values['background'] = (string) $visual_map->background; - } - - $values['width'] = 0; - if (isset($visual_map->width)) { - $values['width'] = (string) $visual_map->width; - } - - $values['height'] = 0; - if (isset($visual_map->height)) { - $values['height'] = (string) $visual_map->height; - } - - $posible_name = $values['name']; - $exist = true; - $loops = 30; - // Loops to exit or tries - while ($exist && $loops > 0) { - $exist = (bool) db_get_row_filter('tlayout', ['name' => io_safe_input($posible_name)]); - - if ($exist) { - $loops--; - $posible_name = $values['name'].' ('.(30 - $loops).')'; - } - } - - if ($exist) { - ui_print_error_message( - sprintf( - __("Error create '%s' visual map, the name exist and there aren't free name."), - $values['name'] - ) - ); - continue; - } else if ($loops != 30) { - ui_print_error_message( - sprintf( - __("Warning create '%s' visual map, the name exist, the report have a name %s."), - $values['name'], - $posible_name - ) - ); - } - - $values['name'] = io_safe_input($posible_name); - $id_visual_map = db_process_sql_insert('tlayout', $values); - - ui_print_result_message( - (bool) $id_visual_map, - sprintf(__("Success create '%s' visual map."), $posible_name), - sprintf(__("Error create '%s' visual map."), $posible_name) - ); - - if ($id_visual_map !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Visual Console #%s', $id_visual_map), - $config['id_user'] - ); - } else { - break; - } - - $relation_other_ids = []; - - foreach ($visual_map->item as $item) { - $no_agents = true; - - if (isset($item->agent)) { - $agent_clean = str_replace(['[', ']'], '', $item->agent); - $regular_expresion = ($agent_clean != $item->agent); - - $agents = agents_get_agents(['id_grupo' => $filter_group], ['id_agente', 'nombre']); - if ($agents === false) { - $agents = []; - } - - $temp = []; - foreach ($agents as $agent) { - $temp[$agent['id_agente']] = $agent['nombre']; - } - - $agents = $temp; - - $agents_in_item = []; - foreach ($agents as $id => $agent) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent))) { - $agents_in_item[$id]['name'] = $agent; - $no_agents = false; - } - } else { - if ($agent_clean == io_safe_output($agent)) { - $agents_in_item[$id]['name'] = $agent; - $no_agents = false; - break; - } - } - } - } - - $no_modules = true; - if (isset($item->module)) { - $module_clean = str_replace(['[', ']'], '', $item->module); - $regular_expresion = ($module_clean != $item->module); - - foreach ($agents_in_item as $id => $agent) { - $modules = db_get_all_rows_filter( - 'tagente_modulo', - ['id_agente' => $id], - [ - 'id_agente_modulo', - 'nombre', - ] - ); - - $modules_in_item = []; - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { - $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; - $no_modules = false; - } - } else { - if ($module_clean == io_safe_output($module['nombre'])) { - $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; - $no_modules = false; - break; - } - } - } - - $agents_in_item[$id]['modules'] = $modules_in_item; - } - } - - $values = []; - - $values['id_layout'] = $id_visual_map; - if (isset($item->label)) { - $values['label'] = io_safe_input($item->label); - } - - if (isset($item->x)) { - $values['pos_x'] = (string) $item->x; - } - - if (isset($item->y)) { - $values['pos_y'] = (string) $item->y; - } - - if (isset($item->height)) { - $values['height'] = (string) $item->height; - } - - if (isset($item->width)) { - $values['width'] = (string) $item->width; - } - - if (isset($item->image)) { - $values['image'] = (string) $item->image; - } - - if (isset($item->period)) { - $values['period'] = (string) $item->period; - } - - if (isset($item->parent_item)) { - // Hack for link the items use the OTHER_ID - // and have too OTHER_ID - // then $relation_other_ids[OTHER_ID] have the item_id in DB. - $values['parent_item'] = (string) $relation_other_ids[(string) $item->parent_item]; - } - - if (isset($item->map_linked)) { - $values['id_layout_linked'] = (string) $item->map_linked; - } - - if (isset($item->type)) { - $values['type'] = (string) $item->type; - } - - if (isset($item->clock_animation)) { - $values['clock_animation'] = (string) $item->clock_animation; - } - - if (isset($item->fill_color)) { - $values['fill_color'] = (string) $item->fill_color; - } - - if (isset($item->type_graph)) { - $values['type_graph'] = (string) $item->type_graph; - } - - if (isset($item->time_format)) { - $values['time_format'] = (string) $item->time_format; - } - - if (isset($item->timezone)) { - $values['timezone'] = (string) $item->timezone; - } - - if (isset($item->border_width)) { - $values['border_width'] = (string) $item->border_width; - } - - if (isset($item->border_color)) { - $values['border_color'] = (string) $item->border_color; - } - - if ($no_agents) { - $id_item = db_process_sql_insert('tlayout_data', $values); - - ui_print_result_message( - (bool) $id_item, - sprintf(__("Success create item type '%d' visual map."), $values['type']), - sprintf(__("Error create item type '%d' visual map."), $values['type']) - ); - - if ($id_item !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Item %s in Visual Console #%s', $id_item, $values['id_layout']), - $config['id_user'] - ); - } - } else { - foreach ($agents_in_item as $id => $agent) { - if ($no_modules) { - $values['id_agent'] = $id; - - $id_item = db_process_sql_insert('tlayout_data', $values); - - if (isset($item->other_id) === true) { - $relation_other_ids[(string) $item->other_id] = $id_item; - } - - ui_print_result_message( - (bool) $id_item, - sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), - sprintf(__("Error create item for agent '%s' visual map."), $agent['name']) - ); - - if ($id_item !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Item %s in Visual Console #%s', $id_item, $values['id_layout']), - $config['id_user'] - ); - } - } else { - // TODO: Review this else. - foreach ($agent['modules'] as $id_module => $module) { - $values['id_agent'] = $id; - $values['id_agente_modulo'] = $id_module; - - db_process_sql_insert('tlayout_data', $values); - - ui_print_result_message( - (bool) $id_item, - sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), - sprintf(__("Error create item for agent '%s' visual map."), $agent['name']) - ); - - if ($id_item !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Item %s in Visual Console #%s', $id_item, $values['id_layout']), - $config['id_user'] - ); - } - } - } - } - } - } - } -} - - -function process_upload_xml_component($xml) -{ - // Extract components. - $components = []; - foreach ($xml->xpath('/component') as $componentElement) { - $name = io_safe_input((string) $componentElement->name); - $id_os = (int) $componentElement->id_os; - $os_version = io_safe_input((string) $componentElement->os_version); - $data = io_safe_input((string) $componentElement->data); - $type = (int) $componentElement->type; - $group = (int) $componentElement->group; - $description = io_safe_input((string) $componentElement->description); - $module_interval = (int) $componentElement->module_interval; - $max = (float) $componentElement->max; - $min = (float) $componentElement->min; - $tcp_send = io_safe_input((string) $componentElement->tcp_send); - $tcp_rcv_text = io_safe_input((string) $componentElement->tcp_rcv_text); - $tcp_port = (int) $componentElement->tcp_port; - $snmp_oid = io_safe_input((string) $componentElement->snmp_oid); - $snmp_community = io_safe_input((string) $componentElement->snmp_community); - $id_module_group = (int) $componentElement->id_module_group; - $module_source = (int) $componentElement->module_source; - $plugin = (int) $componentElement->plugin; - $plugin_username = io_safe_input((string) $componentElement->plugin_username); - $plugin_password = io_safe_input((string) $componentElement->plugin_password); - $plugin_parameters = io_safe_input((string) $componentElement->plugin_parameters); - $max_timeout = (int) $componentElement->max_timeout; - $max_retries = (int) $componentElement->max_retries; - $historical_data = (int) $componentElement->historical_data; - $dynamic_interval = (int) $componentElement->dynamic_interval; - $dynamic_min = (int) $componentElement->dynamic_min; - $dynamic_max = (int) $componentElement->dynamic_max; - $dynamic_two_tailed = (int) $componentElement->dynamic_two_tailed; - $min_war = (float) $componentElement->min_war; - $max_war = (float) $componentElement->max_war; - $str_war = (string) $componentElement->str_war; - $min_cri = (float) $componentElement->min_cri; - $max_cri = (float) $componentElement->max_cri; - $str_cri = (string) $componentElement->str_cri; - $ff_treshold = (int) $componentElement->ff_treshold; - $snmp_version = (int) $componentElement->snmp_version; - $auth_user = io_safe_input((string) $componentElement->auth_user); - $auth_password = io_safe_input((string) $componentElement->auth_password); - $auth_method = io_safe_input((string) $componentElement->auth_method); - $privacy_method = io_safe_input((string) $componentElement->privacy_method); - $privacy_pass = io_safe_input((string) $componentElement->privacy_pass); - $security_level = io_safe_input((string) $componentElement->security_level); - $wmi_query = io_safe_input((string) $componentElement->wmi_query); - $key_string = io_safe_input((string) $componentElement->key_string); - $field_number = (int) $componentElement->field_number; - $namespace = io_safe_input((string) $componentElement->namespace); - $wmi_user = io_safe_input((string) $componentElement->wmi_user); - $wmi_password = io_safe_input((string) $componentElement->wmi_password); - $post_process = io_safe_input((float) $componentElement->post_process); - - $idComponent = false; - switch ((int) $componentElement->module_source) { - case 1: - // Local component. - $values = [ - 'description' => $description, - 'id_network_component_group' => $group, - 'os_version' => $os_version, - ]; - $return = enterprise_hook('local_components_create_local_component', [$name, $data, $id_os, $values]); - if ($return !== ENTERPRISE_NOT_HOOK) { - $idComponent = $return; - } - break; - - case 2: - // Network component - // for modules - // 15 = remote_snmp, 16 = remote_snmp_inc, - // 17 = remote_snmp_string, 18 = remote_snmp_proc. - $custom_string_1 = ''; - $custom_string_2 = ''; - $custom_string_3 = ''; - if ($type >= 15 && $type <= 18) { - // New support for snmp v3. - $tcp_send = $snmp_version; - $plugin_user = $auth_user; - $plugin_pass = $auth_password; - $plugin_parameters = $auth_method; - $custom_string_1 = $privacy_method; - $custom_string_2 = $privacy_pass; - $custom_string_3 = $security_level; - } - - $idComponent = network_components_create_network_component( - $name, - $type, - $group, - [ - 'description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $plugin_username, - 'plugin_pass' => $plugin_password, - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - ] - ); - if ((bool) $idComponent === true) { - $components[] = $idComponent; - } - break; - - case 4: - // Plugin component. - $idComponent = network_components_create_network_component( - $name, - $type, - $group, - [ - 'description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $plugin_username, - 'plugin_pass' => $plugin_password, - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - ] - ); - if ((bool) $idComponent === true) { - $components[] = $idComponent; - } - break; - - case 6: - // WMI component. - $idComponent = network_components_create_network_component( - $name, - $type, - $group, - [ - 'description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $namespace, - // work around - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $field_number, - // work around - 'snmp_oid' => $wmi_query, - // work around - 'snmp_community' => $key_string, - // work around - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $wmi_user, - // work around - 'plugin_pass' => $wmi_password, - // work around - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - ] - ); - if ((bool) $idComponent === true) { - $components[] = $idComponent; - } - break; - - case 5: - // Prediction component. - case 7: - // Web component. - default: - // Do nothing. - break; - } - - ui_print_result_message( - (bool) $idComponent, - sprintf(__("Success create '%s' component."), $name), - sprintf(__("Error create '%s' component."), $name) - ); - } - - // Extract the template. - $templateElement = $xml->xpath('//template'); - if (empty($templateElement) === false) { - $templateElement = $templateElement[0]; - - $templateName = (string) $templateElement->name; - $templateDescription = (string) $templateElement->description; - - $idTemplate = db_process_sql_insert('tnetwork_profile', ['name' => $templateName, 'description' => $templateDescription]); - - $result = false; - if ((bool) $idTemplate) { - foreach ($components as $idComponent) { - db_process_sql_insert('tnetwork_profile_component', ['id_nc' => $idComponent, 'id_np' => $idTemplate]); - } - } - } -} - - -function process_upload_xml($xml) -{ - $hook_enterprise = enterprise_include('extensions/resource_registration/functions.php'); - - // Extract component. - process_upload_xml_component($xml); - - $group_filter = get_parameter('group'); - - // Extract visual map. - process_upload_xml_visualmap($xml, $group_filter); - - // Extract policies. - if ($hook_enterprise === true) { - $centralized_management = is_management_allowed(); - if ($centralized_management === true) { - process_upload_xml_policy($xml, $group_filter); - } - } - - // Extract reports. - process_upload_xml_report($xml, $group_filter); -} - - -function resource_registration_extension_main() -{ - global $config; - - if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { - db_pandora_audit( - AUDIT_LOG_ACL_VIOLATION, - 'Trying to access Setup Management' - ); - include 'general/noaccess.php'; - return; - } - - include_once $config['homedir'].'/include/functions_network_components.php'; - include_once $config['homedir'].'/include/functions_db.php'; - enterprise_include_once('include/functions_local_components.php'); - - ui_print_standard_header( - __('Resource registration'), - 'images/extensions.png', - false, - '', - true, - [], - [ - [ - 'link' => '', - 'label' => __('Resources'), - ], - [ - 'link' => '', - 'label' => __('Resource registration'), - ], - ] - ); - - if (extension_loaded('libxml') === false) { - ui_print_error_message(_('Error, please install the PHP libXML in the system.')); - - return; - } - - if (is_management_allowed() === false) { - if (is_metaconsole() === false) { - $url = ''.__('metaconsole').''; - } else { - $url = __('any node'); - } - - ui_print_warning_message( - __( - 'This node is configured with centralized mode. Go to %s to create a policy.', - $url - ) - ); - - return; - } - - ui_print_warning_message( - __('This extension makes registering resource templates easier.').'
'.__('Here you can upload a resource template in .ptr format.').'
'.__('Please refer to our documentation for more information on how to obtain and use %s resources.', get_product_name()).' '.'

'.__('You can get more resurces in our Public Resource Library') - ); - - $table = new stdClass(); - $table->class = 'databox filter-table-adv'; - $table->id = 'resource_registration_table'; - - $table->data = []; - - $table->data[0][] = html_print_label_input_block( - __('File to upload'), - html_print_input_file('resource_upload', true) - ); - - $table->data[0][] = html_print_label_input_block( - __('Group filter'), - html_print_select_groups(false, 'AW', true, 'group', '', '', __('All'), 0, true) - ); - - // Upload form. - echo '
'; - html_print_table($table); - html_print_action_buttons( - html_print_submit_button( - __('Upload'), - 'upload', - false, - [ 'icon' => 'wand' ], - true - ), - ['type' => 'form_action'] - ); - echo '
'; - /* - echo ''; - echo ''; - echo "'; - echo ''; - echo "'; - echo '
"; - echo ''.__('Group filter: ').''; - html_print_select_groups(false, 'AW', true, 'group'); - echo '"; - echo '
';*/ - - if (isset($_FILES['resource_upload']['tmp_name']) === false) { - return; - } - - $xml = simplexml_load_file($_FILES['resource_upload']['tmp_name'], null, LIBXML_NOCDATA); - - if ($xml === false) { - ui_print_error_message( - __('Error uploading resource. Check if the selected file is a valid resource template in .ptr format') - ); - } else { - process_upload_xml($xml); - } -} - - -extensions_add_godmode_menu_option(__('Resource registration'), 'PM', 'gagente', '', 'v1r1'); -extensions_add_godmode_function('resource_registration_extension_main'); diff --git a/pandora_console/extras/delete_files/delete_files.txt b/pandora_console/extras/delete_files/delete_files.txt index f3eada8070..b3fbea46dd 100644 --- a/pandora_console/extras/delete_files/delete_files.txt +++ b/pandora_console/extras/delete_files/delete_files.txt @@ -1736,3 +1736,5 @@ extensions/files_repo/sql/files_repo.oracle.sql extensions/files_repo/sql/files_repo.postgreSQL.sql extensions/files_repo/sql/files_repo.sql extensions/files_repo +extensions/resource_exportation.php +extensions/resource_registration.php diff --git a/pandora_console/godmode/resources/resources_export_import.php b/pandora_console/godmode/resources/resources_export_import.php index b7fc23704a..9fe4eb2852 100644 --- a/pandora_console/godmode/resources/resources_export_import.php +++ b/pandora_console/godmode/resources/resources_export_import.php @@ -42,6 +42,7 @@ if (check_acl($config['id_user'], 0, 'PM') === false) { } require_once $config['homedir'].'/include/class/Prd.class.php'; +$msg = ''; // Instance of the prd class. $prd = new Prd(); @@ -50,11 +51,17 @@ if (isset($_FILES['resource_import']) === true) { $data = parse_ini_file($_FILES['resource_import']['tmp_name'], true); if ($data !== false) { $msg = $prd->importPrd($data); + $array_msg = []; + foreach ($msg['items'] as $key => $value) { + $array_msg[$value[0]][key($value[1])][$value[1][key($value[1])]] = $value[1][key($value[1])]; + } + + $msg['items'] = $array_msg; } else { $msg = [ 'status' => false, - 'items' => [], - 'errors' => ['Unexpected error: Unable to parse PRD file.'] + 'items' => [], + 'errors' => ['Unexpected error: Unable to parse PRD file.'], ]; } } @@ -130,10 +137,48 @@ html_print_table($table); ?> \ No newline at end of file + diff --git a/pandora_console/include/ajax/resources.ajax.php b/pandora_console/include/ajax/resources.ajax.php index 379a499407..7035655620 100644 --- a/pandora_console/include/ajax/resources.ajax.php +++ b/pandora_console/include/ajax/resources.ajax.php @@ -69,10 +69,11 @@ if ((bool) is_ajax() === true) { $data = $prd->exportPrd($type, $value, $name); - $return = ''; + $return = []; if (empty($data) === false) { - $filename = $type.'-'.date('Ymd').'-'.date('His').'.prd'; + $filename = uniqid().'.prd'; + $filename_download = date('YmdHis').'-'.$type.'-'.$name.'.prd'; $file = $config['attachment_store'].'/'.$filename; $file_pointer = fopen($file, 'a'); @@ -80,18 +81,19 @@ if ((bool) is_ajax() === true) { $write = fwrite($file_pointer, $data); if ($write === false) { - $return = -2; + $return['error'] = -2; } else { - $return = $filename; + $return['name'] = $filename; + $return['name_download'] = $filename_download; } fclose($file_pointer); } else { - $return = -1; + $return['error'] = -1; } } - echo $return; + echo json_encode($return); return; } From b858527a315bd225ec1b2b1b821880b071fc85ac Mon Sep 17 00:00:00 2001 From: Daniel Maya Date: Wed, 7 Feb 2024 16:45:11 +0100 Subject: [PATCH 20/24] #12687 Changes in export dialog --- .../godmode/resources/resources_export_import.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pandora_console/godmode/resources/resources_export_import.php b/pandora_console/godmode/resources/resources_export_import.php index 5127094753..721666df05 100644 --- a/pandora_console/godmode/resources/resources_export_import.php +++ b/pandora_console/godmode/resources/resources_export_import.php @@ -149,13 +149,8 @@ html_print_table($table); Object.entries(value).forEach(([field, value2]) => { message += "with " + field + ": ("; if (typeof value2 === 'object' && Object.keys(value2).length > 0) { - let cont = 0; Object.entries(value2).forEach(([key3, value3]) => { message += value3 + " , "; - if (cont === 6) { - message += "
"; - } - cont++; }); } }); From 5d000a03d1ef686afaa877e65a624452818bf6fa Mon Sep 17 00:00:00 2001 From: Enrique Martin Date: Wed, 7 Feb 2024 18:26:22 +0100 Subject: [PATCH 21/24] Improved import and export. Supported Array and CSV fields. --- pandora_console/include/class/Prd.class.php | 811 ++++++++++++-------- 1 file changed, 505 insertions(+), 306 deletions(-) diff --git a/pandora_console/include/class/Prd.class.php b/pandora_console/include/class/Prd.class.php index b4815e6f54..c1b58f71eb 100644 --- a/pandora_console/include/class/Prd.class.php +++ b/pandora_console/include/class/Prd.class.php @@ -1899,6 +1899,455 @@ class Prd } } + /** + * Function to traverse the array based on the reference. + * + * @param mixed $data JSON Array. + * @param string $reference JSON key reference. + * + * @return mixed + */ + private function extractJsonArrayValue($data, $reference) { + $keys = explode('.', $reference); + + foreach ($keys as $key) { + if (preg_match('/(.+)\[(\d+)\]/', $key, $matches)) { + // Handle array access + $data = $data[$matches[1]][$matches[2]]; + } else { + // Handle regular key access + $data = $data[$key]; + } + } + + return $data; + } + + /** + * Function to update a value in the JSON based on the reference. + * + * @param mixed $data JSON Array. + * @param string $reference JSON key reference. + * @param mixed $newValue JSON new value. + * + * @return void + */ + private function updateJsonArrayValue(&$data, $reference, $newValue) { + $keys = explode('.', $reference); + $lastKey = array_pop($keys); + + foreach ($keys as $key) { + if (preg_match('/(.+)\[(\d+)\]/', $key, $matches)) { + // Handle array access + $data = &$data[$matches[1]][$matches[2]]; + } else { + // Handle regular key access + $data = &$data[$key]; + } + } + + // Update the value + if (isset($data[$lastKey]) === true) { + $data[$lastKey] = $newValue; + } + } + + /** + * Get reference from value and return true if found. + * + * @param mixed $when_value Condition to build SQL. + * @param array $sql_tables SQL tables. + * @param array $sql_wheres SQL wheres. + * + * @return void + */ + private function recursiveWhenSQLBuildWhere($when_value, &$sql_tables, &$sql_wheres) { + $rec_when = reset($when_value['when']); + if (is_array($rec_when) === true) { + $sql_tables[] = '`'.$rec_when['table'].'`'; + $sql_wheres[] = '`'.$when_value['table'].'`.`'.array_key_first($when_value['when']).'` = `'.$rec_when['table'].'`.`'.$rec_when['id'].'`'; + + $this->recursiveWhenSQLBuildWhere($rec_when, $sql_tables, $sql_wheres); + } else { + $sql_wheres[] = '`'.$when_value['table'].'`.`'.array_key_first($when_value['when']).'` = "'.$rec_when.'"'; + } + } + + /** + * Evals conditional references. + * + * @param string $compare_value Value to compare. + * @param mixed $when Condition to check. + * + * @return boolean + */ + private function evalConditionalRef($compare_value, $when) { + $when_value = reset($when); + + if ($compare_value == $when_value) { + return true; + } else { + if (is_array($when_value) === true) { + if (isset($when_value['table']) === true + && isset($when_value['id']) === true + && isset($when_value['when']) === true + ) { + if ($this->validateJSON($compare_value) === true) { + $json_value = json_decode($compare_value, true); + if (isset($json_value[$when_value['table']][$when_value['id']])) { + $compare_value = $json_value[$when_value['table']][$when_value['id']]; + + return $this->evalConditionalRef($compare_value, $when_value['when']); + } + } + + $sql_fields = []; + $sql_tables = []; + $sql_wheres = []; + + $sql_fields[] = '`'.$when_value['table'].'`.`'.$when_value['id'].'`'; + $sql_tables[] = '`'.$when_value['table'].'`'; + + $this->recursiveWhenSQLBuildWhere($when_value, $sql_tables, $sql_wheres); + + $sql = sprintf('SELECT %s FROM %s WHERE %s', + implode(',', $sql_fields), + implode(',', $sql_tables), + implode(' AND ', $sql_wheres) + ); + + $sql_value = db_get_value_sql($sql); + + if ($compare_value == $sql_value) { + return true; + } + } + } + } + + return false; + } + + /** + * Get reference from value and return true if found. + * + * @param string $table Table. + * @param string $column Table column. + * @param array $reference Reference to extract value. + * @param array $row Current row values. + * @param string $value Value to update. + * + * @return void + */ + private function getReferenceFromValue($table, $column, $reference, $row, &$value) { + if (isset($reference['conditional_refs']) === true) { + // Conditional refs. + $conditional = $reference['conditional_refs']; + foreach ($conditional as $key => $condition) { + if (isset($condition['when']) === true + && isset($condition['ref']) === true + ) { + if (isset($row[array_key_first($condition['when'])]) === true) { + $compare_value = $row[array_key_first($condition['when'])]; + + if ($this->evalConditionalRef($compare_value, $condition['when']) === true + && empty($value) === false + ) { + if (isset($condition['ref']['array']) === true + && $condition['ref']['array'] === true + ) { + if ($this->validateJSON($value)) { + $value_arr = json_decode($value, true); + if (is_array($value_arr)) { + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_val = $this->searchValue( + $condition['ref']['columns'], + $condition['ref']['table'], + $condition['ref']['id'], + $val + ); + if (isset($condition['ref']['values_as_keys']) === true + && $condition['ref']['values_as_keys'] === true + ) { + $ref_arr[$ref_val] = $ref_val; + } else { + $ref_arr[] = $ref_val; + } + } + $value = json_encode($ref_arr); + } + } + } else if (isset($condition['ref']['csv']) === true + && $condition['ref']['csv'] === true + ) { + $csv_separator = ','; + if (isset($condition['ref']['csv_separator']) === true + && $condition['ref']['csv_separator'] === true + ) { + $csv_separator = $condition['ref']['csv_separator']; + } + $value_arr = explode($csv_separator, $value); + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_arr[] = $this->searchValue( + $condition['ref']['columns'], + $condition['ref']['table'], + $condition['ref']['id'], + $val + ); + } + $value = implode($csv_separator, $ref_arr); + } else { + $value = $this->searchValue( + $condition['ref']['columns'], + $condition['ref']['table'], + $condition['ref']['id'], + $value + ); + } + return; + } + } + } + } + } + + if (isset($reference['ref']) === true) { + $ref = $reference['ref']; + + if (isset($ref['join']) === true) { + $join_array = $this->recursiveJoin( + $ref, + $value + ); + $value = [$ref['table'] => $join_array]; + $value = json_encode($value); + } else { + if (isset($ref['array']) === true + && $ref['array'] === true + ) { + if ($this->validateJSON($value)) { + $value_arr = json_decode($value, true); + if (is_array($value_arr)) { + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_val = $this->searchValue( + $ref['columns'], + $ref['table'], + $ref['id'], + $val + ); + if (isset($ref['values_as_keys']) === true + && $ref['values_as_keys'] === true + ) { + $ref_arr[$ref_val] = $ref_val; + } else { + $ref_arr[] = $ref_val; + } + } + $value = json_encode($ref_arr); + } + } + } else if (isset($ref['csv']) === true + && $ref['csv'] === true + ) { + $csv_separator = ','; + if (isset($ref['csv_separator']) === true + && $ref['csv_separator'] === true + ) { + $csv_separator = $ref['csv_separator']; + } + $value_arr = explode($csv_separator, $value); + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_arr[] = $this->searchValue( + $ref['columns'], + $ref['table'], + $ref['id'], + $val + ); + } + $value = implode($csv_separator, $ref_arr); + } else { + $value = $this->searchValue( + $ref['columns'], + $ref['table'], + $ref['id'], + $value + ); + } + } + } + } + + /** + * Get value from reference and return true if found. + * + * @param string $table Table. + * @param string $column Table column. + * @param array $reference Reference to extract value. + * @param string $value Value to update. + * + * @return boolean + */ + private function getValueFromReference($table, $column, $reference, &$value) { + if (isset($reference['conditional_refs']) === true) { + // Conditional refs. + $prd_item = false; + $conditional = $reference['conditional_refs']; + foreach ($conditional as $key => $condition) { + if (isset($condition['when']) === true + && isset($condition['ref']) === true + ) { + if (isset($this->currentItem['parsed'][array_key_first($condition['when'])]) === true) { + $compare_value = $this->currentItem['parsed'][array_key_first($condition['when'])]; + + if ($this->evalConditionalRef($compare_value, $condition['when']) === true + && empty($value) === false + ) { + if (isset($condition['ref']['array']) === true + && $condition['ref']['array'] === true + ) { + if ($this->validateJSON($value)) { + $value_arr = json_decode($value, true); + if (is_array($value_arr)) { + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_val = $this->findPrdItem( + $condition['ref'], + $value + ); + if (isset($condition['ref']['values_as_keys']) === true + && $condition['ref']['values_as_keys'] === true + ) { + $ref_arr[$ref_val] = $ref_val; + } else { + $ref_arr[] = $ref_val; + } + } + $prd_item = json_encode($ref_arr); + } + } + } else if (isset($condition['ref']['csv']) === true + && $condition['ref']['csv'] === true + ) { + $csv_separator = ','; + if (isset($condition['ref']['csv_separator']) === true + && $condition['ref']['csv_separator'] === true + ) { + $csv_separator = $condition['ref']['csv_separator']; + } + $value_arr = explode($csv_separator, $value); + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_arr[] = $this->findPrdItem( + $condition['ref'], + $value + ); + } + $prd_item = implode($csv_separator, $ref_arr); + } else { + $prd_item = $this->findPrdItem( + $condition['ref'], + $value + ); + } + break; + } + } + } + } + + if (isset($condition['ref']['autocreate_item']) === true + && $prd_item === false + ) { + $this->autocreateItem( + $condition['ref'], + $column, + $condition['ref']['autocreate_item'] + ); + } else if (empty($prd_item) === false) { + $value = $prd_item; + } else { + return false; + } + + return true; + } + + if (isset($reference['ref']) === true) { + $ref = $reference['ref']; + if (isset($ref['array']) === true + && $ref['array'] === true + ) { + if ($this->validateJSON($value)) { + $value_arr = json_decode($value, true); + if (is_array($value_arr)) { + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_val = $this->findPrdItem( + $ref, + $value + ); + if (isset($ref['values_as_keys']) === true + && $ref['values_as_keys'] === true + ) { + $ref_arr[$ref_val] = $ref_val; + } else { + $ref_arr[] = $ref_val; + } + } + $prd_item = json_encode($ref_arr); + } + } + } else if (isset($ref['csv']) === true + && $ref['csv'] === true + ) { + $csv_separator = ','; + if (isset($ref['csv_separator']) === true + && $ref['csv_separator'] === true + ) { + $csv_separator = $ref['csv_separator']; + } + $value_arr = explode($csv_separator, $value); + $ref_arr = []; + foreach ($value_arr as $val) { + $ref_arr[] = $this->findPrdItem( + $ref, + $value + ); + } + $prd_item = implode($csv_separator, $ref_arr); + } else { + $prd_item = $this->findPrdItem( + $ref, + $value + ); + } + + if (isset($ref['autocreate_item']) === true && $prd_item === false) { + $this->autocreateItem( + $ref, + $column, + $ref['autocreate_item'] + ); + } else if (empty($prd_item) === false) { + $value = $prd_item; + } else { + return false; + } + + return true; + } + + if (isset($reference['fixed_value']) === true) { + $value = $reference['fixed_value']; + return true; + } + + return true; + } /** * Converts a resource into a string. @@ -2005,135 +2454,30 @@ class Prd && empty($value) === false ) { // The column is inside column refs. - if (isset($columns_ref[$column]['ref']) === true) { - // Column ref. - if (isset($columns_ref[$column]['ref']['join']) === true) { - $join_array = $this->recursiveJoin( - $columns_ref[$column]['ref'], - $value - ); - $value = [$columns_ref[$column]['ref']['table'] => $join_array]; - $value = json_encode($value); - } else { - $value = $this->searchValue( - $columns_ref[$column]['ref']['columns'], - $columns_ref[$column]['ref']['table'], - $columns_ref[$column]['ref']['id'], - $value - ); - } - } else if (isset($columns_ref[$column]['conditional_refs']) === true) { - // Conditional refs. - foreach ($columns_ref[$column]['conditional_refs'] as $key => $condition) { - if (isset($condition['when']) === true) { - $control = false; - if ($row[array_key_first($condition['when'])] == reset($condition['when']) - && empty($value) === false - ) { - $control = true; - } - - if ($control === true) { - $value = $this->searchValue( - $condition['ref']['columns'], - $condition['ref']['table'], - $condition['ref']['id'], - $value - ); - break; - } - } - } - } - } else if (isset($json_ref[$column]) === true) { + $this->getReferenceFromValue( + $element['table'], + $column, + $columns_ref[$column], + $row, + $value + ); + } else if (isset($json_ref[$column]) === true + && empty($value) === false + ) { // Json ref. - $json_array = json_decode($value, true); - foreach ($json_ref[$column] as $json_key => $json_values) { - if (empty($json_array[$json_key]) === false) { - if (isset($json_values['conditional_refs']) === true) { - foreach ($json_values['conditional_refs'] as $key => $condition) { - $when = reset($condition['when']); - - $sql_check = sprintf( - 'SELECT * FROM %s WHERE %s=%s AND %s like "%s"', - $when['table'], - $when['id'], - $row[array_key_first($condition['when'])], - array_key_first($when['when']), - reset($when['when']) - ); - - $check = db_get_row_sql($sql_check); - if ($check !== false && isset($condition['ref']) === true) { - if (isset($condition['ref']['join']) === true) { - $join_array = $this->recursiveJoin( - $condition['ref'], - $json_array[$json_key] - ); - $json_array[$json_key] = [$condition['ref']['table'] => $join_array]; - } else { - if (is_array($json_array[$json_key]) === true) { - $implode_where = implode(',', $json_array[$json_key]); - if (empty($implode_where) === false) { - $sql_json = sprintf( - 'SELECT %s FROM %s WHERE %s IN (%s)', - implode( - ',', - $condition['ref']['columns'] - ), - $condition['ref']['table'], - $condition['ref']['id'], - $implode_where - ); - - $value = db_get_row_sql($sql_json); - } else { - $value = false; - } - } else { - $sql_json = sprintf( - 'SELECT %s FROM %s WHERE %s=%s', - implode( - ',', - $condition['ref']['columns'] - ), - $condition['ref']['table'], - $condition['ref']['id'], - $json_array[$json_key] - ); - - $value = db_get_row_sql($sql_json); - } - - if ($value !== false) { - $new_array = []; - $new_array[$condition['ref']['table']] = $value; - $json_array[$json_key] = $new_array; - } - } - - break; - } - } - } else { - $sql_json = sprintf( - 'SELECT %s FROM %s WHERE %s=%s', - implode( - ',', - $json_values['ref']['columns'] - ), - $json_values['ref']['table'], - $json_values['ref']['id'], - $json_array[$json_key] - ); - - $value = db_get_row_sql($sql_json); - $new_array = []; - $new_array[$json_values['ref']['table']] = $value; - $json_array[$json_key] = $new_array; - } - } + $array_value = json_decode($value, true); + foreach($json_ref[$column] as $json_key => $json_ref) { + $json_value = $this->extractJsonArrayValue($array_value, $json_key); + $this->getReferenceFromValue( + $element['table'], + $column, + $json_ref[$column], + $row, + $json_value + ); + $this->updateJsonArrayValue($array_value, $json_key, $json_value); } + $value = json_encode($array_value); } if (!isset($result[$element['table']][$primary_key])) { @@ -2262,199 +2606,54 @@ class Prd $ids = array_shift($internal_array); foreach ($ids as $id) { - $skip_item = false; + $create_item = true; $this->fillCurrentItem($id, $table, $internal_array); foreach ($this->currentItem['parsed'] as $column => $value) { if (isset($column_refs[$column]) === true && empty($value) === false ) { - if (isset($column_refs[$column]['conditional_refs']) === true) { - // Conditional refs. - $prd_item = false; - $conditional = $column_refs[$column]['conditional_refs']; - foreach ($conditional as $key => $condition) { - if (isset($condition['when']) === true) { - $control = false; - if ($this->currentItem['parsed'][array_key_first($condition['when'])] == reset($condition['when']) - && empty($value) === false - ) { - $control = true; - } - - if ($control === true) { - $prd_item = $this->findPrdItem( - $condition['ref'], - $value - ); - break; - } - } - } - - if (isset($condition['ref']['autocreate_item']) === true - && $prd_item === false - ) { - $this->autocreateItem( - $condition['ref'], - $column, - $condition['ref']['autocreate_item'] - ); - } else if (empty($prd_item) === false) { - if (isset($this->base64Refs[$table]) === true - && reset($this->base64Refs[$table]) === $column - ) { - // Base64 ref. - $prd_item = base64_encode($prd_item); - } - - $this->currentItem['parsed'][$column] = $prd_item; - } else { - $skip_item = true; - break; - } - - continue; - } - - if (isset($column_refs[$column]['ref']) === true) { - $ref = $column_refs[$column]['ref']; - $prd_item = $this->findPrdItem($ref, $value); - if (isset($ref['autocreate_item']) === true && $prd_item === false) { - $this->autocreateItem($ref, $column, $ref['autocreate_item']); - } else if (empty($prd_item) === false) { - if (isset($this->base64Refs[$table]) === true - && reset($this->base64Refs[$table]) === $column - ) { - // Base64 ref. - $prd_item = base64_encode($prd_item); - } - - $this->currentItem['parsed'][$column] = $prd_item; - } else { - $skip_item = true; - break; - } - - continue; - } - - if (isset($column_refs[$column]['fixed_value']) === true) { - $this->currentItem['parsed'][$column] = $column_refs[$column]['fixed_value']; - continue; - } + $create_item = $this->getValueFromReference( + $table, + $column, + $column_refs[$column], + $value + ); } else if (isset($json_refs[$column]) === true && empty($value) === false ) { - // Json ref. $array_value = json_decode($value, true); - foreach ($array_value as $key => $val) { - if (isset($json_refs[$column][$key]) === true) { - if (isset($json_refs[$column][$key]['conditional_refs']) === true) { - foreach ($json_refs[$column][$key]['conditional_refs'] as $conditional) { - if (isset($conditional['when']) === true) { - $when = reset($conditional['when']); - if ($this->validateJSON($this->currentItem['parsed'][array_key_first($conditional['when'])]) === true) { - $currentField = json_decode($this->currentItem['parsed'][array_key_first($conditional['when'])], true); - $control = true; - foreach ($when['when'] as $field => $value_when) { - if ($value_when !== $currentField[$when['table']][$field]) { - $control = false; - } - } - - if ($control === true) { - if (isset($conditional['ref'])) { - $prd_item = $this->findPrdItem($conditional['ref'], json_encode($val)); - if (isset($conditional['ref']['autocreate_item']) === true - && $prd_item === false - ) { - $this->autocreateItem($conditional['ref'], $column, $conditional['ref']['autocreate_item']); - } - - if (empty($prd_item) === false) { - $array_value[$key] = $prd_item; - } - - break; - } - } - } else { - // Search in data base. - $sql_condition = sprintf( - 'SELECT * FROM %s WHERE %s=%s AND %s like "%s"', - $when['table'], - $when['id'], - $this->currentItem['parsed'][array_key_first($conditional['when'])], - array_key_first($when['when']), - reset($when['when']) - ); - - $check = db_get_row_sql($sql_condition); - if ($check !== false) { - $prd_item = $this->findPrdItem($conditional['ref'], json_encode($val)); - if (isset($conditional['ref']['autocreate_item']) === true - && $prd_item === false - ) { - $this->autocreateItem($conditional['ref'], $column, $conditional['ref']['autocreate_item']); - } - - if (empty($prd_item) === false) { - $array_value[$key] = $prd_item; - } - - break; - } - } - } - } - - continue; - } - - if (isset($json_refs[$column][$key]['ref']) === true) { - $ref = $json_refs[$column][$key]['ref']; - $prd_item = $this->findPrdItem( - $ref, - json_encode($val) - ); - - if (isset($ref['autocreate_item']) === true - && $prd_item === false - ) { - $this->autocreateItem($ref, $column, $ref['autocreate_item']); - } - - if (empty($prd_item) === false) { - $array_value[$key] = $prd_item; - } - - continue; - } + foreach($json_refs[$column] as $json_key => $json_ref) { + $json_value = $this->extractJsonArrayValue($array_value, $json_key); + if($this->getValueFromReference( + $table, + $column, + $json_refs[$column], + $json_value + ) === true) { + $this->updateJsonArrayValue($array_value, $json_key, $json_value); + } else { + $create_item = false; + break; } } - - $array_value = json_encode($array_value); - - if (isset($this->base64Refs[$table]) === true - && reset($this->base64Refs[$table]) === $column - ) { - // Base64 ref. - $array_value = base64_encode($array_value); - } - - $this->currentItem['parsed'][$column] = $array_value; - } else { - $this->currentItem['parsed'][$column] = $value; + $value = json_encode($array_value); } + + if (isset($this->base64Refs[$table]) === true + && reset($this->base64Refs[$table]) === $column + ) { + // Base64 ref. + $value = base64_encode($value); + } + + $this->currentItem['parsed'][$column] = $value; } - if ($skip_item) { - continue; - } - - if ($this->createItem($table, $crossed_refs) === false) { - $this->setResultStatus(false); - break; + if ($create_item === true) { + if ($this->createItem($table, $crossed_refs) === false) { + $this->setResultStatus(false); + break; + } } } From afb6892ef0d4bbd24c4feab977b83383f431aa88 Mon Sep 17 00:00:00 2001 From: Enrique Martin Date: Wed, 7 Feb 2024 19:32:08 +0100 Subject: [PATCH 22/24] Remove only not ref keys in items creation --- pandora_console/include/class/Prd.class.php | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/pandora_console/include/class/Prd.class.php b/pandora_console/include/class/Prd.class.php index c1b58f71eb..7d7d75d5cd 100644 --- a/pandora_console/include/class/Prd.class.php +++ b/pandora_console/include/class/Prd.class.php @@ -2604,8 +2604,8 @@ class Prd $column_refs = $this->getOneColumnRefs($table); $json_refs = $this->getOneJsonRefs($table); - $ids = array_shift($internal_array); - foreach ($ids as $id) { + $ids = reset($internal_array); + foreach ($ids as $id => $i) { $create_item = true; $this->fillCurrentItem($id, $table, $internal_array); foreach ($this->currentItem['parsed'] as $column => $value) { @@ -3188,6 +3188,15 @@ class Prd { $id = $crossed_refs[$table]['value']; + // Remove primary keys not references + foreach ($id as $id_column) { + if (in_array($id_column, $crossed_refs[$table]['ref']) === false + && isset($this->columnRefs[$table][$id_column]) === false + ) { + unset($this->currentItem['parsed'][$id_column]); + } + } + // Update current item crossed references. if (isset($crossed_refs[$table]) === true && empty($crossed_refs[$table]['ref']) === false From 9901dea9a060cd1f69b23e5639e17720e95f7713 Mon Sep 17 00:00:00 2001 From: Enrique Martin Date: Wed, 7 Feb 2024 21:24:41 +0100 Subject: [PATCH 23/24] Fixed services import when agent not found --- pandora_console/include/class/Prd.class.php | 44 ++++++++++++++++----- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/pandora_console/include/class/Prd.class.php b/pandora_console/include/class/Prd.class.php index 7d7d75d5cd..00500be1f2 100644 --- a/pandora_console/include/class/Prd.class.php +++ b/pandora_console/include/class/Prd.class.php @@ -2337,7 +2337,6 @@ class Prd } else { return false; } - return true; } @@ -2829,7 +2828,7 @@ class Prd 'service_module' => [ 'id_agent' => $this->findPrdItem( $this->tagente, - $current_item['tagente_modulo']['id_agente'] + json_encode($current_item['tagente_modulo']['id_agente']) ), 'interval' => 300, 'status' => AGENT_MODULE_STATUS_NORMAL, @@ -2859,7 +2858,7 @@ class Prd 'fields' => [ 'id_agente_modulo' => &$this->currentItem['last_autocreate'], 'datos' => '', - 'timestamp' => '01-01-1970 00:00:00', + 'timestamp' => '1970-01-01 00:00:00', 'estado' => $autocreate_globals[$autocreate_key]['status'], 'known_status' => $autocreate_globals[$autocreate_key]['status'], 'id_agente' => $autocreate_globals[$autocreate_key]['id_agent'], @@ -2900,7 +2899,7 @@ class Prd 'service_sla_module' => [ 'id_agent' => $this->findPrdItem( $this->tagente, - $current_item['tagente_modulo']['id_agente'] + json_encode($current_item['tagente_modulo']['id_agente']) ), 'interval' => 300, 'status' => AGENT_MODULE_STATUS_NORMAL, @@ -2928,7 +2927,7 @@ class Prd 'fields' => [ 'id_agente_modulo' => &$this->currentItem['last_autocreate'], 'datos' => '', - 'timestamp' => '01-01-1970 00:00:00', + 'timestamp' => '1970-01-01 00:00:00', 'estado' => $autocreate_globals[$autocreate_key]['status'], 'known_status' => $autocreate_globals[$autocreate_key]['status'], 'id_agente' => $autocreate_globals[$autocreate_key]['id_agent'], @@ -2969,7 +2968,7 @@ class Prd 'service_sla_value_module' => [ 'id_agent' => $this->findPrdItem( $this->tagente, - $current_item['tagente_modulo']['id_agente'] + json_encode($current_item['tagente_modulo']['id_agente']) ), 'interval' => 300, 'status' => AGENT_MODULE_STATUS_NORMAL, @@ -2998,7 +2997,7 @@ class Prd 'fields' => [ 'id_agente_modulo' => &$this->currentItem['last_autocreate'], 'datos' => '', - 'timestamp' => '01-01-1970 00:00:00', + 'timestamp' => '1970-01-01 00:00:00', 'estado' => $autocreate_globals[$autocreate_key]['status'], 'known_status' => $autocreate_globals[$autocreate_key]['status'], 'id_agente' => $autocreate_globals[$autocreate_key]['id_agent'], @@ -3228,6 +3227,19 @@ class Prd if (isset($values['pre_items']) === true) { foreach ($values['pre_items'] as $insert) { // Run each INSERT and store each value in $this->currentItem['last_autocreate'] overwriting. + foreach ($insert['fields'] as $insert_f => $insert_v) { + if ($insert_v === false) { + $this->addResultError( + sprintf( + 'Failed when trying to autocreate unexisting item (dependent item not found in pre inserts): table => %s, item => %s, field => %s', + $this->currentItem['table'], + $this->currentItem['id'], + $field + ) + ); + return false; + } + } $insert_query = db_process_sql_insert( $insert['table'], $insert['fields'], @@ -3245,8 +3257,8 @@ class Prd sprintf( 'Failed when trying to autocreate unexisting item: table => %s, item => %s, field => %s', $this->currentItem['table'], - $field, - $this->currentItem['id'] + $this->currentItem['id'], + $field ) ); return false; @@ -3314,6 +3326,20 @@ class Prd if (isset($values['post_updates']) === true) { foreach ($values['post_updates'] as $update) { // Run each UPDATE query. + foreach ($update['fields'] as $update_f => $update_v) { + if ($update_v === false) { + $this->addResultError( + sprintf( + 'Failed when trying to autocreate unexisting item (dependent item not found in post updates): table => %s, item => %s, field => %s', + $this->currentItem['table'], + $this->currentItem['id'], + $field, + ) + ); + return false; + } + } + $update = db_process_sql_update( $update['table'], $update['fields'], From b9d871cbd941058407acce31117442a1b6ecfefc Mon Sep 17 00:00:00 2001 From: Daniel Maya Date: Thu, 8 Feb 2024 09:07:33 +0100 Subject: [PATCH 24/24] #12687 Changes in import dialog --- .../resources/resources_export_import.php | 38 +++++++------------ 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/pandora_console/godmode/resources/resources_export_import.php b/pandora_console/godmode/resources/resources_export_import.php index 721666df05..ac9fdd44a4 100644 --- a/pandora_console/godmode/resources/resources_export_import.php +++ b/pandora_console/godmode/resources/resources_export_import.php @@ -50,13 +50,14 @@ $prd = new Prd(); if (isset($_FILES['resource_import']) === true) { $data = parse_ini_file($_FILES['resource_import']['tmp_name'], true); if ($data !== false) { - $msg = $prd->importPrd($data); - $array_msg = []; - foreach ($msg['items'] as $key => $value) { - $array_msg[$value[0]][key($value[1])][$value[1][key($value[1])]] = $value[1][key($value[1])]; + if (isset($data['prd_data']['name']) === true + && isset($data['prd_data']['type']) === true + ) { + $name = $data['prd_data']['name']; + $type = $data['prd_data']['type']; } - $msg['items'] = $array_msg; + $msg = $prd->importPrd($data); } else { $msg = [ 'status' => false, @@ -141,26 +142,13 @@ html_print_table($table); let title = ""; let message = ""; if (msg.status === true) { - title = ""; - message = ""; - message += "
"; - Object.entries(msg.items).forEach(([table, value]) => { - message += table + " "; - Object.entries(value).forEach(([field, value2]) => { - message += "with " + field + ": ("; - if (typeof value2 === 'object' && Object.keys(value2).length > 0) { - Object.entries(value2).forEach(([key3, value3]) => { - message += value3 + " , "; - }); - } - }); - message = message.substring(0, message.length - 3); - message += ")"; - message += "
"; - }); - + title = ""; + message = ""; + const name = ""; + const type = ""; + message += ` ${type} - ${name}`; } else { - title = ""; + title = ""; Object.entries(msg.errors).forEach(([key, value]) => { message += value + "
"; }); @@ -256,4 +244,4 @@ html_print_table($table); }); } }); - + \ No newline at end of file