From 74b80f68a531a9fc43c57b55163ada3e180cbb24 Mon Sep 17 00:00:00 2001 From: samucarc Date: Thu, 25 Oct 2018 16:52:39 +0200 Subject: [PATCH 001/249] Fixed minor bug in pandora flot js --- pandora_console/include/graphs/flot/pandora.flot.js | 1 + 1 file changed, 1 insertion(+) diff --git a/pandora_console/include/graphs/flot/pandora.flot.js b/pandora_console/include/graphs/flot/pandora.flot.js index 95985cb874..fabfa030a2 100644 --- a/pandora_console/include/graphs/flot/pandora.flot.js +++ b/pandora_console/include/graphs/flot/pandora.flot.js @@ -866,6 +866,7 @@ function pandoraFlotArea( graph_id, values, legend, var unit = params.unit ? params.unit : ''; var homeurl = params.homeurl; var font_size = parseInt(params.font_size); + if (font != undefined) var font = params.font.split("/").pop().split(".").shift(); var width = params.width; var height = params.height; From c05b4c53e82efcd5df56415aae2eb2000ff81ac6 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Fri, 7 Dec 2018 15:12:09 +0100 Subject: [PATCH 002/249] fix bug when updating path of ssl certificate in general setup Former-commit-id: dfe466e64e18c7e3ea949f7786e0ef6343334260 --- pandora_console/godmode/setup/setup_general.php | 5 +++++ pandora_console/include/functions_config.php | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/pandora_console/godmode/setup/setup_general.php b/pandora_console/godmode/setup/setup_general.php index b935f4fc13..285ae1451b 100644 --- a/pandora_console/godmode/setup/setup_general.php +++ b/pandora_console/godmode/setup/setup_general.php @@ -292,6 +292,11 @@ $(document).ready (function () { $("#zone").attr("hidden", false); $("#timezone").attr("hidden", false); }); + + if ($("input[name=use_cert]").is(':checked')) { + $('#setup_general-13').show(); + } + $("input[name=use_cert]").change(function () { if( $(this).is(":checked") ){ var val = $(this).val(); diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index e773224c16..ec6d791d62 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -136,7 +136,7 @@ function config_update_config () { $error_update[] = __('Time source'); if (!config_update_value ('autoupdate', (bool) get_parameter ('autoupdate'))) $error_update[] = __('Automatic check for updates'); - if (!config_update_value ('cert_path', (bool) get_parameter ('cert_path'))) + if (!config_update_value ('cert_path', get_parameter ('cert_path'))) $error_update[] = __('SSL cert path'); if (!config_update_value ('https', (bool) get_parameter ('https'))) $error_update[] = __('Enforce https'); From 0670eb0d29bae1a57e1583111d5c9d34867aca5a Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Mon, 10 Dec 2018 11:04:21 +0100 Subject: [PATCH 003/249] disable double authentication option on user edit when disabled in authentication setup Former-commit-id: 3718da22ded115ae7de492ffbd200d972704865f --- pandora_console/operation/users/user_edit.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/pandora_console/operation/users/user_edit.php b/pandora_console/operation/users/user_edit.php index 2c33acdea6..0626c4de3b 100644 --- a/pandora_console/operation/users/user_edit.php +++ b/pandora_console/operation/users/user_edit.php @@ -376,9 +376,12 @@ $table->data[] = $data; // Double auth $double_auth_enabled = (bool) db_get_value('id', 'tuser_double_auth', 'id_user', $config['id_user']); $data = array(); -$data[0] = ''.__('Double authentication').''; -$data[0] .= $jump; -$data[0] .= ''.html_print_checkbox('double_auth', 1, $double_auth_enabled, true).''; +if ($config['double_auth_enabled']) { + $data[0] = ''.__('Double authentication').''; + $data[0] .= $jump; + $data[0] .= ''.html_print_checkbox('double_auth', 1, $double_auth_enabled, true).''; +} + if ($double_auth_enabled) { $data[0] .= $jump; $data[0] .= html_print_button(__('Show information'), 'show_info', false, 'javascript:show_double_auth_info();', '', true); From 279e94f452dc3b86caf2e35b606239e3bf0a697b Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Tue, 11 Dec 2018 10:30:24 +0100 Subject: [PATCH 004/249] agent named replaced by agent alias in mobile console's alerts view Former-commit-id: 4140bddcf5785f76a948bbe1ba0f694a58c9b50a --- pandora_console/mobile/operation/alerts.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/mobile/operation/alerts.php b/pandora_console/mobile/operation/alerts.php index cf9c89272f..b6a71dddba 100644 --- a/pandora_console/mobile/operation/alerts.php +++ b/pandora_console/mobile/operation/alerts.php @@ -263,7 +263,7 @@ class Alerts { $row = array(); if (isset($this->columns['agent']) && $this->columns['agent']) { - $row[__('Agent')] = sprintf($disabled_style, io_safe_output($alert['agent_name'])); + $row[__('Agent')] = sprintf($disabled_style, io_safe_output($alert['agent_alias'])); } $row[__('Module')] = sprintf($disabled_style, io_safe_output($alert['module_name'])); From dd6c8ca87082f67156a07f68d394926d80a3dc1f Mon Sep 17 00:00:00 2001 From: "manuel.montes" Date: Tue, 11 Dec 2018 16:43:52 +0100 Subject: [PATCH 005/249] Fixed bug in metaconsole custom fields2 Former-commit-id: f96e08279f779d5d64d1ce88f23787f15ac3d144 --- pandora_console/include/functions_events.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php index 591f3ae89d..2ccc38079c 100644 --- a/pandora_console/include/functions_events.php +++ b/pandora_console/include/functions_events.php @@ -39,7 +39,7 @@ function events_get_all_fields() { $columns['estado'] = __('Status'); $columns['timestamp'] = __('Timestamp'); $columns['event_type'] = __('Event type'); - $columns['id_agentmodule'] = __('Agent module'); + $columns['id_agentmodule'] = __('Module name'); $columns['id_alert_am'] = __('Alert'); $columns['criticity'] = __('Severity'); $columns['user_comment'] = __('Comment'); From c5c5ba94034a38d6eea7718f4fb339f4d1dc99f6 Mon Sep 17 00:00:00 2001 From: "manuel.montes" Date: Wed, 12 Dec 2018 12:21:52 +0100 Subject: [PATCH 006/249] Fixed bug in diagnostic info Former-commit-id: 0318eabdf8cbf60267667ba1b4d74d8e476d0b3d --- pandora_console/extras/pandora_diag.php | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/pandora_console/extras/pandora_diag.php b/pandora_console/extras/pandora_diag.php index 29e83182fe..b961c30091 100644 --- a/pandora_console/extras/pandora_diag.php +++ b/pandora_console/extras/pandora_diag.php @@ -122,8 +122,8 @@ function get_logs_size($file){ function get_status_logs($path){ $status_server_log = ""; - $size_server_log = get_logs_size($path); - if ($size_server_log <= 10240){ + $size_server_log = number_format(get_logs_size($path)); + if ($size_server_log <= 1048576){ $status_server_log = "Normal Status   You have less than 10 MB of logs"; }else{ $status_server_log = "Warning Status   You have more than 10 MB of logs"; @@ -344,11 +344,7 @@ render_info_data ("SELECT COUNT(*) FROM tagente","Total agents"); render_info_data ("SELECT COUNT(*) FROM tagente_modulo","Total modules"); render_info_data ("SELECT COUNT(*) FROM tgrupo","Total groups"); render_info_data ("SELECT COUNT(*) FROM tagente_datos","Total module data records"); -// render_info_data ("SELECT COUNT(*) FROM tagente_datos_string","Total module string data records"); -// render_info_data ("SELECT COUNT(*) FROM tagente_datos_log4x","Total module log4x data records"); render_info_data ("SELECT COUNT(*) FROM tagent_access","Total agent access record"); -// render_info ("tagente_estado"); -// render_info ("talert_template_modules"); render_info_data ("SELECT COUNT(*) FROM tevento","Total events"); if($config['enterprise_installed']) @@ -560,7 +556,7 @@ render_row(status_values($read_buffer_size_min_rec_value,$read_buffer_size), 'Re render_row(status_values($read_rnd_buffer_size_min_rec_value,$read_rnd_buffer_size), 'Read rnd-buffer size ','Read rnd-buffer size '); render_row(status_values($query_cache_min_res_unit_min_rec_value,$query_cache_min_res_unit), 'Query cache min-res-unit ','Query cache min-res-unit '); render_row(status_values($innodb_file_per_table_min_rec_value,$innodb_file_per_table), 'InnoDB file per table ','InnoDB file per table '); -echo "".__("Tables fragmentation in the PandoraFMS database").""; +echo "".__("Tables fragmentation in the Pandora FMS database").""; @@ -568,14 +564,14 @@ render_row ($tables_fragmentation_max_rec_value . "%", "Tables fragmentation (ma render_row (number_format($tables_fragmentation, 2) . "%", "Tables fragmentation (current value)"); render_row (status_fragmentation_tables($tables_fragmentation_max_rec_value, $tables_fragmentation), "Status fragmentation tables"); -echo "".__(" PandoraFMS logs dates").""; +echo "".__(" Pandora FMS logs dates").""; -render_row(number_format(get_logs_size($path_server_logs)/1024, 2) . "M", 'Size server logs (current value)'); +render_row(number_format(get_logs_size($path_server_logs)/1048576, 3) . "M", 'Size server logs (current value)'); render_row(get_status_logs($path_server_logs),'Status server logs'); -render_row(number_format(get_logs_size($path_console_logs)/1024, 2) . "M", 'Size console logs (current value)'); +render_row(number_format(get_logs_size($path_console_logs)/1048576, 3) . "M", 'Size console logs (current value)'); render_row(get_status_logs($path_console_logs),'Status console logs'); -echo "".__(" PandoraFMS Licence Information").""; +echo "".__(" Pandora FMS Licence Information").""; render_row( html_print_textarea ('keys[customer_key]', 10, 255, $settings->customer_key, 'style="height:40px; width:450px;"', true),'Customer key'); render_row( $license['expiry_date'],'Expires'); From bc36bb053411dc4b6c4b403aa8e59e481595c127 Mon Sep 17 00:00:00 2001 From: Ramon Novoa Date: Mon, 17 Dec 2018 15:39:44 +0100 Subject: [PATCH 007/249] Add support for exact matches to SNMP alerts. Ref pandora_enterprise#3214. Former-commit-id: 35aa55d4d2ae236e614be7f4db50a9eb9f62aafa --- pandora_console/godmode/snmpconsole/snmp_alert.php | 2 +- pandora_server/lib/PandoraFMS/Core.pm | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pandora_console/godmode/snmpconsole/snmp_alert.php b/pandora_console/godmode/snmpconsole/snmp_alert.php index 870597bee5..b223d8dafe 100755 --- a/pandora_console/godmode/snmpconsole/snmp_alert.php +++ b/pandora_console/godmode/snmpconsole/snmp_alert.php @@ -634,7 +634,7 @@ if ($create_alert || $update_alert) { // OID echo '' . - '' . __('Enterprise String') . '' . + '' . __('Enterprise String') . ui_print_help_tip (__('Matches substrings. End the string with $ for exact matches.'), true) . '' . ''; html_print_input_text ("oid", $oid, '', 50, 255); echo ''; diff --git a/pandora_server/lib/PandoraFMS/Core.pm b/pandora_server/lib/PandoraFMS/Core.pm index c986eb0510..f4485e789b 100644 --- a/pandora_server/lib/PandoraFMS/Core.pm +++ b/pandora_server/lib/PandoraFMS/Core.pm @@ -3400,7 +3400,16 @@ sub pandora_evaluate_snmp_alerts ($$$$$$$$$) { $alert->{'oid'} = decode_entities($alert->{'oid'}); my $oid = $alert->{'oid'}; if ($oid ne '') { - next if (index ($trap_oid, $oid) == -1 && index ($trap_oid_text, $oid) == -1); + my $term = substr($oid, -1); + # Strict match. + if ($term eq '$') { + chop($oid); + next if ($trap_oid ne $oid && $trap_oid_text ne $oid); + } + # Partial match. + else { + next if (index ($trap_oid, $oid) == -1 && index ($trap_oid_text, $oid) == -1); + } $alert_data .= "OID: $oid "; } From e6049870f78f1f84d115667cb0ab44c0dcf89947 Mon Sep 17 00:00:00 2001 From: "manuel.montes" Date: Tue, 18 Dec 2018 12:52:01 +0100 Subject: [PATCH 008/249] Fixed validations and changed alert by dialog Former-commit-id: 4c38c7f665cd328708bca48f997794b9a8586840 --- .../visual_console_builder.editor.js | 498 ++++++++++++++---- .../include/functions_visual_map_editor.php | 95 +++- 2 files changed, 469 insertions(+), 124 deletions(-) diff --git a/pandora_console/godmode/reporting/visual_console_builder.editor.js b/pandora_console/godmode/reporting/visual_console_builder.editor.js index bc573e1b92..f367d6aeaa 100755 --- a/pandora_console/godmode/reporting/visual_console_builder.editor.js +++ b/pandora_console/godmode/reporting/visual_console_builder.editor.js @@ -213,6 +213,20 @@ function is_metaconsole() { return false; } +function dialog_message(message_id){ + $(message_id).css('display', 'inline').dialog({ + modal: true, + show: "blind", + hide: "blind", + buttons:{ + "Close": function(){ + $(this).dialog("close"); + } + } + }); + +} + function update_button_palette_callback() { var values = {}; @@ -223,16 +237,11 @@ function update_button_palette_callback() { switch (selectedItem) { case 'background': if(values['width'] < 1024 || values['height'] < 768){ - alert('Min allowed size is 1024x768'); + dialog_message("#message_min_allowed_size"); return false; } - - if(values['width'] == 0 && values['height'] == 0) { - values['width'] = - $("#hidden-background_original_width").val(); - values['height'] = - $("#hidden-background_original_height").val(); - } + $("#hidden-background_width").val(values['width']); + $("#hidden-background_height").val(values['height']); $("#background").css('width', values['width']); $("#background").css('height', values['height']); @@ -244,11 +253,19 @@ function update_button_palette_callback() { break; case 'box_item': if($('input[name=width_box]').val() == ''){ - alert('Undefined width'); + dialog_message("#message_alert_no_width"); + return false; + } + if (parseInt($("input[name='width_box']").val()) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); return false; } if($('input[name=height_box]').val() == ''){ - alert('Undefined height'); + dialog_message("#message_alert_no_height"); + return false; + } + if (parseInt($("input[name='height_box']").val()) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_height"); return false; } @@ -267,7 +284,7 @@ function update_button_palette_callback() { break; case 'group_item': if((values['image'] == '' || values['image'] == 'none') && (values['label'] == '') && (values['show_statistics'] == false)){ - alert('Undefined image'); + dialog_message("#message_alert_no_image"); return false; } @@ -385,15 +402,31 @@ function update_button_palette_callback() { break; case 'static_graph': if($('input[name=width]').val() == ''){ - alert('Undefined width'); + dialog_message("#message_alert_no_width"); + return false; + } + if (parseInt($("input[name='width']").val()) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); return false; } if($('input[name=height]').val() == ''){ - alert('Undefined height'); + dialog_message("#message_alert_no_height"); + return false; + } + if (parseInt($("input[name='height']").val()) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_height"); + return false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + return false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); return false; } if(((values['image'] == '' || values['image'] == 'none') && (values['label'] == ''))){ - alert('Undefined image'); + dialog_message("#message_alert_no_image"); return false; } @@ -485,13 +518,24 @@ function update_button_palette_callback() { break; case 'percentile_bar': case 'percentile_item': - if($('input[name=width_percentile]').val() == ''){ - alert('Undefined width'); + if($('input[name=height_percentile]').val() == ''){ + dialog_message("#message_alert_no_height"); return false; } - - if($('input[name=height_percentile]').val() == ''){ - alert('Undefined height'); + if($('input[name=width_percentile]').val() == ''){ + dialog_message("#message_alert_no_width"); + return false; + } + if($('input[name=width_percentile]').val() > parseInt($("#hidden-background_width").val())){ + dialog_message("#message_alert_max_width"); + return false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + return false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); return false; } @@ -516,31 +560,42 @@ function update_button_palette_callback() { if($('#dir_items').html() == 'horizontal'){ if(parseInt($('#text-left').val()) + (parseInt($('input[name=height_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('width')) || parseInt($('#text-left').val()) + (parseInt($('input[name=width_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('width'))){ - alert($('#count_items').html()+' joined graph items are wider than background'); return false; - } } - if($('#dir_items').html() == 'vertical'){ if(parseInt($('#text-top').val()) + (parseInt($('input[name=height_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('height'))){ alert($('#count_items').html()+' joined graph items are higher than background'); return false; - } } - + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + return false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); + return false; + } if($('input[name=width_module_graph]').val() == ''){ - alert('Undefined width'); + dialog_message("#message_alert_no_width"); return false; } if($('input[name=height_module_graph]').val() == ''){ - alert('Undefined height'); + dialog_message("#message_alert_no_height"); + return false; + } + if (parseInt(values['width_module_graph']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + return false; + } + if (parseInt($('input[name=height_module_graph]').val()) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); return false; } if($('#custom_graph_row').css('display') != 'none' && $("#custom_graph option:selected").html() == 'None'){ - alert('Undefined graph'); + dialog_message("#message_alert_no_custom_graph"); return false; } @@ -550,12 +605,19 @@ function update_button_palette_callback() { break; case 'bars_graph': if($('input[name=width_percentile]').val() == ''){ - alert('Undefined width'); + dialog_message("#message_alert_no_width"); return false; } - if($('input[name=bars_graph_height]').val() == ''){ - alert('Undefined height'); + dialog_message("#message_alert_no_height"); + return false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + return false; + } + if ((values['agent_string'] == '')) { + dialog_message("#message_alert_no_agent"); return false; } @@ -566,6 +628,10 @@ function update_button_palette_callback() { break; case 'clock': + if (parseInt(values['width_percentile']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + return false; + } $("#text_" + idItem).html(values['label']); $("#image_" + idItem).attr("src", "images/spinner.gif"); @@ -573,12 +639,28 @@ function update_button_palette_callback() { break; case 'auto_sla_graph': - if($('input[name=width]').val() == ''){ - alert('Undefined width'); + if (values['height'] == '') { + dialog_message("#message_alert_no_height"); return false; } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); + if (parseInt(values['height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + return false; + } + if (values['width'] == '') { + dialog_message("#message_alert_no_width"); + return false; + } + if (parseInt(values['width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + return false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + return false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); return false; } $("#text_" + idItem).html(values['label']); @@ -587,8 +669,19 @@ function update_button_palette_callback() { setEventsBar(idItem, values); break; case 'donut_graph': + if (parseInt(values['width_percentile']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + return false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module_string_type"); + return false; + } + if ((values['agent_string'] == '')) { + dialog_message("#message_alert_no_agent"); + return false; + } $("#image_" + idItem).attr("src", "images/spinner.gif"); - setDonutsGraph(idItem, values); break; case 'simple_value': @@ -606,21 +699,41 @@ function update_button_palette_callback() { '
'+values["label"]+'
' ) } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + return false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); + return false; + } break; case 'label': + if ((values['label'] == '')) { + dialog_message("#message_alert_no_label"); + return false; + } $("#text_" + idItem).html(values['label']); break; case 'icon': if($('input[name=width]').val() == ''){ - alert('Undefined width'); + dialog_message("#message_alert_no_width"); return false; } + if (parseInt($('input[name=width]').val()) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + return false; + } if($('input[name=height]').val() == ''){ - alert('Undefined height'); + dialog_message("#message_alert_no_height"); return false; } + if (parseInt($('input[name=height]').val()) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + return false; + } if(values['image'] == '' || values['image'] == 'none'){ - alert('Undefined image'); + dialog_message("#message_alert_no_image"); return false; } $("#image_" + idItem).attr('src', "images/spinner.gif"); @@ -653,14 +766,56 @@ function update_button_palette_callback() { var image = values['image'] + ".png"; set_image("image", idItem, image); break; + case 'line_item': + if (parseInt(values['line_width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + return false; + } + break; + case 'color_cloud': + if (parseInt(values['diameter']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + return false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + return false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); + return false; + } + break; + case 'service': + if (values['height'] == '' || values['height_module_graph'] == 0) { + dialog_message("#message_alert_no_height"); + return false; + } + if (parseInt(values['height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + return false; + } + if (values['width'] == '' || values['width_module_graph'] == 0) { + dialog_message("#message_alert_no_width"); + return false; + } + if (parseInt(values['width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + return false; + } + if($("select[name=service]").val() == '' || $("select[name=service]").val() == 'none'){ + dialog_message("#message_alert_no_service"); + return false; + } + break; default: if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; + dialog_message("#message_alert_no_width"); + return false; } if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; + dialog_message("#message_alert_no_height"); + return false; } //Maybe save in any Enterprise item. if (typeof(enterprise_update_button_palette_callback) == 'function') { @@ -860,144 +1015,288 @@ function create_button_palette_callback() { var validate = true; switch (creationItem) { case 'box_item': - if (($("input[name='width_box']").val() == '')) { - alert('Undefined width'); + if ($("input[name='width_box']").val() == '') { + dialog_message("#message_alert_no_width"); validate = false; } - if (($("input[name='height_box']").val() == '')) { - alert('Undefined height'); + if (parseInt($("input[name='width_box']").val()) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + if ($("input[name='height_box']").val() == '') { + dialog_message("#message_alert_no_height"); + validate = false; + } + if(parseInt($("input[name='height_box']").val()) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); validate = false; } break; case 'group_item': + if (values['height'] == '') { + dialog_message("#message_alert_no_height"); + validate = false; + } + if (parseInt(values['height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + validate = false; + } + if (values['width'] == '') { + dialog_message("#message_alert_no_width"); + validate = false; + } + if (parseInt(values['width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } if((values['image'] == '' || values['image'] == 'none') && (values['label'] == '') && (values['show_statistics'] == false)){ - alert('Undefined images'); + dialog_message("#message_alert_no_image"); validate = false; } break; case 'static_graph': - if ((values['width'] == '')) { - alert('Undefined width'); + + if (values['height'] == '') { + dialog_message("#message_alert_no_height"); validate = false; } - if ((values['height'] == '')) { - alert('Undefined height'); + if (parseInt(values['height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + validate = false; + } + if (values['width'] == '') { + dialog_message("#message_alert_no_width"); + validate = false; + } + if (parseInt(values['width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + validate = false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); validate = false; } if((values['image'] == '' || values['image'] == 'none') && (values['label']) == false){ - alert('Undefined image'); + dialog_message("#message_alert_no_image"); validate = false; } - break; case 'auto_sla_graph': + + if (values['height'] == '') { + dialog_message("#message_alert_no_height"); + validate = false; + } + if (parseInt(values['height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + validate = false; + } + if (values['width'] == '') { + dialog_message("#message_alert_no_width"); + validate = false; + } + if (parseInt(values['width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + validate = false; + } if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); + dialog_message("#message_alert_no_agent"); validate = false; } break; case 'donut_graph': + if (parseInt(values['width_percentile']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module_string_type"); + validate = false; + } if ((values['agent_string'] == '')) { - alert($("#message_alert_no_agent").html()); + dialog_message("#message_alert_no_agent"); validate = false; } break; case 'label': if ((values['label'] == '')) { - alert($("#message_alert_no_label").html()); + dialog_message("#message_alert_no_label"); validate = false; } break; case 'icon': if ((values['width'] == '')) { - alert('Undefined width'); + dialog_message("#message_alert_no_width"); + validate = false; + } + if (parseInt(values['width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); validate = false; } if ((values['height'] == '')) { - alert('Undefined height'); + dialog_message("#message_alert_no_height"); + validate = false; + } + if (parseInt(values['height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); validate = false; } if ((values['image'] == '' || values['image'] == 'none')) { - alert($("#message_alert_no_image").html()); + dialog_message("#message_alert_no_image"); validate = false; } break; case 'percentile_bar': case 'percentile_item': - if ((values['width'] == '')) { - alert('Undefined width'); - validate = false; - } - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - if ((values['max_percentile'] == '')) { - alert($("#message_alert_no_max_percentile").html()); + if (parseInt(values['width_percentile']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); validate = false; } if ((values['width_percentile'] == '')) { - alert($("#message_alert_no_width_percentile").html()); + dialog_message("#message_alert_no_width"); validate = false; } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + validate = false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); + validate = false; + } + + if ((values['max_percentile'] == '')) { + dialog_message("#message_alert_no_max_percentile"); + validate = false; + } + break; case 'module_graph': - if (values['width_module_graph'] == '') { - alert('Undefined width'); - validate = false; - } - if (values['height_module_graph'] == '') { - alert('Undefined height'); + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); validate = false; } if (values['id_custom_graph'] == 0) { if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); + dialog_message("#message_alert_no_agent"); validate = false; } if ((values['period'] == 0)) { - alert($("#message_alert_no_period").html()); + dialog_message("#message_alert_no_period"); validate = false; } } - break; - case 'bars_graph': - if ((values['agent_string'] == '')) { - alert($("#message_alert_no_agent").html()); + if (values['height_module_graph'] == '' || values['height_module_graph'] == 0) { + dialog_message("#message_alert_no_height"); validate = false; } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); + if (parseInt(values['height_module_graph']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + validate = false; + } + if (values['width_module_graph'] == '' || values['width_module_graph'] == 0) { + dialog_message("#message_alert_no_width"); + validate = false; + } + if (parseInt(values['width_module_graph']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + break; + case 'bars_graph': + if ((values['bars_graph_height'] == '')) { + dialog_message("#message_alert_no_height"); + validate = false; + } + if (parseInt(values['bars_graph_height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); validate = false; } if ((values['width_percentile'] == '')) { - alert($("#message_alert_no_width_percentile").html()); + dialog_message("#message_alert_no_width"); validate = false; } - if ((values['bars_graph_height'] == '')) { - alert($("#message_alert_no_bars_graph_height").html()); + if (parseInt(values['width_percentile']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + validate = false; + } + if ((values['agent_string'] == '')) { + dialog_message("#message_alert_no_agent"); validate = false; } break; case 'simple_value': - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); validate = false; } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); validate = false; } break; + case 'clock': + if (parseInt(values['width_percentile']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + break; + case 'line_item': + if (parseInt(values['line_width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + break; + case 'color_cloud': + if (parseInt(values['diameter']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + validate = false; + } + if ((values['module'] == 0)) { + dialog_message("#message_alert_no_module"); + validate = false; + } + if ((values['agent'] == '')) { + dialog_message("#message_alert_no_agent"); + validate = false; + } + break; + case 'service': + if (values['height'] == '' || values['height_module_graph'] == 0) { + dialog_message("#message_alert_no_height"); + validate = false; + } + if (parseInt(values['height']) > parseInt($("#hidden-background_height").val())) { + dialog_message("#message_alert_max_height"); + validate = false; + } + if (values['width'] == '' || values['width_module_graph'] == 0) { + dialog_message("#message_alert_no_width"); + validate = false; + } + if (parseInt(values['width']) > parseInt($("#hidden-background_width").val())) { + dialog_message("#message_alert_max_width"); + validate = false; + } + if($("select[name=service]").val() == '' || $("select[name=service]").val() == 'none'){ + dialog_message("#message_alert_no_service"); + validate = false; + } + break; + default: //Maybe save in any Enterprise item. if (typeof(enterprise_create_button_palette_callback) == 'function') { @@ -3603,7 +3902,6 @@ function createItem(type, values, id_data) { case 'clock': sizeStyle = ''; imageSize = ''; - if(values['label_position'] == 'up'){ item = $('
' + '
' + values['label'] + '
' + diff --git a/pandora_console/include/functions_visual_map_editor.php b/pandora_console/include/functions_visual_map_editor.php index 4b835d65fc..64d974c131 100755 --- a/pandora_console/include/functions_visual_map_editor.php +++ b/pandora_console/include/functions_visual_map_editor.php @@ -1136,31 +1136,78 @@ function visual_map_editor_print_hack_translate_strings() { echo ''; //Hack to translate messages in javascript - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; + + echo""; - echo ''; - echo ''; } ?> From f60b55ac2b375b5cda32cd3a9c0eb857b3267caa Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Wed, 19 Dec 2018 13:14:09 +0100 Subject: [PATCH 009/249] fix metaconsole sql items creation Former-commit-id: 68e45006b53599e3f59322fe08cf5a93df747c32 --- .../godmode/reporting/reporting_builder.php | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/pandora_console/godmode/reporting/reporting_builder.php b/pandora_console/godmode/reporting/reporting_builder.php index 229c5ab56f..4605e9a3d9 100755 --- a/pandora_console/godmode/reporting/reporting_builder.php +++ b/pandora_console/godmode/reporting/reporting_builder.php @@ -1473,16 +1473,6 @@ switch ($action) { $values['server_name'] = get_parameter ('combo_server'); - if (is_metaconsole()) { - // For SQL Query check if it is setted in the meta - if ($values['type'] == "sql") { - if (empty($values['server_name'])) { - $good_format = false; - } - } - } - - $values['id_agent'] = get_parameter('id_agent'); $values['id_gs'] = get_parameter('id_custom_graph'); if (($values['type'] == 'alert_report_agent') or ($values['type'] == 'event_report_agent') or ($values['type'] == 'agent_configuration') or ($values['type'] == 'group_configuration')) From 91e90a1b26367c812b2515a2e5b972ac91e8f440 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Thu, 20 Dec 2018 13:35:57 +0100 Subject: [PATCH 010/249] remove special characters from agent alias string on creation and trim blank spaces from beginning and end of alias string Former-commit-id: 2294ef705ac0df638bc897f56ff9e9beff8379fc --- pandora_console/godmode/agentes/configurar_agente.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index fab0ad7637..2c4931e267 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -157,7 +157,7 @@ $module_macros = array (); // Create agent if ($create_agent) { $mssg_warning = 0; - $alias = (string) get_parameter_post("alias",''); + $alias = trim (preg_replace('/[\/\\\|%#&$-]/', '', html_entity_decode( str_replace('`','‘',(string) get_parameter_post ("alias", ""))))); $alias_as_name = (int) get_parameter_post("alias_as_name", 0); $direccion_agente = (string) get_parameter_post("direccion",''); @@ -709,7 +709,7 @@ if ($update_agent) { // if modified some agent paramenter $mssg_warning = 0; $id_agente = (int) get_parameter_post ("id_agente"); $nombre_agente = str_replace('`','‘',(string) get_parameter_post ("agente", "")); - $alias = str_replace('`','‘',(string) get_parameter_post ("alias", "")); + $alias = trim (preg_replace('/[\/\\\|%#&$-]/', '', html_entity_decode( str_replace('`','‘',(string) get_parameter_post ("alias", ""))))); $alias_as_name = (int) get_parameter_post ('alias_as_name', 0); $direccion_agente = (string) get_parameter_post ("direccion", ''); //safe_output only validate ip From 471c01a4c52d2876f7c3eef414652a8aad80cada Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Wed, 9 Jan 2019 10:20:17 +0100 Subject: [PATCH 011/249] fixed bad link to node in metaconsole's custom graph item editor Former-commit-id: 22fb4302de980d8b3e16fb90d087b71c218598a1 --- .../godmode/reporting/reporting_builder.item_editor.php | 2 +- pandora_console/include/ajax/reporting.ajax.php | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/pandora_console/godmode/reporting/reporting_builder.item_editor.php b/pandora_console/godmode/reporting/reporting_builder.item_editor.php index a929740e39..4f4b5e7c22 100755 --- a/pandora_console/godmode/reporting/reporting_builder.item_editor.php +++ b/pandora_console/godmode/reporting/reporting_builder.item_editor.php @@ -2492,7 +2492,7 @@ function edit_custom_graph() { } }); - window.location.href = server_url + "/index.php?sec=reporting&sec2=godmode/reporting/graph_builder&edit_graph=1&id=" + id_element_graph + hash_data; + window.location.href = server_url + "index.php?sec=reporting&sec2=godmode/reporting/graph_builder&edit_graph=1&id=" + id_element_graph + hash_data; Date: Wed, 9 Jan 2019 16:20:24 +0100 Subject: [PATCH 012/249] Added option in setup for unique main IP in agents - #1744 Former-commit-id: f8f9668a14818a01b811a73052e2e7e82e9a8c7a --- .../godmode/agentes/agent_manager.php | 4 +++- .../godmode/agentes/configurar_agente.php | 22 ++++++++++++++++++- .../godmode/setup/setup_general.php | 5 +++++ pandora_console/include/functions_config.php | 10 +++++++-- 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index f94cb7737b..40469f75b2 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -228,7 +228,9 @@ if($new_agent){ } $table->data[2][0] = __('IP Address'); -$table->data[2][1] = html_print_input_text ('direccion', $direccion_agente, '', 16, 100, true); +$table->data[2][1] = html_print_input_text ('direccion', $direccion_agente, '', 16, 100, true). + html_print_checkbox ("unique_ip", 1, $config['unique_ip'], true).__('Unique IP') . + ui_print_help_tip (__("Set the primary IP address as the unique IP, preventing the same primary IP address from being used in more than one agent"), true); if ($id_agente) { $table->data[2][1] .= '    '; diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index fab0ad7637..92c3cc4b73 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -81,6 +81,7 @@ $alias_as_name = 0; $direccion_agente = get_parameter('direccion', ''); $direccion_agente = trim(io_safe_output($direccion_agente)); $direccion_agente = io_safe_input($direccion_agente); +$unique_ip = 0; $intervalo = SECONDS_5MINUTES; $ff_interval = 0; $quiet_module = 0; @@ -160,6 +161,7 @@ if ($create_agent) { $alias = (string) get_parameter_post("alias",''); $alias_as_name = (int) get_parameter_post("alias_as_name", 0); $direccion_agente = (string) get_parameter_post("direccion",''); + $unique_ip = (int) get_parameter_post("unique_ip", 0); //safe_output only validate ip $direccion_agente = trim(io_safe_output($direccion_agente)); @@ -214,7 +216,12 @@ if ($create_agent) { $nombre_agente = $alias; } - if(!$exists_alias){ + if($unique_ip && $direccion_agente != ''){ + $sql = 'SELECT direccion FROM tagente WHERE direccion = "' . $direccion_agente . '"'; + $exists_ip = db_get_row_sql($sql); + } + + if(!$exists_alias && !$exists_ip){ $id_agente = db_process_sql_insert ( 'tagente', array ( @@ -304,6 +311,9 @@ if ($create_agent) { if($exists_alias){ $agent_creation_error = __('Could not be created, because name already exists'); } + elseif($exists_ip){ + $agent_creation_error = __('Could not be created, because IP already exists'); + } } } } @@ -712,6 +722,7 @@ if ($update_agent) { // if modified some agent paramenter $alias = str_replace('`','‘',(string) get_parameter_post ("alias", "")); $alias_as_name = (int) get_parameter_post ('alias_as_name', 0); $direccion_agente = (string) get_parameter_post ("direccion", ''); + $unique_ip = (int) get_parameter_post ('unique_ip', 0); //safe_output only validate ip $direccion_agente = trim(io_safe_output($direccion_agente)); @@ -795,9 +806,18 @@ if ($update_agent) { // if modified some agent paramenter ui_print_error_message(__('No agent alias specified')); //If there is an agent with the same name, but a different ID } + + if($unique_ip && $direccion_agente != ''){ + $sql = 'SELECT direccion FROM tagente WHERE direccion = "' . $direccion_agente . '"'; + $exists_ip = db_get_row_sql($sql); + } + if ($grupo <= 0) { ui_print_error_message(__('The group id %d is incorrect.', $grupo)); } + elseif($exists_ip){ + ui_print_error_message(__('Duplicate main IP address')); + } else { //If different IP is specified than previous, add the IP if ($direccion_agente != '' && diff --git a/pandora_console/godmode/setup/setup_general.php b/pandora_console/godmode/setup/setup_general.php index b935f4fc13..aedeec5173 100644 --- a/pandora_console/godmode/setup/setup_general.php +++ b/pandora_console/godmode/setup/setup_general.php @@ -230,6 +230,11 @@ $table->data[38][0] = __('Set alias as name by default in agent creation'); $table->data[38][1] = __('Yes').'   '.html_print_radio_button ('alias_as_name', 1, '', $config["alias_as_name"], true).'  '; $table->data[38][1] .= __('No').'   '.html_print_radio_button ('alias_as_name', 0, '', $config["alias_as_name"], true); +$table->data[39][0] = __('Unique IP') . + ui_print_help_tip (__("Set the primary IP address as the unique IP, preventing the same primary IP address from being used in more than one agent"), true); +$table->data[39][1] = __('Yes').'   '.html_print_radio_button ('unique_ip', 1, '', $config["unique_ip"], true).'  '; +$table->data[39][1] .= __('No').'   '.html_print_radio_button ('unique_ip', 0, '', $config["unique_ip"], true); + echo '
'; echo "
"; diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index bd0c78bd76..a1f2320d9f 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -204,10 +204,12 @@ function config_update_config () { $error_update[] = __('Identification_reminder'); if (!config_update_value ('include_agents', (bool)get_parameter('include_agents'))) $error_update[] = __('Include_agents'); - if (!config_update_value ('alias_as_name', get_parameter('alias_as_name'))) - $error_update[] = __('alias_as_name'); + if (!config_update_value ('alias_as_name', get_parameter('alias_as_name'))) + $error_update[] = __('alias_as_name'); if (!config_update_value ('auditdir', get_parameter('auditdir'))) $error_update[] = __('Audit log directory'); + if (!config_update_value ('unique_ip', get_parameter('unique_ip'))) + $error_update[] = __('unique_ip'); break; case 'enterprise': if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { @@ -1123,6 +1125,10 @@ function config_process_config () { config_update_value ('limit_parameters_massive', ini_get("max_input_vars") / 2); } + if (!isset ($config["unique_ip"])) { + config_update_value ('unique_ip', 0); + } + /* *Parse the ACL IP list for access API */ From ff85a4a8d534fb50503877cb89df20ae897c2d14 Mon Sep 17 00:00:00 2001 From: samucarc Date: Tue, 15 Jan 2019 13:10:13 +0100 Subject: [PATCH 013/249] Eliminated message when secondary groups are added Former-commit-id: 07a6e423a66830543126444a5b4f54c196818e63 --- pandora_console/godmode/agentes/configurar_agente.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index fab0ad7637..44e6bf3c00 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -847,7 +847,7 @@ if ($update_agent) { // if modified some agent paramenter $result = db_process_sql_update ('tagente', $values, array ('id_agente' => $id_agente)); - if ($result == false && $update_custom_result == false) { + if ($result === false && $update_custom_result == false) { ui_print_error_message( __('There was a problem updating the agent')); } From e316977d4b407bd7ae393d087de35bf930c7d947 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Wed, 16 Jan 2019 12:23:19 +0100 Subject: [PATCH 014/249] Refactorize and add two new fields to api_get_groups api function Former-commit-id: 2d59091279c284d549c09744ee61c8fee1e33564 --- pandora_console/include/functions_api.php | 34 +++++++++++------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/pandora_console/include/functions_api.php b/pandora_console/include/functions_api.php index 53479ae7ed..aa21faad1a 100644 --- a/pandora_console/include/functions_api.php +++ b/pandora_console/include/functions_api.php @@ -283,30 +283,28 @@ function api_get_test_event_replication_db() { //-------------------------DEFINED OPERATIONS FUNCTIONS----------------- function api_get_groups($thrash1, $thrash2, $other, $returnType, $user_in_db) { - if (defined ('METACONSOLE')) { - return; - } - if ($other['type'] == 'string') { - if ($other['data'] != '') { - returnError('error_parameter', 'Error in the parameters.'); - return; - } - else {//Default values - $separator = ';'; - } - } - else if ($other['type'] == 'array') { - $separator = $other['data'][0]; - } - - $groups = users_get_groups ($user_in_db, "IR"); + $returnAllGroup = true; + $returnAllColumns = false; + + if (isset($other['data'][1])) + $returnAllGroup = ( $other['data'][1] == '1' ? true : false); + + if (isset($other['data'][2])) + $returnAllColumns = ( $other['data'][2] == '1' ? true : false); + + $groups = users_get_groups ($user_in_db, "IR", $returnAllGroup, $returnAllColumns); $data_groups = array(); foreach ($groups as $id => $group) { $data_groups[] = array($id, $group); } - + + if (!isset($other['data'][0])) + $separator = ';'; // by default + else + $separator = $other['data'][0]; + $data['type'] = 'array'; $data['data'] = $data_groups; From 2155420d71f75f6c6448f6bda5591335fea8459e Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Fri, 18 Jan 2019 11:13:29 +0100 Subject: [PATCH 015/249] implement custom fields for node monitor view Former-commit-id: d9dd515a726d1fa7cc5855b016270b9ef083cb6f --- .../agentes/status_monitor_custom_fields.php | 240 +++++ .../operation/agentes/status_monitor.php | 939 ++++++++++-------- pandora_console/pandoradb_data.sql | 1 + 3 files changed, 757 insertions(+), 423 deletions(-) create mode 100644 pandora_console/godmode/agentes/status_monitor_custom_fields.php diff --git a/pandora_console/godmode/agentes/status_monitor_custom_fields.php b/pandora_console/godmode/agentes/status_monitor_custom_fields.php new file mode 100644 index 0000000000..e01839c40a --- /dev/null +++ b/pandora_console/godmode/agentes/status_monitor_custom_fields.php @@ -0,0 +1,240 @@ + 'status_monitor_fields', + 'value' => $status_monitor_fields + ); + + //update 'status_monitor_fields' in tconfig table to keep the value at update. + $result = db_process_sql_update('tconfig', $values, + array ('token' => 'status_monitor_fields')); + + ui_print_result_message ($result, __('Successfully updated'), __('Could not be updated')); + + $config['status_monitor_fields'] = $status_monitor_fields; +} + +$fields_selected = array(); +$status_monitor_fields = ''; +$fields_selected = explode (',', $config['status_monitor_fields']); + +$result_selected = array(); + +//show list of fields selected. +if ($fields_selected[0]!='') { + foreach ($fields_selected as $field_selected) { + switch ($field_selected) { + case 'policy': + $result = __('Policy'); + break; + case 'agent': + $result = __('Agent'); + break; + case 'data_type': + $result = __('Data type'); + break; + case 'module_name': + $result = __('Module name'); + break; + case 'server_type': + $result = __('Server type'); + break; + case 'interval': + $result = __('Interval'); + break; + case 'status': + $result = __('Status'); + break; + case 'graph': + $result = __('Graph'); + break; + case 'warn': + $result = __('Warn'); + break; + case 'data': + $result = __('Data'); + break; + case 'timestamp': + $result = __('Timestamp'); + break; + case 'to_critical': + $result = __('Went to critical'); + break; + } + $result_selected[$field_selected] = $result; + } +} + +echo '

'.__('Show monitor detail fields').'

'; + +$table = new stdClass(); +$table->width = '100%'; +$table->class = 'databox filters'; + +$table->size = array(); +//~ $table->size[0] = '20%'; +$table->size[1] = '10px'; +//~ $table->size[2] = '20%'; + +$table->style[0] = 'text-align:center;'; +$table->style[2] = 'text-align:center;'; + +$table->data = array(); + +$fields_available = array(); + +$fields_available['policy'] = __('Policy'); +$fields_available['agent'] = __('Agent'); +$fields_available['data_type'] = __('Data type'); +$fields_available['module_name'] = __('Module name'); +$fields_available['server_type'] = __('Server type'); +$fields_available['interval'] = __('Interval'); +$fields_available['status'] = __('Status'); +$fields_available['graph'] = __('Graph'); +$fields_available['warn'] = __('Warn'); +$fields_available['data'] = __('Data'); +$fields_available['timestamp'] = __('Timestamp'); +$fields_available['to_critical'] = __('Went to critical'); + +//remove fields already selected +foreach ($fields_available as $key=>$available) { + foreach ($result_selected as $selected) { + if ($selected == $available) { + unset($fields_available[$key]); + } + } +} + +$table->data[0][0] = '' . __('Fields available').''; +$table->data[1][0] = html_print_select ($fields_available, 'fields_available[]', true, '', '', 0, true, true, false, '', false, 'width: 300px'); +$table->data[1][1] = '' . + html_print_image('images/darrowright.png', true, + array('id' => 'right', 'title' => __('Add fields to select'))) . + ''; +$table->data[1][1] .= '



' . + html_print_image('images/darrowleft.png', true, + array('id' => 'left', 'title' => __('Delete fields to select'))) . + ''; + +$table->data[0][1] = ''; +$table->data[0][2] = '' . __('Fields selected') . ''; +$table->data[1][2] = html_print_select($result_selected, + 'fields_selected[]', true, '', '', 0, true, true, false, '', false, 'width: 300px'); + +echo ''; +html_print_table($table); + +echo '
'; + html_print_submit_button (__('Update'), 'upd_button', false, 'class="sub upd"'); +echo ''; +echo '
'; +?> + + diff --git a/pandora_console/operation/agentes/status_monitor.php b/pandora_console/operation/agentes/status_monitor.php index 724feb4aea..dff51edd17 100644 --- a/pandora_console/operation/agentes/status_monitor.php +++ b/pandora_console/operation/agentes/status_monitor.php @@ -36,9 +36,38 @@ enterprise_include_once ('include/functions_metaconsole.php'); $isFunctionPolicies = enterprise_include_once ('include/functions_policies.php'); if (! defined ('METACONSOLE')) { - //Header - ui_print_page_header (__('Monitor detail'), - 'images/brick.png', false); + + $section = (string) get_parameter ("section", "view"); + + + $buttons['fields'] = array('active' => false, + 'text' => '' . + html_print_image("images/custom_columns.png", true, array("title" => __('Custom fields'))) . '', + 'operation' => true); + + $buttons['view'] = array('active' => false, + 'text' => '' . + html_print_image("images/list.png", true, array("title" => __('View'))) . '', + 'operation' => true); + + + switch ($section) { + case 'fields': + $buttons['fields']['active'] = true; + $subpage = ' - ' . __('Custom fields'); + break; + default: + $buttons['view']['active'] = true; + break; + } + + ui_print_page_header (__("Monitor detail") . $subpage, "", false, "", true, $buttons); + + if ($section == 'fields') { + require_once($config["homedir"] . '/godmode/agentes/status_monitor_custom_fields.php'); + exit(); + } + } else { @@ -882,60 +911,90 @@ if (!empty($result)) { $table->size = array (); $table->align = array (); - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) - $table->head[0] = '' . __('P.') . ''; +$show_fields = explode (',', $config['status_monitor_fields']); - $table->head[1] = __('Agent'); - $table->head[1] .=' ' . html_print_image('images/sort_up.png', true, array('style' => $selectAgentNameUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectAgentNameDown, 'alt' => 'down')) . ''; - $table->head[2] = __('Data Type'); - $table->head[2] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectTypeUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectTypeDown, 'alt' => 'down')) . ''; - - $table->align[2] = 'left'; - - $table->head[3] = __('Module name'); - $table->head[3] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectModuleNameUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectModuleNameDown, 'alt' => 'down')) . ''; - - $table->head[4] = __('Server type'); - $table->head[4] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectModuleNameUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectModuleNameDown, 'alt' => 'down')) . ''; - - $table->head[5] = __('Interval'); - $table->head[5] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectIntervalUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectIntervalDown, 'alt' => 'down')) . ''; - $table->align[5] = 'left'; - - $table->head[6] = __('Status'); - $table->head[6] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectStatusDown, 'alt' => 'down')) . ''; - - $table->align[6] = 'left'; - - $table->head[7] = __('Graph'); - $table->align[7] = 'left'; - - $table->head[8] = __('Warn'); - $table->align[8] = 'left'; - - $table->head[9] = __('Data'); - $table->align[9] = 'left'; - if ( is_metaconsole() ) { - $table->head[9] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectStatusDown, 'alt' => 'down')) . ''; + if (in_array('policy', $show_fields)) { + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) + $table->head[0] = '' . __('P.') . ''; } - $table->head[10] = __('Timestamp'); - $table->head[10] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectTimestampUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectTimestampDown, 'alt' => 'down')) . ''; - $table->align[10] = 'left'; + if (in_array('agent', $show_fields) || is_metaconsole()) { + $table->head[1] = __('Agent'); + $table->head[1] .=' ' . html_print_image('images/sort_up.png', true, array('style' => $selectAgentNameUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectAgentNameDown, 'alt' => 'down')) . ''; + } + + if (in_array('data_type', $show_fields) || is_metaconsole()) { + $table->head[2] = __('Data Type'); + $table->head[2] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectTypeUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectTypeDown, 'alt' => 'down')) . ''; + + $table->align[2] = 'left'; + } + + if (in_array('module_name', $show_fields) || is_metaconsole()) { + $table->head[3] = __('Module name'); + $table->head[3] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectModuleNameUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectModuleNameDown, 'alt' => 'down')) . ''; + } + + if (in_array('server_type', $show_fields) || is_metaconsole()) { + $table->head[4] = __('Server type'); + $table->head[4] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectModuleNameUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectModuleNameDown, 'alt' => 'down')) . ''; + } + + if (in_array('interval', $show_fields) || is_metaconsole()) { + $table->head[5] = __('Interval'); + $table->head[5] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectIntervalUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectIntervalDown, 'alt' => 'down')) . ''; + $table->align[5] = 'left'; + } + + if (in_array('status', $show_fields) || is_metaconsole()) { + $table->head[6] = __('Status'); + $table->head[6] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectStatusDown, 'alt' => 'down')) . ''; + + $table->align[6] = 'left'; + } + + if (in_array('graph', $show_fields) || is_metaconsole()) { + $table->head[7] = __('Graph'); + $table->align[7] = 'left'; + } + + if (in_array('warn', $show_fields) || is_metaconsole()) { + $table->head[8] = __('Warn'); + $table->align[8] = 'left'; + } + + if (in_array('data', $show_fields) || is_metaconsole()) { + $table->head[9] = __('Data'); + $table->align[9] = 'left'; + if ( is_metaconsole() ) { + $table->head[9] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectStatusDown, 'alt' => 'down')) . ''; + } + } + + if (in_array('timestamp', $show_fields) || is_metaconsole()) { + $table->head[10] = __('Timestamp'); + $table->head[10] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectTimestampUp, 'alt' => 'up')) . '' . + '' . html_print_image('images/sort_down.png', true, array('style' => $selectTimestampDown, 'alt' => 'down')) . ''; + $table->align[10] = 'left'; + } + + if (in_array('to_critical', $show_fields)) { + $table->head[11] = __('Went to critical'); + } $id_type_web_content_string = db_get_value('id_tipo', 'ttipo_modulo', 'nombre', 'web_content_string'); foreach ($result as $row) { + //Avoid unset, null and false value if (empty($row['server_name'])) $row['server_name'] = ""; @@ -957,440 +1016,474 @@ if (!empty($result)) { } $data = array (); - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { - if(is_metaconsole()){ - $node = metaconsole_get_connection_by_id($row['server_id']); - if (metaconsole_load_external_db($node) !== NOERR) { - // Restore the default connection. - metaconsole_restore_db(); - $errors++; - break; - } - } - $policyInfo = policies_info_module_policy($row['id_agente_modulo']); - - if ($policyInfo === false) - $data[0] = ''; - else { - $linked = policies_is_module_linked($row['id_agente_modulo']); - - $adopt = false; - if (policies_is_module_adopt($row['id_agente_modulo'])) { - $adopt = true; + if (in_array('policy', $show_fields) || is_metaconsole()) { + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { + if(is_metaconsole()){ + $node = metaconsole_get_connection_by_id($row['server_id']); + if (metaconsole_load_external_db($node) !== NOERR) { + // Restore the default connection. + metaconsole_restore_db(); + $errors++; + break; + } } - if ($linked) { - if ($adopt) { - $img = 'images/policies_brick.png'; - $title = __('(Adopt) ') . $policyInfo['name_policy']; + $policyInfo = policies_info_module_policy($row['id_agente_modulo']); + + if ($policyInfo === false) + $data[0] = ''; + else { + $linked = policies_is_module_linked($row['id_agente_modulo']); + + $adopt = false; + if (policies_is_module_adopt($row['id_agente_modulo'])) { + $adopt = true; + } + + if ($linked) { + if ($adopt) { + $img = 'images/policies_brick.png'; + $title = __('(Adopt) ') . $policyInfo['name_policy']; + } + else { + $img = 'images/policies.png'; + $title = $policyInfo['name_policy']; + } } else { - $img = 'images/policies.png'; - $title = $policyInfo['name_policy']; + if ($adopt) { + $img = 'images/policies_not_brick.png'; + $title = __('(Unlinked) (Adopt) ') . $policyInfo['name_policy']; + } + else { + $img = 'images/unlinkpolicy.png'; + $title = __('(Unlinked) ') . $policyInfo['name_policy']; + } } + if(is_metaconsole()){ + $data[0] = '' . + html_print_image($img,true, array('title' => $title)) . + ''; + } + else{ + $data[0] = '' . + html_print_image($img,true, array('title' => $title)) . + ''; + } + } + + if(is_metaconsole()){ + metaconsole_restore_db(); + } + } + } + + if (in_array('agent', $show_fields) || is_metaconsole()) { + $agent_alias = !empty($row['agent_alias']) ? $row['agent_alias'] : $row['agent_name']; + + // TODO: Calculate hash access before to use it more simply like other sections. I.E. Events view + if (defined('METACONSOLE')) { + $agent_link = ''; + $agent_alias = ui_print_truncate_text($agent_alias, + 'agent_small', false, true, false, '[…]', + 'font-size:7.5pt;'); + if (can_user_access_node ()) { + $data[1] = $agent_link . '' . $agent_alias . ''; } else { - if ($adopt) { - $img = 'images/policies_not_brick.png'; - $title = __('(Unlinked) (Adopt) ') . $policyInfo['name_policy']; - } - else { - $img = 'images/unlinkpolicy.png'; - $title = __('(Unlinked) ') . $policyInfo['name_policy']; - } + $data[1] = $agent_alias; } - if(is_metaconsole()){ - $data[0] = '' . - html_print_image($img,true, array('title' => $title)) . - ''; - } - else{ - $data[0] = '' . - html_print_image($img,true, array('title' => $title)) . - ''; - } - } - - if(is_metaconsole()){ - metaconsole_restore_db(); - } - } - - $agent_alias = !empty($row['agent_alias']) ? $row['agent_alias'] : $row['agent_name']; - - // TODO: Calculate hash access before to use it more simply like other sections. I.E. Events view - if (defined('METACONSOLE')) { - $agent_link = ''; - $agent_alias = ui_print_truncate_text($agent_alias, - 'agent_small', false, true, false, '[…]', - 'font-size:7.5pt;'); - if (can_user_access_node ()) { - $data[1] = $agent_link . '' . $agent_alias . ''; } else { - $data[1] = $agent_alias; + $data[1] = ''; + $data[1] .= ui_print_truncate_text($agent_alias, 'agent_medium', false, true, false, '[…]', 'font-size:7.5pt;'); + $data[1] .= ''; } } - else { - $data[1] = ''; - $data[1] .= ui_print_truncate_text($agent_alias, 'agent_medium', false, true, false, '[…]', 'font-size:7.5pt;'); - $data[1] .= ''; - } - - $data[2] = html_print_image('images/' . modules_show_icon_type ($row['module_type']), true); - $agent_groups = is_metaconsole() - ? $row['groups_in_server'] - : agents_get_all_groups_agent($row['id_agent'], $row['id_group']); - if (check_acl_one_of_groups ($config['id_user'], $agent_groups, 'AW')) { - $show_edit_icon = true; - if (defined('METACONSOLE')) { - if (!can_user_access_node ()) { - $show_edit_icon = false; + if (in_array('data_type', $show_fields) || is_metaconsole()) { + $data[2] = html_print_image('images/' . modules_show_icon_type ($row['module_type']), true); + $agent_groups = is_metaconsole() + ? $row['groups_in_server'] + : agents_get_all_groups_agent($row['id_agent'], $row['id_group']); + if (check_acl_one_of_groups ($config['id_user'], $agent_groups, 'AW')) { + $show_edit_icon = true; + if (defined('METACONSOLE')) { + if (!can_user_access_node ()) { + $show_edit_icon = false; + } + + $url_edit_module = $row['server_url'] . 'index.php?' . + 'sec=gagente&' . + 'sec2=godmode/agentes/configurar_agente&' . + 'id_agente=' . $row['id_agent'] . '&' . + 'tab=module&' . + 'id_agent_module=' . $row['id_agente_modulo'] . '&' . + 'edit_module=1' . + '&loginhash=auto&loginhash_data=' . $row['hashdata'] . '&loginhash_user=' . str_rot13($row['user']); + } + else { + $url_edit_module = 'index.php?' . + 'sec=gagente&' . + 'sec2=godmode/agentes/configurar_agente&' . + 'id_agente=' . $row['id_agent'] . '&' . + 'tab=module&' . + 'id_agent_module=' . $row['id_agente_modulo'] . '&' . + 'edit_module=1'; } - $url_edit_module = $row['server_url'] . 'index.php?' . - 'sec=gagente&' . - 'sec2=godmode/agentes/configurar_agente&' . - 'id_agente=' . $row['id_agent'] . '&' . - 'tab=module&' . - 'id_agent_module=' . $row['id_agente_modulo'] . '&' . - 'edit_module=1' . - '&loginhash=auto&loginhash_data=' . $row['hashdata'] . '&loginhash_user=' . str_rot13($row['user']); - } - else { - $url_edit_module = 'index.php?' . - 'sec=gagente&' . - 'sec2=godmode/agentes/configurar_agente&' . - 'id_agente=' . $row['id_agent'] . '&' . - 'tab=module&' . - 'id_agent_module=' . $row['id_agente_modulo'] . '&' . - 'edit_module=1'; - } - - if ($show_edit_icon) { - $data[2] .= '' . - html_print_image('images/config.png', true, - array('alt' => '0', 'border' => '', 'title' => __('Edit'))) . - ''; + if ($show_edit_icon) { + $data[2] .= '' . + html_print_image('images/config.png', true, + array('alt' => '0', 'border' => '', 'title' => __('Edit'))) . + ''; + } } } - $data[3] = ui_print_truncate_text($row['module_name'], 'agent_small', false, true, true); - if ($row['extended_info'] != '') { - $data[3] .= ui_print_help_tip ($row['extended_info'], true, '/images/default_list.png'); + if (in_array('module_name', $show_fields) || is_metaconsole()) { + $data[3] = ui_print_truncate_text($row['module_name'], 'agent_small', false, true, true); + if ($row['extended_info'] != '') { + $data[3] .= ui_print_help_tip ($row['extended_info'], true, '/images/default_list.png'); + } + if ($row['tags'] != '') { + $data[3] .= html_print_image('/images/tag_red.png', true, + array( + 'title' => $row['tags'], + 'style' => 'width: 20px; margin-left: 3px;')); + } } - if ($row['tags'] != '') { - $data[3] .= html_print_image('/images/tag_red.png', true, - array( - 'title' => $row['tags'], - 'style' => 'width: 20px; margin-left: 3px;')); - } - $data[4] = servers_show_type ($row['id_modulo']); + + if (in_array('server_type', $show_fields) || is_metaconsole()) + $data[4] = servers_show_type ($row['id_modulo']); - $data[5] = ($row['module_interval'] == 0) ? - human_time_description_raw($row['agent_interval']) - : - human_time_description_raw($row['module_interval']); - if ($row['utimestamp'] == 0 && (($row['module_type'] < 21 || - $row['module_type'] > 23) && $row['module_type'] != 100)) { - $data[6] = ui_print_status_image(STATUS_MODULE_NO_DATA, - __('NOT INIT'), true); + if (in_array('interval', $show_fields) || is_metaconsole()) { + $data[5] = ($row['module_interval'] == 0) ? + human_time_description_raw($row['agent_interval']) + : + human_time_description_raw($row['module_interval']); } - elseif ($row['estado'] == 0) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_OK, - __('NORMAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + + if (in_array('status', $show_fields) || is_metaconsole()) { + if ($row['utimestamp'] == 0 && (($row['module_type'] < 21 || + $row['module_type'] > 23) && $row['module_type'] != 100)) { + $data[6] = ui_print_status_image(STATUS_MODULE_NO_DATA, + __('NOT INIT'), true); + } + elseif ($row['estado'] == 0) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image(STATUS_MODULE_OK, + __('NORMAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + } + else { + $data[6] = ui_print_status_image(STATUS_MODULE_OK, + __('NORMAL') . ': ' . $row['datos'], true); + } + } + elseif ($row['estado'] == 1) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image(STATUS_MODULE_CRITICAL, + __('CRITICAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + } + else { + $data[6] = ui_print_status_image(STATUS_MODULE_CRITICAL, + __('CRITICAL') . ': ' . $row['datos'], true); + } + } + elseif ($row['estado'] == 2) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image(STATUS_MODULE_WARNING, + __('WARNING') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + } + else { + $data[6] = ui_print_status_image(STATUS_MODULE_WARNING, + __('WARNING') . ': ' . $row['datos'], true); + } } else { - $data[6] = ui_print_status_image(STATUS_MODULE_OK, - __('NORMAL') . ': ' . $row['datos'], true); + $last_status = modules_get_agentmodule_last_status( + $row['id_agente_modulo']); + switch($last_status) { + case 0: + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, + __('UNKNOWN') . ' - ' . __('Last status') . " " . + __('NORMAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + } + else { + $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, + __('UNKNOWN') . ' - ' . __('Last status') . " " . + __('NORMAL') . ': ' . $row['datos'], true); + } + break; + case 1: + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, + __('UNKNOWN') . ' - ' . __('Last status') ." " . + __('CRITICAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + } + else { + $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, + __('UNKNOWN') . ' - ' . __('Last status') ." " . + __('CRITICAL') . ': ' . $row['datos'], true); + } + break; + case 2: + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, + __('UNKNOWN') . ' - ' . __('Last status') . " " . + __('WARNING') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + } + else { + $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, + __('UNKNOWN') . ' - ' . __('Last status') . " " . + __('WARNING') . ': ' . $row['datos'], true); + } + break; + } } } - elseif ($row['estado'] == 1) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_CRITICAL, - __('CRITICAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); + + if (in_array('graph', $show_fields) || is_metaconsole()) { + $data[7] = ""; + + $acl_graphs = false; + + // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions + if (!is_metaconsole()) { + $acl_graphs = check_acl($config['id_user'], $row['id_group'], 'RR'); } else { - $data[6] = ui_print_status_image(STATUS_MODULE_CRITICAL, - __('CRITICAL') . ': ' . $row['datos'], true); - } - } - elseif ($row['estado'] == 2) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_WARNING, - __('WARNING') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_WARNING, - __('WARNING') . ': ' . $row['datos'], true); - } - } - else { - $last_status = modules_get_agentmodule_last_status( - $row['id_agente_modulo']); - switch($last_status) { - case 0: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('NORMAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('NORMAL') . ': ' . $row['datos'], true); - } - break; - case 1: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') ." " . - __('CRITICAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') ." " . - __('CRITICAL') . ': ' . $row['datos'], true); - } - break; - case 2: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('WARNING') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('WARNING') . ': ' . $row['datos'], true); - } - break; - } - } - - $data[7] = ""; - - $acl_graphs = false; - - // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions - if (!is_metaconsole()) { - $acl_graphs = check_acl($config['id_user'], $row['id_group'], 'RR'); - } - else { - $acl_graphs = true; - } - - if ($row['history_data'] == 1 && $acl_graphs) { - $graph_type = return_graphtype ($row['module_type']); - - $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); - $handle = dechex(crc32($row['id_agente_modulo'].$row['module_name'])); - $win_handle = 'day_'.$handle; - - $graph_params = array( - 'type' => $graph_type, - 'period' => SECONDS_1DAY, - 'id' => $row['id_agente_modulo'], - 'label' => base64_encode($row['module_name']), - 'refresh' => SECONDS_10MINUTES - ); - - if (is_metaconsole() && isset($row['server_id'])) { - // Set the server id - $graph_params['server'] = $row['server_id']; + $acl_graphs = true; } - $graph_params_str = http_build_query($graph_params); - - $link = 'winopeng(\''.$url.'?'.$graph_params_str.'\',\''.$win_handle.'\')'; + if ($row['history_data'] == 1 && $acl_graphs) { + $graph_type = return_graphtype ($row['module_type']); + + $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); + $handle = dechex(crc32($row['id_agente_modulo'].$row['module_name'])); + $win_handle = 'day_'.$handle; + + $graph_params = array( + 'type' => $graph_type, + 'period' => SECONDS_1DAY, + 'id' => $row['id_agente_modulo'], + 'label' => base64_encode($row['module_name']), + 'refresh' => SECONDS_10MINUTES + ); + + if (is_metaconsole() && isset($row['server_id'])) { + // Set the server id + $graph_params['server'] = $row['server_id']; + } + + $graph_params_str = http_build_query($graph_params); + + $link = 'winopeng(\''.$url.'?'.$graph_params_str.'\',\''.$win_handle.'\')'; - $data[7] = get_module_realtime_link_graph($row); + $data[7] = get_module_realtime_link_graph($row); - if(!is_snapshot_data($row['datos'])){ - $data[7] .= '' . html_print_image('images/chart_curve.png', true, array('border' => '0', 'alt' => '')) . ''; + if(!is_snapshot_data($row['datos'])){ + $data[7] .= '' . html_print_image('images/chart_curve.png', true, array('border' => '0', 'alt' => '')) . ''; + } + $data[7] .= '' . + html_print_image ('images/binary.png', true, + array ('border' => '0', 'alt' => '')) . ''; + + $data[7] .= '' . + $row['module_name'] . + ''; } - $data[7] .= '' . - html_print_image ('images/binary.png', true, - array ('border' => '0', 'alt' => '')) . ''; - - $data[7] .= '' . - $row['module_name'] . - ''; } - - $data[8] = ui_print_module_warn_value($row['max_warning'], - $row['min_warning'], $row['str_warning'], $row['max_critical'], - $row['min_critical'], $row['str_critical']); - if (is_numeric($row['datos']) && !modules_is_string_type($row['module_type'])) { - if ( $config['render_proc'] ) { - switch($row['module_type']) { - case 2: - case 6: - case 9: - case 18: - case 21: - case 31: - if ( $row['datos'] >= 1 ) - $salida = $config['render_proc_ok']; - else - $salida = $config['render_proc_fail']; - break; - default: - switch($row['module_type']) { - case 15: - $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); - if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') - $salida = human_milliseconds_to_string($row['datos']); - else + if (in_array('warn', $show_fields) || is_metaconsole()) { + + $data[8] = ui_print_module_warn_value($row['max_warning'], + $row['min_warning'], $row['str_warning'], $row['max_critical'], + $row['min_critical'], $row['str_critical']); + + if (is_numeric($row['datos']) && !modules_is_string_type($row['module_type'])) { + if ( $config['render_proc'] ) { + switch($row['module_type']) { + case 2: + case 6: + case 9: + case 18: + case 21: + case 31: + if ( $row['datos'] >= 1 ) + $salida = $config['render_proc_ok']; + else + $salida = $config['render_proc_fail']; + break; + default: + switch($row['module_type']) { + case 15: + $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); + if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') + $salida = human_milliseconds_to_string($row['datos']); + else + $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); + break; + default: $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - default: - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - } + break; + } + break; + } + } + else { + switch($row['module_type']) { + case 15: + $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); + if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') + $salida = human_milliseconds_to_string($row['datos']); + else + $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); + break; + default: + $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); break; } - } - else { - switch($row['module_type']) { - case 15: - $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); - if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') - $salida = human_milliseconds_to_string($row['datos']); - else - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - default: - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; } - } - - // Show units ONLY in numeric data types - if (isset($row['unit'])) { - $data_macro = modules_get_unit_macro($row['datos'],$row['unit']); - if($data_macro) { - $salida = $data_macro; - } else { - $salida .= ' ' . '' . io_safe_output($row['unit']) . ''; - if(strlen($salida) > $config['agent_size_text_small']) { - $salida = ui_print_truncate_text($salida, 'agent_small', true, true, false, '[…]', 'font-size:7.5pt;'); - //clean tag - $text_aux = explode(' $row['id_agente_modulo'], - 'interval' => $row['current_interval'], - 'module_name' => $row['module_name'], - 'id_node' => $row['server_id'] - )); - $salida = ui_get_snapshot_image($link, $is_snapshot) . '  '; - } else { - $sub_string = substr(io_safe_output($row['datos']), 0, 12); - if ($module_value == $sub_string) { - if ($module_value == 0 && !$sub_string) { - $salida = 0; - } - else { - $data_macro = modules_get_unit_macro($row['datos'],$row['unit']); - if($data_macro) { - $salida = $data_macro; + $salida .= ' ' . '' . io_safe_output($row['unit']) . ''; + if(strlen($salida) > $config['agent_size_text_small']) { + $salida = ui_print_truncate_text($salida, 'agent_small', true, true, false, '[…]', 'font-size:7.5pt;'); + //clean tag + $text_aux = explode(' $row['id_agente_modulo'], + 'interval' => $row['current_interval'], + 'module_name' => $row['module_name'], + 'id_node' => $row['server_id'] + )); + $salida = ui_get_snapshot_image($link, $is_snapshot) . '  '; + } else { + $sub_string = substr(io_safe_output($row['datos']), 0, 12); + if ($module_value == $sub_string) { + if ($module_value == 0 && !$sub_string) { + $salida = 0; + } + else { + $data_macro = modules_get_unit_macro($row['datos'],$row['unit']); + if($data_macro) { + $salida = $data_macro; + } else { + $salida = $row['datos']; + } + } } else { - //Fixed the data from Selenium Plugin - if ($module_value != strip_tags($module_value)) { - $module_value = io_safe_input($module_value); + //Fixed the goliat sends the strings from web + //without HTML entities + if ($is_web_content_string) { $sub_string = substr($row['datos'], 0, 12); } else { - $sub_string = substr(io_safe_output($row['datos']),0, 12); + //Fixed the data from Selenium Plugin + if ($module_value != strip_tags($module_value)) { + $module_value = io_safe_input($module_value); + $sub_string = substr($row['datos'], 0, 12); + } + else { + $sub_string = substr(io_safe_output($row['datos']),0, 12); + } + } + + if ($module_value == $sub_string) { + $salida = $module_value; + } + else { + $salida = "" . + $module_value . + "" . + "" . + '' . + $sub_string . ' ' . + "" . + html_print_image('images/rosette.png', true) . ''; } - } - - if ($module_value == $sub_string) { - $salida = $module_value; - } - else { - $salida = "" . - $module_value . - "" . - "" . - '' . - $sub_string . ' ' . - "" . - html_print_image('images/rosette.png', true) . ''; } } } } + + if (in_array('data', $show_fields) || is_metaconsole()) + $data[9] = $salida; - $data[9] = $salida; - - if ($row['module_interval'] > 0) - $interval = $row['module_interval']; - else - $interval = $row['agent_interval']; - - if ($row['estado'] == 3) { - $option = array ('html_attr' => 'class="redb"','style' => 'font-size:7pt;'); + if (in_array('timestamp', $show_fields) || is_metaconsole()) { + if ($row['module_interval'] > 0) + $interval = $row['module_interval']; + else + $interval = $row['agent_interval']; + + if ($row['estado'] == 3) { + $option = array ('html_attr' => 'class="redb"','style' => 'font-size:7pt;'); + } + else { + $option = array ('style' => 'font-size:7pt;'); + } + $data[10] = ui_print_timestamp ($row['utimestamp'], true, $option); } - else { - $option = array ('style' => 'font-size:7pt;'); + + if (in_array('to_critical', $show_fields)) { + + if ($row['estado'] == 1) { + $to_critical_timestamp = db_get_sql ('SELECT utimestamp FROM tevento WHERE id_agentmodule=' . $row['id_agente_modulo'] . ' AND event_type LIKE "going_up_critical" ORDER BY utimestamp DESC'); + $data[11] = ui_print_timestamp ($to_critical_timestamp, true, $option); + } else { + $data[11] = '-'; + } + } - $data[10] = ui_print_timestamp ($row['utimestamp'], true, $option); array_push ($table->data, $data); } diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index 53b7b79257..162c5ff45d 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -85,6 +85,7 @@ INSERT INTO `tconfig` (`token`, `value`) VALUES ('netflow_nfdump', '/usr/bin/nfdump'), ('netflow_max_resolution', '50'), ('event_fields', 'evento,id_agente,estado,timestamp'), +('status_monitor_fields', 'policy,agent,data_type,module_name,server_type,interval,status,graph,warn,data,timestamp'), ('list_ACL_IPs_for_API', '127.0.0.1'), ('enable_pass_policy', 0), ('pass_size', 4), From 4d4569cadbbf4656ae23553951792735036094e2 Mon Sep 17 00:00:00 2001 From: "tatiana.llorente@artica.es" Date: Fri, 25 Jan 2019 13:52:49 +0100 Subject: [PATCH 016/249] Fixed error with slashes - #3426 Former-commit-id: 8dbead7acd73faa66e406cccf1fe81ed775eb933 --- pandora_console/include/functions_config.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index 2fd79d6d43..3e414f636a 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -2248,7 +2248,7 @@ function config_check () { __('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), __("Problems with disable functions in PHP.INI")); } - $result_ejecution = exec($config['phantomjs_bin'] . '/phantomjs --version'); + $result_ejecution = exec('"'.io_safe_output($config['phantomjs_bin']) . '/phantomjs" --version'); if(!isset($result_ejecution) || $result_ejecution == '') { if ($config['language'] == 'es') { set_pandora_error_for_header( From dc3d7cc5e2669475a3a118e13dca27e0def65464 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 30 Jan 2019 11:56:21 +0100 Subject: [PATCH 017/249] notifications, first approach db schema Former-commit-id: 1142c65f175c13eaaff9b26a9887f4ef519e9612 --- .../pandoradb_migrate_6.0_to_7.0.mysql.sql | 88 +++++++++++++++ pandora_console/pandoradb.sql | 101 +++++++++++++++--- pandora_console/pandoradb_data.sql | 12 +++ 3 files changed, 187 insertions(+), 14 deletions(-) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 5dc7cd70c4..e62e76efd5 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1868,3 +1868,91 @@ CREATE TABLE IF NOT EXISTS `tgis_map_layer_groups` ( FOREIGN KEY (`group_id`) REFERENCES `tgrupo` (`id_grupo`) ON DELETE CASCADE, FOREIGN KEY (`agent_id`) REFERENCES `tagente` (`id_agente`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ----------------------------------------------------- +-- Table `tnotification_source` +-- ----------------------------------------------------- +CREATE TABLE `tnotification_source` ( + `id` serial, + `description` VARCHAR(255) DEFAULT NULL, + `icon` text, + `max_postpone_time` int(11) DEFAULT NULL, + `enabled` int(1) DEFAULT NULL, + `user_editable` int(1) DEFAULT NULL, + `also_mail` int(1) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- +-- Dumping data for table `tnotification_source` +-- +INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, `user_editable`, `also_mail`) VALUES + ("System status", "icono_info_mr.png", 86400, 1, 0), + ("Message", "icono_info_mr.png", 86400, 1, 0), + ("Pending task", "icono_info_mr.png", 86400, 1, 0), + ("Advertisement", "icono_info_mr.png", 86400, 1, 0), + ("Official communication", "icono_info_mr.png", 86400, 1, 0), + ("Sugerence", "icono_info_mr.png", 86400, 1, 0); + +-- ----------------------------------------------------- +-- Table `tmensajes` +-- ----------------------------------------------------- +ALTER TABLE `tmensajes` ADD COLUMN `url` TEXT; +ALTER TABLE `tmensajes` ADD COLUMN `response_mode` VARCHAR(200) DEFAULT NULL; +ALTER TABLE `tmensajes` ADD COLUMN `citicity` INT(10) UNSIGNED DEFAULT '0'; +ALTER TABLE `tmensajes` ADD COLUMN `id_source` BIGINT(20) UNSIGNED NOT NULL; +ALTER TABLE `tmensajes` ADD CONSTRAINT `tsource_fk` FOREIGN KEY (`id_source`) REFERENCES `tnotification_source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE + + +-- ---------------------------------------------------------------------- +-- Table `tnotification_user` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_user` ( + `id_mensaje` INT(10) UNSIGNED NOT NULL, + `id_user` VARCHAR(60) NOT NULL, + `utimestamp_read` BIGINT(20), + `utimestamp_erased` BIGINT(20), + `postpone` INT, + PRIMARY KEY (`id_mensaje`,`id_user`), + FOREIGN KEY (`id_mensaje`) REFERENCES `tmensajes`(`id_mensaje`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_group` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_group` ( + `id_mensaje` INT(10) UNSIGNED NOT NULL, + `id_group` mediumint(4) UNSIGNED NOT NULL, + PRIMARY KEY (`id_mensaje`,`id_group`), + FOREIGN KEY (`id_mensaje`) REFERENCES `tmensajes`(`id_mensaje`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_source_user` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_source_user` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_user` VARCHAR(60), + `enabled` INT(1) DEFAULT NULL, + `also_mail` INT(1) DEFAULT NULL, + PRIMARY KEY (`id_source`,`id_user`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_source_group` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_source_group` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL, + PRIMARY KEY (`id_source`,`id_group`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index 7f8197540b..c70650c70b 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -719,20 +719,6 @@ CREATE TABLE IF NOT EXISTS `tlink` ( PRIMARY KEY (`id_link`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; --- ----------------------------------------------------- --- Table `tmensajes` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `tmensajes` ( - `id_mensaje` int(10) unsigned NOT NULL auto_increment, - `id_usuario_origen` varchar(60) NOT NULL default '', - `id_usuario_destino` varchar(60) NOT NULL default '', - `mensaje` text NOT NULL, - `timestamp` bigint (20) unsigned NOT NULL default '0', - `subject` varchar(255) NOT NULL default '', - `estado` int(4) unsigned NOT NULL default '0', - PRIMARY KEY (`id_mensaje`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -- ---------------------------------------------------------------------- -- Table `tmodule_group` -- ---------------------------------------------------------------------- @@ -1177,6 +1163,93 @@ CREATE TABLE IF NOT EXISTS `treset_pass_history` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +-- ----------------------------------------------------- +-- Table `tnotification_source` +-- ----------------------------------------------------- +CREATE TABLE `tnotification_source` ( + `id` serial, + `description` VARCHAR(255) DEFAULT NULL, + `icon` text, + `max_postpone_time` int(11) DEFAULT NULL, + `enabled` int(1) DEFAULT NULL, + `user_editable` int(1) DEFAULT NULL, + `also_mail` int(1) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ----------------------------------------------------- +-- Table `tmensajes` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `tmensajes` ( + `id_mensaje` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, + `id_usuario_origen` VARCHAR(60) NOT NULL DEFAULT '', + `mensaje` TEXT NOT NULL, + `timestamp` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', + `subject` VARCHAR(255) NOT NULL DEFAULT '', + `estado` INT(4) UNSIGNED NOT NULL DEFAULT '0', + `url` TEXT, + `response_mode` VARCHAR(200) DEFAULT NULL, + `citicity` INT(10) UNSIGNED DEFAULT '0', + `id_source` BIGINT(20) UNSIGNED NOT NULL, + PRIMARY KEY (`id_mensaje`), + UNIQUE KEY `id_mensaje` (`id_mensaje`), + KEY `tsource_fk` (`id_source`), + CONSTRAINT `tsource_fk` FOREIGN KEY (`id_source`) REFERENCES `tnotification_source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_user` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_user` ( + `id_mensaje` INT(10) UNSIGNED NOT NULL, + `id_user` VARCHAR(60) NOT NULL, + `utimestamp_read` BIGINT(20), + `utimestamp_erased` BIGINT(20), + `postpone` INT, + PRIMARY KEY (`id_mensaje`,`id_user`), + FOREIGN KEY (`id_mensaje`) REFERENCES `tmensajes`(`id_mensaje`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_group` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_group` ( + `id_mensaje` INT(10) UNSIGNED NOT NULL, + `id_group` mediumint(4) UNSIGNED NOT NULL, + PRIMARY KEY (`id_mensaje`,`id_group`), + FOREIGN KEY (`id_mensaje`) REFERENCES `tmensajes`(`id_mensaje`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_source_user` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_source_user` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_user` VARCHAR(60), + `enabled` INT(1) DEFAULT NULL, + `also_mail` INT(1) DEFAULT NULL, + PRIMARY KEY (`id_source`,`id_user`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_source_group` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_source_group` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL, + PRIMARY KEY (`id_source`,`id_group`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + -- ---------------------------------------------------------------------- -- Table `tnews` -- ---------------------------------------------------------------------- diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index 32adab0421..e803c83d82 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1267,3 +1267,15 @@ INSERT INTO `tcontainer` SET `name` = 'Default graph container'; INSERT INTO tlog_graph_models VALUES (1, 'Apache log model', '^.*?\s+.*".*?\s(\/.*?)\?.*1.1"\s+(.*?)\s+(.*?)\s+', 'pagina, html_err_code, _tiempo_', 1); + +-- +-- Dumping data for table `tnotification_source` +-- +INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, `user_editable`, `also_mail`) VALUES + ("System status", "icono_info_mr.png", 86400, 1, 0), + ("Message", "icono_info_mr.png", 86400, 1, 0), + ("Pending task", "icono_info_mr.png", 86400, 1, 0), + ("Advertisement", "icono_info_mr.png", 86400, 1, 0), + ("Official communication", "icono_info_mr.png", 86400, 1, 0), + ("Sugerence", "icono_info_mr.png", 86400, 1, 0); + From fa6c4d5bc9f32e75fa1f98109e602d11b30be8d8 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 30 Jan 2019 11:56:47 +0100 Subject: [PATCH 018/249] notifications, WIP: new lib defined Former-commit-id: 430ac2e090f91403fc074d2a9b37ab36de10d5a9 --- .../include/functions_messages.php | 652 +++++++++++------- .../include/functions_notifications.php | 53 ++ .../operation/messages/message_list.php | 470 +++++++------ 3 files changed, 698 insertions(+), 477 deletions(-) create mode 100644 pandora_console/include/functions_notifications.php diff --git a/pandora_console/include/functions_messages.php b/pandora_console/include/functions_messages.php index dec3dc2b62..675b9c2a38 100644 --- a/pandora_console/include/functions_messages.php +++ b/pandora_console/include/functions_messages.php @@ -1,321 +1,451 @@ $usuario_origen, + 'subject' => $subject, + 'mensaje' => $mensaje, + 'id_source' => get_notification_source_id('message'), + 'timestamp' => get_system_time(), + ] + ); + + // Update URL + // Update targets. + if ($message_id !== false) { + $return = db_process_sql_insert( + 'tnotification_user', + [ + 'id_mensaje' => $message_id, + 'id_user' => $usuario_destino, + ] + ); + } + + if ($return === false) { + return false; + } else { + return true; + } } -/** + +/** * Creates private messages to be forwarded to groups - * - * @param string The sender of the message - * @param string The receivers (group) of the message - * @param string Subject of the message (much like E-Mail) - * @param string The actual message. This message will be cleaned by io_safe_input - * (html is allowed but loose html chars will be translated) * - * @return bool true when delivered, false in case of error + * @param string $usuario_origen The sender of the message. + * @param string $dest_group The receivers (group) of the message. + * @param string $subject Subject of the message (much like E-Mail). + * @param string $mensaje The actual message. This message will be + * cleaned by io_safe_input (html is allowed but + * loose html chars will be translated). + * + * @return boolean true when delivered, false in case of error */ -function messages_create_group ($usuario_origen, $dest_group, $subject, $mensaje) { - $users = users_get_info (); - $group_users = groups_get_users ($dest_group); - - if (! array_key_exists ($usuario_origen, $users)) { - //Users don't exist in the system - return false; - } - elseif (empty ($group_users)) { - //There are no users in the group, so it hasn't failed although it hasn't done anything. - return true; - } - - // array unique - foreach ($group_users as $user) { - foreach ($user as $key=>$us) { - if ($key == 'id_user') { - $group_user[$us] = $us; - } - } - } - - foreach ($group_user as $user) { - $return = messages_create_message ($usuario_origen, get_user_id ($user), $subject, $mensaje); - if ($return === false) { - //Error sending message - return false; - } - } - - return true; +function messages_create_group( + string $usuario_origen, + string $dest_group, + string $subject, + string $mensaje +) { + $users = users_get_info(); + $group_users = groups_get_users($dest_group); + + if (! array_key_exists($usuario_origen, $users)) { + // Users don't exist in the system. + return false; + } else if (empty($group_users)) { + /* + There are no users in the group, so it hasn't failed + although it hasn't done anything. + */ + + return true; + } + + // Array unique. + foreach ($group_users as $user) { + foreach ($user as $key => $us) { + if ($key == 'id_user') { + $group_user[$us] = $us; + } + } + } + + foreach ($group_user as $user) { + $return = messages_create_message( + $usuario_origen, + get_user_id($user), + $subject, + $mensaje + ); + if ($return === false) { + // Error sending message. + return false; + } + } + + return true; } -/** + +/** * Deletes a private message - * - * @param int $id_message * - * @return bool true when deleted, false in case of error + * @param integer $id_message Message to be deleted. + * + * @return boolean true when deleted, false in case of error */ -function messages_delete_message ($id_message) { - global $config; - - $where = array( - //'id_usuario_destino' => $config["id_user"], - 'id_mensaje' => $id_message); - return (bool)db_process_sql_delete('tmensajes', $where); +function messages_delete_message(int $id_message) +{ + global $config; + // 'id_usuario_destino' => $config["id_user"], + $where = ['id_mensaje' => $id_message]; + return (bool) db_process_sql_delete('tmensajes', $where); } -/** + +/** * Marks a private message as read/unread - * - * @param int $message_id The message to modify - * @param bool $read To set unread pass 0, false or empty value * - * @return bool true when marked, false in case of error + * @param integer $message_id The message to modify. + * @param boolean $read To set unread pass 0, false or empty value. + * + * @return boolean true when marked, false in case of error */ -function messages_process_read ($message_id, $read = true) { - if (empty ($read)) { - $read = 0; - } - else { - $read = 1; - } - - return (bool) db_process_sql_update('tmensajes', array('estado' => $read), array('id_mensaje' => $message_id)); +function messages_process_read( + int $message_id, + bool $read=true +) { + if (empty($read)) { + $read = 0; + } else { + $read = 1; + } + + return (bool) db_process_sql_update( + 'tmensajes', + ['estado' => $read], + ['id_mensaje' => $message_id] + ); } -/** + +/** * Gets a private message * - * This function abstracts the database backend so it can simply be replaced with another system - * - * @param int $message_id + * This function abstracts the database backend so it can simply be + * replaced with another system + * + * @param integer $message_id Message to be retrieved. * * @return mixed False if it doesn't exist or a filled array otherwise */ -function messages_get_message ($message_id) { - global $config; - - $sql = sprintf("SELECT id_usuario_origen, id_usuario_destino, subject, mensaje, timestamp - FROM tmensajes - WHERE id_usuario_destino='%s' AND id_mensaje=%d" , $config["id_user"], $message_id); - $row = db_get_row_sql ($sql); - - if (empty ($row)) { - return false; - } - - return $row; +function messages_get_message(int $message_id) +{ + global $config; + + $sql = sprintf( + "SELECT id_usuario_origen, id_usuario_destino, subject, mensaje, timestamp + FROM tmensajes + WHERE id_usuario_destino='%s' AND id_mensaje=%d", + $config['id_user'], + $message_id + ); + $row = db_get_row_sql($sql); + + if (empty($row)) { + return false; + } + + return $row; } -/** + +/** * Gets a sent message * - * This function abstracts the database backend so it can simply be replaced with another system - * - * @param int $message_id + * This function abstracts the database backend so it can simply be + * replaced with another system + * + * @param integer $message_id Message to be retrieved. * * @return mixed False if it doesn't exist or a filled array otherwise */ -function messages_get_message_sent ($message_id) { - global $config; - - $sql = sprintf("SELECT id_usuario_origen, id_usuario_destino, subject, mensaje, timestamp - FROM tmensajes - WHERE id_usuario_origen='%s' AND id_mensaje=%d" , $config["id_user"], $message_id); - $row = db_get_row_sql ($sql); - - if (empty ($row)) { - return false; - } - - return $row; +function messages_get_message_sent(int $message_id) +{ + global $config; + + $sql = sprintf( + "SELECT id_usuario_origen, id_usuario_destino, subject, mensaje, timestamp + FROM tmensajes + WHERE id_usuario_origen='%s' AND id_mensaje=%d", + $config['id_user'], + $message_id + ); + $row = db_get_row_sql($sql); + + if (empty($row)) { + return false; + } + + return $row; } -/** +/** * Counts private messages * - * @param string $user - * @param bool $incl_read Whether or not to include read messages + * @param string $user Target user. + * @param boolean $incl_read Whether or not to include read messages. * - * @return int The number of messages this user has + * @return integer The number of messages this user has */ -function messages_get_count ($user = false, $incl_read = false) { - if (empty ($user)) { - global $config; - $user = $config["id_user"]; - } - - if (empty ($incl_read)) { - $filter = "AND estado = 0"; - } - else { - $filter = ""; - } - $sql = sprintf("SELECT COUNT(*) - FROM tmensajes WHERE id_usuario_destino='%s' %s", $user, $filter); - - return (int) db_get_sql ($sql); -} +function messages_get_count( + string $user='', + bool $incl_read=false +) { + if (empty($user)) { + global $config; + $user = $config['id_user']; + } -/** - * Counts sended messages - * - * @param string $user - * - * @return int The number of messages this user has sent - */ -function messages_get_count_sent ($user = false) { - if (empty ($user)) { - global $config; - $user = $config["id_user"]; - } - $sql = sprintf("SELECT COUNT(*) - FROM tmensajes WHERE id_usuario_origen='%s'", $user); - - return (int) db_get_sql ($sql); + if (!empty($incl_read)) { + // Retrieve only unread messages. + $filter = 'AND nu.uptimestap_read == NULL'; + } else { + // Do not filter. + $filter = ''; + } + + $sql = sprintf( + "SELECT count(*) FROM tmensajes tm + left join tnotification_user nu + ON tm.id_mensaje=nu.id_mensaje + left join tnotification_group ng + ON tm.id_mensaje=ng.id_mensaje + left join tusuario_perfil up + ON tm.id_mensaje=ng.id_mensaje + AND ng.id_group=up.id_grupo + WHERE (nu.id_user='%s' OR ng.id_group=0 OR up.id_grupo=ng.id_group) + %s", + $config['id_user'], + $filter + ); + + return (int) db_get_sql($sql); } -/** +/** + * Counts messages sent. + * + * @param string $user Target user. + * + * @return integer The number of messages this user has sent + */ +function messages_get_count_sent(string $user='') +{ + if (empty($user)) { + global $config; + $user = $config['id_user']; + } + + $sql = sprintf( + "SELECT COUNT(*) + FROM tmensajes WHERE id_usuario_origen='%s'", + $user + ); + + return (int) db_get_sql($sql); +} + + +/** * Get message overview in array * - * @param string $order How to order them valid: - * (status (default), subject, timestamp, sender) - * @param string $order_dir Direction of order (ASC = Ascending, DESC = Descending) + * @param string $order How to order them valid: + * (status (default), subject, timestamp, sender). + * @param string $order_dir Direction of order + * (ASC = Ascending, DESC = Descending). * - * @return int The number of messages this user has + * @return integer The number of messages this user has */ -function messages_get_overview ($order = "status", $order_dir = "ASC") { - global $config; - - switch ($order) { - case "timestamp": - case "sender": - case "subject": - break; - case "status": - default: - $order = "estado, timestamp"; - break; - } - - if ($order_dir != "ASC") { - $order .= " DESC"; - } - - $result = array (); - $return = db_get_all_rows_field_filter ('tmensajes', 'id_usuario_destino', $config["id_user"], $order); - - if ($return === false) { - return $result; - } - - foreach ($return as $message) { - $result[$message["id_mensaje"]]["sender"] = $message["id_usuario_origen"]; - $result[$message["id_mensaje"]]["subject"] = $message["subject"]; - $result[$message["id_mensaje"]]["timestamp"] = $message["timestamp"]; - $result[$message["id_mensaje"]]["status"] = $message["estado"]; - } - - return $result; +function messages_get_overview( + string $order='status', + string $order_dir='ASC' +) { + global $config; + + switch ($order) { + case 'timestamp':{ + } + case 'sender':{ + } + case 'subject':{ + } + break; + + case 'status': + default: + $order = 'estado, timestamp'; + break; + } + + if ($order_dir != 'ASC') { + $order .= ' DESC'; + } + + $sql = sprintf( + "SELECT * FROM tmensajes tm + left join tnotification_user nu + ON tm.id_mensaje=nu.id_mensaje + left join tnotification_group ng + ON tm.id_mensaje=ng.id_mensaje + left join tusuario_perfil up + ON tm.id_mensaje=ng.id_mensaje + AND ng.id_group=up.id_grupo + WHERE (nu.id_user='%s' OR ng.id_group=0 OR up.id_grupo=ng.id_group) + ORDER BY %s", + $config['id_user'], + $order + ); + + $result = []; + $return = db_get_all_rows_sql($sql); + + if ($return === false) { + return $result; + } + + foreach ($return as $message) { + $id_message = $message['id_mensaje']; + $result[$id_message]['sender'] = $message['id_usuario_origen']; + $result[$id_message]['subject'] = $message['subject']; + $result[$id_message]['timestamp'] = $message['timestamp']; + $result[$id_message]['status'] = $message['estado']; + } + + return $result; } -/** + +/** * Get sent message overview in array * - * @param string $order How to order them valid: - * (status (default), subject, timestamp, sender) - * @param string $order_dir Direction of order (ASC = Ascending, DESC = Descending) + * @param string $order How to order them valid: + * (status (default), subject, timestamp, sender). + * @param string $order_dir Direction of order + * (ASC = Ascending, DESC = Descending). * - * @return int The number of messages this user has + * @return integer The number of messages this user has */ -function messages_get_overview_sent ($order = "timestamp", $order_dir = "ASC") { - global $config; - - switch ($order) { - case "timestamp": - case "sender": - case "subject": - break; - case "status": - default: - $order = "estado, timestamp"; - break; - } - - if ($order_dir != "ASC") { - $order .= " DESC"; - } - - $result = array (); - $return = db_get_all_rows_field_filter ('tmensajes', 'id_usuario_origen', $config["id_user"], $order); - - if ($return === false) { - return $result; - } - - foreach ($return as $message) { - $result[$message["id_mensaje"]]["dest"] = $message["id_usuario_destino"]; - $result[$message["id_mensaje"]]["subject"] = $message["subject"]; - $result[$message["id_mensaje"]]["timestamp"] = $message["timestamp"]; - $result[$message["id_mensaje"]]["status"] = $message["estado"]; - } - - return $result; -} +function messages_get_overview_sent( + string $order='timestamp', + string $order_dir='ASC' +) { + global $config; -?> + switch ($order) { + case 'timestamp':{ + } + case 'sender':{ + } + case 'subject':{ + } + break; + + case 'status': + default: + $order = 'estado, timestamp'; + break; + } + + if ($order_dir != 'ASC') { + $order .= ' DESC'; + } + + $result = []; + $return = db_get_all_rows_field_filter( + 'tmensajes', + 'id_usuario_origen', + $config['id_user'], + $order + ); + + if ($return === false) { + return $result; + } + + foreach ($return as $message) { + $id_message = $message['id_mensaje']; + $result[$id_message]['dest'] = $message['id_usuario_destino']; + $result[$id_message]['subject'] = $message['subject']; + $result[$id_message]['timestamp'] = $message['timestamp']; + $result[$id_message]['status'] = $message['estado']; + } + + return $result; +} diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php new file mode 100644 index 0000000000..8372f54bf0 --- /dev/null +++ b/pandora_console/include/functions_notifications.php @@ -0,0 +1,53 @@ + $active_list, - 'text' => '' . - html_print_image("images/email_inbox.png", true, array ("title" => __('Received messages'))) .''); +$buttons['message_list'] = [ + 'active' => $active_list, + 'text' => ''.html_print_image('images/email_inbox.png', true, ['title' => __('Received messages')]).'', +]; -$buttons['sent_messages'] = array('active' => $active_sent, - 'text' => '' . - html_print_image("images/email_outbox.png", true, array ("title" => __('Sent messages'))) .''); +$buttons['sent_messages'] = [ + 'active' => $active_sent, + 'text' => ''.html_print_image('images/email_outbox.png', true, ['title' => __('Sent messages')]).'', +]; -$buttons['create_message'] = array('active' => false, - 'text' => '' . - html_print_image("images/new_message.png", true, array ("title" => __('Create message'))) .''); +$buttons['create_message'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/new_message.png', + true, + ['title' => __('Create message')] + ).'', +]; -if (!is_ajax ()) { - ui_print_page_header (__('Messages'), "images/email_mc.png", false, "", false, $buttons); +if (!is_ajax()) { + ui_print_page_header( + __('Messages'), + 'images/email_mc.png', + false, + '', + false, + $buttons + ); } if ($mark_unread) { - $message_id = get_parameter('id_message'); - messages_process_read ($message_id, false); + $message_id = get_parameter('id_message'); + messages_process_read($message_id, false); } if ($delete_msg) { - $id = (int) get_parameter ("id"); - $result = messages_delete_message ($id); //Delete message function will actually check the credentials - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Could not be deleted')); + $id = (int) get_parameter('id'); + $result = messages_delete_message($id); + // Delete message function will actually check the credentials. + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Could not be deleted') + ); } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id) { - $result = db_process_sql_delete ('tmensajes', - array ('id_mensaje' => $id)); - - if ($result === false) { - break; - } - } - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting messages')); + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id) { + $result = db_process_sql_delete( + 'tmensajes', + ['id_mensaje' => $id] + ); + + if ($result === false) { + break; + } + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting messages') + ); } -if ($show_sent) { //sent view - $num_messages = messages_get_count_sent($config['id_user']); - if ($num_messages > 0 && !is_ajax()) { - echo '

' . __('You have') . ' ' . $num_messages . ' ' . - ' ' . __('sent message(s)') . '.

'; - } - $messages = messages_get_overview_sent ('', 'DESC'); -} -else { //messages received - $num_messages = messages_get_count ($config["id_user"]); - if ($num_messages > 0 && !is_ajax()) { - echo '

' . __('You have') . ' ' . $num_messages . ' ' . - ' ' . __('unread message(s)') . '.

'; - } - $messages = messages_get_overview (); +if ($show_sent) { + // Sent view. + $num_messages = messages_get_count_sent($config['id_user']); + if ($num_messages > 0 && !is_ajax()) { + echo '

'.__('You have').' '.$num_messages.''.__('sent message(s)').'.

'; + } + + $messages = messages_get_overview_sent('', 'DESC'); +} else { + // Messages received. + $num_messages = messages_get_count($config['id_user']); + if ($num_messages > 0 && !is_ajax()) { + echo '

'.__('You have').' '.$num_messages.''.__('unread message(s)').'.

'; + } + + $messages = messages_get_overview(); } -if (empty ($messages)) { - ui_print_info_message ( - array('no_close'=>true, - 'message'=> __('There are no messages.') ) ); -} -else { - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox data'; - $table->cellpadding = 4; - $table->cellspacing = 4; - $table->head = array (); - $table->data = array (); - $table->align = array (); - $table->size = array (); - - $table->align[0] = "left"; - $table->align[1] = "left"; - $table->align[2] = "left"; - $table->align[3] = "left"; - $table->align[4] = "right"; - - $table->size[0] = "20px"; - $table->size[1] = "100px"; - $table->size[3] = "80px"; - $table->size[4] = "60px"; - - $table->head[0] = __('Status'); - if ($show_sent) - $table->head[1] = __('Destination'); - else - $table->head[1] = __('Sender'); - $table->head[2] = __('Subject'); - $table->head[3] = __('Timestamp'); - $table->head[4] = __('Delete'). html_print_checkbox('all_delete_messages', 0, false, true, false); - - foreach ($messages as $message_id => $message) { - $data = array (); - $data[0] = ''; - if ($message["status"] == 1) { - if ($show_sent) { - $data[0] .= ''; - $data[0] .= html_print_image ("images/email_open.png", true, array ("border" => 0, "title" => __('Click to read'))); - $data[0] .= ''; - } - else { - $data[0] .= ''; - $data[0] .= html_print_image ("images/email_open.png", true, array ("border" => 0, "title" => __('Mark as unread'))); - $data[0] .= ''; - } - } - else { - if ($show_sent) { - $data[0] .= ''; - $data[0] .= html_print_image ("images/email.png", true, array ("border" => 0, "title" => __('Message unread - click to read'))); - $data[0] .= ''; - } - else { - $data[0] .= ''; - $data[0] .= html_print_image ("images/email.png", true, array ("border" => 0, "title" => __('Message unread - click to read'))); - $data[0] .= ''; - } - } - - if ($show_sent) { - $dest_user = get_user_fullname ($message["dest"]); - if (!$dest_user) { - $dest_user = $message["dest"]; - } - $data[1] = $dest_user; - } - else { - $orig_user = get_user_fullname ($message["sender"]); - if (!$orig_user) { - $orig_user = $message["sender"]; - } - $data[1] = $orig_user; - } - - if ($show_sent) { - $data[2] = ''; - } - else { - $data[2] = ''; - } - if ($message["subject"] == "") { - $data[2] .= __('No Subject'); - } - else { - $data[2] .= $message["subject"]; - } - $data[2] .= ''; - - $data[3] = ui_print_timestamp( - $message["timestamp"], true, - array ("prominent" => "timestamp")); - - if ($show_sent) { - $data[4] = '' . - html_print_image ('images/cross.png', true, array("title" => __('Delete'))) . ''. - html_print_checkbox_extended ('delete_multiple_messages[]', $message_id, false, false, '', 'class="check_delete_messages"', true); - } - else { - $data[4] = '' . - html_print_image ('images/cross.png', true, array("title" => __('Delete'))) . ''. - html_print_checkbox_extended ('delete_multiple_messages[]', $message_id, false, false, '', 'class="check_delete_messages"', true); - } - array_push ($table->data, $data); - } - +if (empty($messages)) { + ui_print_info_message( + [ + 'no_close' => true, + 'message' => __('There are no messages.'), + ] + ); +} else { + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox data'; + $table->cellpadding = 4; + $table->cellspacing = 4; + $table->head = []; + $table->data = []; + $table->align = []; + $table->size = []; + + $table->align[0] = 'left'; + $table->align[1] = 'left'; + $table->align[2] = 'left'; + $table->align[3] = 'left'; + $table->align[4] = 'right'; + + $table->size[0] = '20px'; + $table->size[1] = '100px'; + $table->size[3] = '80px'; + $table->size[4] = '60px'; + + $table->head[0] = __('Status'); + if ($show_sent) { + $table->head[1] = __('Destination'); + } else { + $table->head[1] = __('Sender'); + } + + $table->head[2] = __('Subject'); + $table->head[3] = __('Timestamp'); + $table->head[4] = __('Delete').html_print_checkbox('all_delete_messages', 0, false, true, false); + + foreach ($messages as $message_id => $message) { + $data = []; + $data[0] = ''; + if ($message['status'] == 1) { + if ($show_sent) { + $data[0] .= ''; + $data[0] .= html_print_image('images/email_open.png', true, ['border' => 0, 'title' => __('Click to read')]); + $data[0] .= ''; + } else { + $data[0] .= ''; + $data[0] .= html_print_image('images/email_open.png', true, ['border' => 0, 'title' => __('Mark as unread')]); + $data[0] .= ''; + } + } else { + if ($show_sent) { + $data[0] .= ''; + $data[0] .= html_print_image('images/email.png', true, ['border' => 0, 'title' => __('Message unread - click to read')]); + $data[0] .= ''; + } else { + $data[0] .= ''; + $data[0] .= html_print_image('images/email.png', true, ['border' => 0, 'title' => __('Message unread - click to read')]); + $data[0] .= ''; + } + } + + if ($show_sent) { + $dest_user = get_user_fullname($message['dest']); + if (!$dest_user) { + $dest_user = $message['dest']; + } + + $data[1] = $dest_user; + } else { + $orig_user = get_user_fullname($message['sender']); + if (!$orig_user) { + $orig_user = $message['sender']; + } + + $data[1] = $orig_user; + } + + if ($show_sent) { + $data[2] = ''; + } else { + $data[2] = ''; + } + + if ($message['subject'] == '') { + $data[2] .= __('No Subject'); + } else { + $data[2] .= $message['subject']; + } + + $data[2] .= ''; + + $data[3] = ui_print_timestamp( + $message['timestamp'], + true, + ['prominent' => 'timestamp'] + ); + + if ($show_sent) { + $data[4] = ''.html_print_image('images/cross.png', true, ['title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple_messages[]', $message_id, false, false, '', 'class="check_delete_messages"', true); + } else { + $data[4] = ''.html_print_image('images/cross.png', true, ['title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple_messages[]', $message_id, false, false, '', 'class="check_delete_messages"', true); + } + + array_push($table->data, $data); + } } if (!empty($messages)) { - if ($show_sent) { - echo '
'; - } - else { - echo ''; - } - html_print_input_hidden('multiple_delete', 1); - html_print_table($table); - echo "
"; - html_print_submit_button(__('Delete'), 'delete_btn', - false, 'class="sub delete"'); - echo "
"; - echo "
"; + if ($show_sent) { + echo '
'; + } else { + echo ''; + } + + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + echo "
"; + html_print_submit_button( + __('Delete'), + 'delete_btn', + false, + 'class="sub delete"' + ); + echo '
'; + echo '
'; } echo "
"; - echo '
'; - html_print_submit_button (__('Create message'), 'create', false, 'class="sub next" style="margin-right:5px;"'); - echo "
"; -echo "
"; + echo '
'; + html_print_submit_button(__('Create message'), 'create', false, 'class="sub next" style="margin-right:5px;"'); + echo '
'; +echo '
'; ?> From 406c062a3c126e23f55a49413135a73ab2822bc1 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 30 Jan 2019 13:29:46 +0100 Subject: [PATCH 019/249] WIP messages, usable Former-commit-id: 79e0b38fe7499642480505aac088ef8b45b04714 --- .../include/functions_messages.php | 229 ++++----- .../include/functions_notifications.php | 57 ++- .../operation/messages/message_edit.php | 458 ++++++++++++------ .../operation/messages/message_list.php | 11 +- 4 files changed, 463 insertions(+), 292 deletions(-) diff --git a/pandora_console/include/functions_messages.php b/pandora_console/include/functions_messages.php index 675b9c2a38..3d163825c3 100644 --- a/pandora_console/include/functions_messages.php +++ b/pandora_console/include/functions_messages.php @@ -33,33 +33,88 @@ require_once $config['homedir'].'/include/functions_groups.php'; require_once $config['homedir'].'/include/functions_notifications.php'; +/** + * Set targets for given messaje + * + * @param integer $message_id Message id. + * @param array $users An array with all target users. + * @param array $groups An array with all target groups. + * + * @return boolean Task status. + */ +function message_set_targets( + int $message_id, + array $users=null, + array $groups=null +) { + if (empty($message_id)) { + return false; + } + + if (is_array($users)) { + $values = []; + foreach ($users as $user) { + if (empty($user)) { + continue; + } + + $values['id_mensaje'] = $message_id; + $values['id_user'] = $user; + } + + if (!empty($values)) { + $ret = db_process_sql_insert('tnotification_user', $values); + if ($ret === false) { + return false; + } + } + } + + if (is_array($groups)) { + $values = []; + foreach ($groups as $group) { + if (empty($group)) { + continue; + } + + $values['id_mensaje'] = $message_id; + $values['id_group'] = $group; + } + + if (!empty($values)) { + $ret = db_process_sql_insert('tnotification_group', $values); + if ($ret === false) { + return false; + } + } + } + + return true; +} + + /** * Creates a private message to be forwarded to other people * - * @param string $usuario_origen The sender of the message. - * @param string $usuario_destino The receiver of the message. - * @param string $subject Subject of the message (much like E-Mail). - * @param string $mensaje The actual message. This message will be - * cleaned by io_safe_input (html is allowed but - * loose html chars will be translated). + * @param string $usuario_origen The sender of the message. + * @param array $target_users The receiver of the message. + * @param array $target_groups Target groups to be delivered. + * @param string $subject Subject of the message (much like E-Mail). + * @param string $mensaje The actual message. This message will be + * cleaned by io_safe_input (html is allowed but + * loose html chars will be translated). * * @return boolean true when delivered, false in case of error */ function messages_create_message( string $usuario_origen, - string $usuario_destino, + array $target_users, + array $target_groups, string $subject, string $mensaje ) { $users = users_get_info(); - if (!array_key_exists($usuario_origen, $users) - || !array_key_exists($usuario_destino, $users) - ) { - return false; - // Users don't exist so don't send to them. - } - // Create message. $message_id = db_process_sql_insert( 'tmensajes', @@ -75,13 +130,19 @@ function messages_create_message( // Update URL // Update targets. if ($message_id !== false) { - $return = db_process_sql_insert( - 'tnotification_user', - [ - 'id_mensaje' => $message_id, - 'id_user' => $usuario_destino, - ] + $ret = message_set_targets( + $message_id, + $target_users, + $target_groups ); + if ($ret === false) { + // Failed to deliver messages. Erase message and show error. + db_process_sql_delete( + 'tmensajes', + ['id_mensaje' => $message_id] + ); + return false; + } } if ($return === false) { @@ -92,65 +153,6 @@ function messages_create_message( } -/** - * Creates private messages to be forwarded to groups - * - * @param string $usuario_origen The sender of the message. - * @param string $dest_group The receivers (group) of the message. - * @param string $subject Subject of the message (much like E-Mail). - * @param string $mensaje The actual message. This message will be - * cleaned by io_safe_input (html is allowed but - * loose html chars will be translated). - * - * @return boolean true when delivered, false in case of error - */ -function messages_create_group( - string $usuario_origen, - string $dest_group, - string $subject, - string $mensaje -) { - $users = users_get_info(); - $group_users = groups_get_users($dest_group); - - if (! array_key_exists($usuario_origen, $users)) { - // Users don't exist in the system. - return false; - } else if (empty($group_users)) { - /* - There are no users in the group, so it hasn't failed - although it hasn't done anything. - */ - - return true; - } - - // Array unique. - foreach ($group_users as $user) { - foreach ($user as $key => $us) { - if ($key == 'id_user') { - $group_user[$us] = $us; - } - } - } - - foreach ($group_user as $user) { - $return = messages_create_message( - $usuario_origen, - get_user_id($user), - $subject, - $mensaje - ); - if ($return === false) { - // Error sending message. - return false; - } - } - - return true; -} - - /** * Deletes a private message * @@ -160,8 +162,6 @@ function messages_create_group( */ function messages_delete_message(int $id_message) { - global $config; - // 'id_usuario_destino' => $config["id_user"], $where = ['id_mensaje' => $id_message]; return (bool) db_process_sql_delete('tmensajes', $where); } @@ -208,10 +208,9 @@ function messages_get_message(int $message_id) global $config; $sql = sprintf( - "SELECT id_usuario_origen, id_usuario_destino, subject, mensaje, timestamp + 'SELECT * FROM tmensajes - WHERE id_usuario_destino='%s' AND id_mensaje=%d", - $config['id_user'], + WHERE id_mensaje=%d', $message_id ); $row = db_get_row_sql($sql); @@ -239,7 +238,7 @@ function messages_get_message_sent(int $message_id) global $config; $sql = sprintf( - "SELECT id_usuario_origen, id_usuario_destino, subject, mensaje, timestamp + "SELECT id_usuario_origen, subject, mensaje, timestamp FROM tmensajes WHERE id_usuario_origen='%s' AND id_mensaje=%d", $config['id_user'], @@ -251,6 +250,16 @@ function messages_get_message_sent(int $message_id) return false; } + $targets = get_notification_targets($message_id); + + $row['id_usuario_destino'] = implode( + ',', + $targets['users'] + ).implode( + ',', + $targets['groups'] + ); + return $row; } @@ -281,15 +290,15 @@ function messages_get_count( } $sql = sprintf( - "SELECT count(*) FROM tmensajes tm + "SELECT count(tm.id_mensaje) FROM tmensajes tm left join tnotification_user nu ON tm.id_mensaje=nu.id_mensaje + AND nu.id_user='%s' left join tnotification_group ng ON tm.id_mensaje=ng.id_mensaje left join tusuario_perfil up - ON tm.id_mensaje=ng.id_mensaje - AND ng.id_group=up.id_grupo - WHERE (nu.id_user='%s' OR ng.id_group=0 OR up.id_grupo=ng.id_group) + ON ng.id_group=up.id_grupo + AND (ng.id_group=0 OR up.id_grupo=ng.id_group) %s", $config['id_user'], $filter @@ -359,36 +368,21 @@ function messages_get_overview( } $sql = sprintf( - "SELECT * FROM tmensajes tm + "SELECT tm.* FROM tmensajes tm left join tnotification_user nu ON tm.id_mensaje=nu.id_mensaje + AND nu.id_user='%s' left join tnotification_group ng ON tm.id_mensaje=ng.id_mensaje left join tusuario_perfil up - ON tm.id_mensaje=ng.id_mensaje - AND ng.id_group=up.id_grupo - WHERE (nu.id_user='%s' OR ng.id_group=0 OR up.id_grupo=ng.id_group) + ON ng.id_group=up.id_grupo + AND (ng.id_group=0 OR up.id_grupo=ng.id_group) ORDER BY %s", $config['id_user'], $order ); - $result = []; - $return = db_get_all_rows_sql($sql); - - if ($return === false) { - return $result; - } - - foreach ($return as $message) { - $id_message = $message['id_mensaje']; - $result[$id_message]['sender'] = $message['id_usuario_origen']; - $result[$id_message]['subject'] = $message['subject']; - $result[$id_message]['timestamp'] = $message['timestamp']; - $result[$id_message]['status'] = $message['estado']; - } - - return $result; + return db_get_all_rows_sql($sql); } @@ -427,25 +421,10 @@ function messages_get_overview_sent( $order .= ' DESC'; } - $result = []; - $return = db_get_all_rows_field_filter( + return db_get_all_rows_field_filter( 'tmensajes', 'id_usuario_origen', $config['id_user'], $order ); - - if ($return === false) { - return $result; - } - - foreach ($return as $message) { - $id_message = $message['id_mensaje']; - $result[$id_message]['dest'] = $message['id_usuario_destino']; - $result[$id_message]['subject'] = $message['subject']; - $result[$id_message]['timestamp'] = $message['timestamp']; - $result[$id_message]['status'] = $message['estado']; - } - - return $result; } diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 8372f54bf0..03f0b07963 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -1,10 +1,9 @@ [], + 'groups' => [], + ]; + + if (empty($id_message)) { + return $targets; + } + + $ret = db_get_all_rows_sql( + sprintf( + 'SELECT id_user + FROM tnotification_user nu + WHERE nu.id_mensaje = %d', + $id_message + ) + ); + + if (is_array($ret)) { + foreach ($ret as $row) { + array_push($targets['users'], $row['id_user']); + } + } + + $ret = $targets['groups'] = db_get_all_rows_sql( + sprintf( + 'SELECT id_group + FROM tnotification_group ng + WHERE ng.id_mensaje = %d', + $id_message + ) + ); + + if (is_array($ret)) { + foreach ($ret as $row) { + array_push($targets['groups'], $row['id_group']); + } + } + + return $targets; +} diff --git a/pandora_console/operation/messages/message_edit.php b/pandora_console/operation/messages/message_edit.php index 5df20ce9fe..a92abc19e8 100644 --- a/pandora_console/operation/messages/message_edit.php +++ b/pandora_console/operation/messages/message_edit.php @@ -1,26 +1,39 @@ false, - 'text' => '' . - html_print_image("images/email_inbox.png", true, array ("title" => __('Received messages'))) .''); +$buttons['message_list'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/email_inbox.png', + true, + ['title' => __('Received messages')] + ).'', +]; -$buttons['sent_messages'] = array('active' => false, - 'text' => '' . - html_print_image("images/email_outbox.png", true, array ("title" => __('Sent messages'))) .''); +$buttons['sent_messages'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/email_outbox.png', + true, + ['title' => __('Sent messages')] + ).'', +]; -$buttons['create_message'] = array('active' => true, - 'text' => '' . - html_print_image("images/new_message.png", true, array ("title" => __('Create message'))) .''); +$buttons['create_message'] = [ + 'active' => true, + 'text' => ''.html_print_image( + 'images/new_message.png', + true, + ['title' => __('Create message')] + ).'', +]; -// Header -ui_print_page_header (__('Messages'), "images/email_mc.png", false, "", false, $buttons); +// Header. +ui_print_page_header( + __('Messages'), + 'images/email_mc.png', + false, + '', + false, + $buttons +); -//read a message +// Read a message. if ($read_message) { - $message_id = (int) get_parameter ("id_message"); - if ($show_sent) { - $message = messages_get_message_sent ($message_id); - } - else { - $message = messages_get_message ($message_id); - messages_process_read ($message_id); - } - - if ($message == false) { - echo '
'.__('This message does not exist in the system').'
'; - return; //Move out of this page and go processing other pages - } - - $user_name = get_user_fullname ($message["id_usuario_origen"]); - if (!$user_name) { - $user_name = $message["id_usuario_origen"]; - } - - $dst_name = get_user_fullname ($message["id_usuario_destino"]); - if (!$dst_name) { - $dst_name = $message["id_usuario_destino"]; - } - - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox filters'; - $table->data = array(); - - $table->data[0][0] = __('Sender'); - $table->data[0][1] = $user_name.' '.__('at').' ' . ui_print_timestamp ($message["timestamp"], true, array ("prominent" => "timestamp")); - - $table->data[1][0] = __('Destination'); - $table->data[1][1] = $dst_name; - - $table->data[2][0] = __('Subject'); - $table->data[2][1] = html_print_input_text_extended ("subject", $message["subject"], 'text-subject', '', 50, 70, true, false, '', 'readonly'); - - $order = array("\r\n", "\n", "\r"); - $replace = '
'; - $parsed_message = str_replace($order, $replace, $message["mensaje"]); - - $table->data[3][0] = __('Message'); - $table->data[3][1] = html_print_textarea ("message", 15, 255, $message["mensaje"], 'readonly', true); - - //Prevent RE: RE: RE: - if (strstr ($message["subject"], "RE:")) { - $new_subj = $message["subject"]; - } - else { - $new_subj = "RE: ".$message["subject"]; - } - - //Start the message much like an e-mail reply - $new_msg = "\n\n\nOn ".date ($config["date_format"], $message["timestamp"]).' '.$user_name.' '.__('wrote').":\n\n".$message["mensaje"]; - - echo '
'; - html_print_table($table); - echo "
"; - - echo '
'; - html_print_input_hidden ("dst_user", $message["id_usuario_origen"]); - html_print_input_hidden ("subject", $new_subj); - html_print_input_hidden ("message", $new_msg); - html_print_input_hidden ("orig_user", $message["id_usuario_destino"]); - echo '
'; + $message_id = (int) get_parameter('id_message'); + if ($show_sent) { + $message = messages_get_message_sent($message_id); + } else { + $message = messages_get_message($message_id); + messages_process_read($message_id); + } - echo "
"; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'form="delete_message" class="sub delete"'); - echo " "; - html_print_submit_button (__('Reply'), 'reply', false, 'form="reply_message" class="sub next"'); - echo "
"; - - return; + if ($message == false) { + echo '
'.__('This message does not exist in the system').'
'; + return; + // Move out of this page and go processing other pages. + } + + $user_name = get_user_fullname($message['id_usuario_origen']); + if (!$user_name) { + $user_name = $message['id_usuario_origen']; + } + + $dst_name = get_user_fullname($message['id_usuario_destino']); + if (!$dst_name) { + $dst_name = $message['id_usuario_destino']; + } + + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox filters'; + $table->data = []; + + $table->data[0][0] = __('Sender'); + $table->data[0][1] = $user_name.' '.__('at').' '.ui_print_timestamp( + $message['timestamp'], + true, + ['prominent' => 'timestamp'] + ); + + $table->data[1][0] = __('Destination'); + $table->data[1][1] = $dst_name; + + $table->data[2][0] = __('Subject'); + $table->data[2][1] = html_print_input_text_extended( + 'subject', + $message['subject'], + 'text-subject', + '', + 50, + 70, + true, + false, + '', + 'readonly' + ); + + $order = [ + "\r\n", + "\n", + "\r", + ]; + $replace = '
'; + $parsed_message = str_replace($order, $replace, $message['mensaje']); + + $table->data[3][0] = __('Message'); + $table->data[3][1] = html_print_textarea( + 'message', + 15, + 255, + $message['mensaje'], + 'readonly', + true + ); + + // Prevent RE: RE: RE:. + if (strstr($message['subject'], 'RE:')) { + $new_subj = $message['subject']; + } else { + $new_subj = 'RE: '.$message['subject']; + } + + // Start the message much like an e-mail reply. + $new_msg = "\n\n\nOn ".date( + $config['date_format'], + $message['timestamp'] + ).' '.$user_name.' '.__('wrote').":\n\n".$message['mensaje']; + + echo '
'; + html_print_table($table); + echo '
'; + + echo '
'; + html_print_input_hidden('dst_user', $message['id_usuario_origen']); + html_print_input_hidden('subject', $new_subj); + html_print_input_hidden('message', $new_msg); + html_print_input_hidden('orig_user', $message['id_usuario_destino']); + echo '
'; + + echo "
"; + html_print_submit_button( + __('Delete'), + 'delete_btn', + false, + 'form="delete_message" class="sub delete"' + ); + echo ' '; + html_print_submit_button( + __('Reply'), + 'reply', + false, + 'form="reply_message" class="sub next"' + ); + echo '
'; + + return; } -// Create message (destination user) -if (($new_msg) && (!empty ($dst_user)) && (!$reply)) { - $return = messages_create_message ($config["id_user"], $dst_user, $subject, $message); - - $user_name = get_user_fullname ($dst_user); - if (!$user_name) { - $user_name = $dst_user; - } - - ui_print_result_message ($return, - __('Message successfully sent to user %s', $user_name), - __('Error sending message to user %s', $user_name)); +// Create message (destination user). +if (($new_msg) && (!empty($dst_user)) && (!$reply)) { + $return = messages_create_message( + $config['id_user'], + [$dst_user], + [], + $subject, + $message + ); + + $user_name = get_user_fullname($dst_user); + if (!$user_name) { + $user_name = $dst_user; + } + + ui_print_result_message( + $return, + __('Message successfully sent to user %s', $user_name), + __('Error sending message to user %s', $user_name) + ); } -// Create message (destination group) -if (($new_msg) && ($dst_group!='') && (!$reply)) { - $return = messages_create_group ($config["id_user"], $dst_group, $subject, $message); - - ui_print_result_message ($return, - __('Message successfully sent'), - __('Error sending message to group %s', groups_get_name ($dst_group))); +// Create message (destination group). +if (($new_msg) && ($dst_group != '') && (!$reply)) { + $return = messages_create_message( + $config['id_user'], + [], + [$dst_group], + $subject, + $message + ); + + ui_print_result_message( + $return, + __('Message successfully sent'), + __('Error sending message to group %s', groups_get_name($dst_group)) + ); } -//message creation form - -//user info -$own_info = get_user_info ($config['id_user']); +// Message creation form. +// User info. +$own_info = get_user_info($config['id_user']); $table = new stdClass(); $table->width = '100%'; $table->class = 'databox filters'; -$table->data = array(); +$table->data = []; $table->data[0][0] = __('Sender'); if (!empty($own_info['fullname'])) { - $table->data[0][1] = $own_info['fullname']; -} -else { - $table->data[0][1] = $config['id_user']; + $table->data[0][1] = $own_info['fullname']; +} else { + $table->data[0][1] = $config['id_user']; } $table->data[1][0] = __('Destination'); -$is_admin = (bool)db_get_value('is_admin', 'tusuario', 'id_user', $config['id_user']); +$is_admin = (bool) db_get_value( + 'is_admin', + 'tusuario', + 'id_user', + $config['id_user'] +); if ($is_admin) { - $users_full = db_get_all_rows_filter('tusuario', array(), array('id_user', 'fullname')); -} -else { - $users_full = groups_get_users (array_keys(users_get_groups()), false, false); + $users_full = db_get_all_rows_filter( + 'tusuario', + [], + [ + 'id_user', + 'fullname', + ] + ); +} else { + $users_full = groups_get_users( + array_keys(users_get_groups()), + false, + false + ); } -$users = array(); +$users = []; foreach ($users_full as $user_id => $user_info) { - $users[$user_info['id_user']] = $user_info['fullname']; + $users[$user_info['id_user']] = $user_info['fullname']; } -//Check if the user to reply is in the list, if not add reply user +// Check if the user to reply is in the list, if not add reply user. if ($reply) { - if (!array_key_exists($dst_user, $users)) { - //Add the user to reply - $user_reply = db_get_row('tusuario', 'id_user', $dst_user); - $users[$user_reply['id_user']] = $user_reply['fullname']; - } + if (!array_key_exists($dst_user, $users)) { + // Add the user to reply. + $user_reply = db_get_row('tusuario', 'id_user', $dst_user); + $users[$user_reply['id_user']] = $user_reply['fullname']; + } } -if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "PM")) - $return_all_groups = true; -else - $return_all_groups = false; +if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $return_all_groups = true; +} else { + $return_all_groups = false; +} -$groups = users_get_groups ($config["id_user"], "AR"); //Get a list of all groups - -$table->data[1][1] = html_print_select ($users, "dst_user", $dst_user, '', __('Select user'), false, true, false, '', false); +$groups = users_get_groups($config['id_user'], 'AR'); +// Get a list of all groups. +$table->data[1][1] = html_print_select( + $users, + 'dst_user', + $dst_user, + '', + __('Select user'), + false, + true, + false, + '', + false +); $table->data[1][1] .= '  '.__('OR').'  '; -$table->data[1][1] .= html_print_select_groups($config['id_user'], "AR", $return_all_groups, 'dst_group', $dst_group, '', __('Select group'), '', true); +$table->data[1][1] .= html_print_select_groups( + $config['id_user'], + 'AR', + $return_all_groups, + 'dst_group', + $dst_group, + '', + __('Select group'), + '', + true +); $table->data[2][0] = __('Subject'); -$table->data[2][1] = html_print_input_text ("subject", $subject, '', 50, 70, true); +$table->data[2][1] = html_print_input_text( + 'subject', + $subject, + '', + 50, + 70, + true +); $table->data[3][0] = __('Message'); -$table->data[3][1] = html_print_textarea ("message", 15, 255, $message, '', true); +$table->data[3][1] = html_print_textarea( + 'message', + 15, + 255, + $message, + '', + true +); echo '
'; html_print_table($table); echo '
'; - html_print_submit_button (__('Send message'), 'send_mes', false, 'class="sub wand"'); -echo ''; -echo '
'; -?> + html_print_submit_button( + __('Send message'), + 'send_mes', + false, + 'class="sub wand"' + ); + echo ''; + echo ''; diff --git a/pandora_console/operation/messages/message_list.php b/pandora_console/operation/messages/message_list.php index d0ebb09cb3..49ecfe14dd 100644 --- a/pandora_console/operation/messages/message_list.php +++ b/pandora_console/operation/messages/message_list.php @@ -88,13 +88,10 @@ if ($delete_msg) { } if ($multiple_delete) { - $ids = (array) get_parameter('delete_multiple', []); + $ids = (array) get_parameter('delete_multiple_messages', []); foreach ($ids as $id) { - $result = db_process_sql_delete( - 'tmensajes', - ['id_mensaje' => $id] - ); + $result = messages_delete_message($id); if ($result === false) { break; @@ -166,7 +163,9 @@ if (empty($messages)) { $table->head[3] = __('Timestamp'); $table->head[4] = __('Delete').html_print_checkbox('all_delete_messages', 0, false, true, false); - foreach ($messages as $message_id => $message) { + + foreach ($messages as $message) { + $message_id = $message['id_mensaje']; $data = []; $data[0] = ''; if ($message['status'] == 1) { From 9af1680e1589cac3013d46c45b40317bf3f59563 Mon Sep 17 00:00:00 2001 From: daniel Date: Wed, 30 Jan 2019 16:57:07 +0100 Subject: [PATCH 020/249] fixed error php7 info install and RPM Former-commit-id: 4c38ee93e01d2ff88bb0d3dc563cf7bbbbcd9946 --- pandora_console/install.php | 3 +-- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/pandora_console/install.php b/pandora_console/install.php index 18a2a6d9cb..493cc357d0 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -487,7 +487,7 @@ function install_step2() { echo "

Checking software dependencies

"; echo ""; $res = 0; - $res += check_variable(phpversion(),"5.2","PHP version >= 5.2",1); + $res += check_variable(phpversion(),"7.0","PHP version >= 7.0",1); $res += check_extension("gd","PHP GD extension"); $res += check_extension("ldap","PHP LDAP extension"); $res += check_extension("snmp","PHP SNMP extension"); @@ -518,7 +518,6 @@ function install_step2() { font-size: 8.5pt;margin-top: 2px; font-weight: bolder;'>DB Engines"; echo ""; - check_extension("mysql", "PHP MySQL extension"); check_extension("mysqli", "PHP MySQL(mysqli) extension"); echo "
"; echo "
"; diff --git a/pandora_console/pandora_console.redhat.spec b/pandora_console/pandora_console.redhat.spec index 3ece0b1383..f8cca88d0a 100644 --- a/pandora_console/pandora_console.redhat.spec +++ b/pandora_console/pandora_console.redhat.spec @@ -26,7 +26,7 @@ BuildRoot: %{_tmppath}/%{name} BuildArch: noarch AutoReq: 0 Requires: %{httpd_name} >= 2.0.0 -Requires: mod_php >= 5.2.0 +Requires: mod_php >= 7.0 Requires: php-gd, php-ldap, php-snmp, php-session, php-gettext Requires: php-mysqlnd, php-mbstring, php-zip, php-zlib, php-curl Requires: xorg-x11-fonts-75dpi, xorg-x11-fonts-misc, php-pecl-zip diff --git a/pandora_console/pandora_console.spec b/pandora_console/pandora_console.spec index 91dcf164e1..7e3d73910f 100644 --- a/pandora_console/pandora_console.spec +++ b/pandora_console/pandora_console.spec @@ -29,7 +29,7 @@ BuildArch: noarch AutoReq: 0 Requires: apache2 Requires: apache2-mod_php7 -Requires: php >= 4.3.0 +Requires: php >= 7.0 Requires: php-gd, php-snmp, php-json, php-gettext Requires: php-mysqlnd, php-ldap, php-mbstring, php Requires: graphviz, xorg-x11-fonts-core, graphviz-gd From 3f81e60df245f2e752f4d2c5fc3eaa973a6373be Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 30 Jan 2019 17:33:31 +0100 Subject: [PATCH 021/249] wip messages Former-commit-id: 7852ce90b3f2681a0134a651812341f7fac00c53 --- .../include/functions_messages.php | 184 +++++++++++++----- .../include/functions_notifications.php | 51 ++++- .../operation/messages/message_edit.php | 2 +- .../operation/messages/message_list.php | 14 +- 4 files changed, 195 insertions(+), 56 deletions(-) diff --git a/pandora_console/include/functions_messages.php b/pandora_console/include/functions_messages.php index 3d163825c3..7552dc74f2 100644 --- a/pandora_console/include/functions_messages.php +++ b/pandora_console/include/functions_messages.php @@ -73,7 +73,7 @@ function message_set_targets( if (is_array($groups)) { $values = []; foreach ($groups as $group) { - if (empty($group)) { + if ($group != 0 && empty($group)) { continue; } @@ -162,8 +162,43 @@ function messages_create_message( */ function messages_delete_message(int $id_message) { - $where = ['id_mensaje' => $id_message]; - return (bool) db_process_sql_delete('tmensajes', $where); + global $config; + + // Check if user has grants to access the message. + if (check_notification_readable($id_message) === false) { + return false; + } + + $utimestamp = time(); + + $ret = db_process_sql_update( + 'tnotification_user', + ['utimestamp_erased' => $utimestamp], + [ + 'id_mensaje' => $id_message, + 'id_user' => $config['id_user'], + ] + ); + + if ($ret === 0) { + // No previous updates. + // Message available to user due group assignment. + $ret = db_process_sql_insert( + 'tnotification_user', + [ + 'id_mensaje' => $id_message, + 'id_user' => $config['id_user'], + 'utimestamp_erased' => $utimestamp, + ] + ); + + // Quick fix. Insertions returns 0. + if ($ret !== false) { + $ret = 1; + } + } + + return (bool) $ret; } @@ -179,17 +214,45 @@ function messages_process_read( int $message_id, bool $read=true ) { - if (empty($read)) { - $read = 0; - } else { - $read = 1; + global $config; + + // Check if user has grants to read the message. + if (check_notification_readable($message_id) === false) { + return false; } - return (bool) db_process_sql_update( - 'tmensajes', - ['estado' => $read], - ['id_mensaje' => $message_id] + if (empty($read)) { + // Mark as unread. + $utimestamp = null; + } else { + // Mark as read. + $utimestamp = time(); + } + + $ret = db_process_sql_update( + 'tnotification_user', + ['utimestamp_read' => $utimestamp], + [ + 'id_mensaje' => $message_id, + 'id_user' => $config['id_user'], + 'utimestamp_read' => null, + ] ); + + if ($ret === 0) { + // No previous updates. + // Message available to user due group assignment. + $ret = db_process_sql_insert( + 'tnotification_user', + [ + 'id_mensaje' => $message_id, + 'id_user' => $config['id_user'], + 'utimestamp_read' => $utimestamp, + ] + ); + } + + return (bool) $ret; } @@ -207,10 +270,17 @@ function messages_get_message(int $message_id) { global $config; + // Check if user has grants to read the message. + if (check_notification_readable($message_id) === false) { + return false; + } + $sql = sprintf( - 'SELECT * - FROM tmensajes - WHERE id_mensaje=%d', + 'SELECT *, nu.utimestamp_read > 0 as "read" + FROM tmensajes tm + LEFT JOIN tnotification_user nu + ON nu.id_mensaje = tm.id_mensaje + WHERE tm.id_mensaje=%d', $message_id ); $row = db_get_row_sql($sql); @@ -219,6 +289,8 @@ function messages_get_message(int $message_id) return false; } + $row['id_usuario_destino'] = $config['id_user']; + return $row; } @@ -255,7 +327,7 @@ function messages_get_message_sent(int $message_id) $row['id_usuario_destino'] = implode( ',', $targets['users'] - ).implode( + ).','.implode( ',', $targets['groups'] ); @@ -282,26 +354,30 @@ function messages_get_count( } if (!empty($incl_read)) { - // Retrieve only unread messages. - $filter = 'AND nu.uptimestap_read == NULL'; - } else { // Do not filter. - $filter = ''; + $read = ''; + } else { + // Retrieve only unread messages. + $read = 'where t.read is null'; } $sql = sprintf( - "SELECT count(tm.id_mensaje) FROM tmensajes tm - left join tnotification_user nu - ON tm.id_mensaje=nu.id_mensaje - AND nu.id_user='%s' - left join tnotification_group ng - ON tm.id_mensaje=ng.id_mensaje - left join tusuario_perfil up - ON ng.id_group=up.id_grupo - AND (ng.id_group=0 OR up.id_grupo=ng.id_group) - %s", - $config['id_user'], - $filter + 'SELECT count(*) FROM ( + SELECT tm.*, utimestamp_read > 0 as "read" FROM tmensajes tm + LEFT JOIN tnotification_user nu + ON tm.id_mensaje=nu.id_mensaje + LEFT JOIN (tnotification_group ng + INNER JOIN tusuario_perfil up + ON ng.id_group=up.id_grupo + AND up.id_grupo=ng.id_group + ) ON tm.id_mensaje=ng.id_mensaje + WHERE utimestamp_erased is null + AND (up.id_usuario="%s" OR nu.id_user="%s" OR ng.id_group=0) + ) t + %s', + $user, + $user, + $read ); return (int) db_get_sql($sql); @@ -335,16 +411,18 @@ function messages_get_count_sent(string $user='') /** * Get message overview in array * - * @param string $order How to order them valid: - * (status (default), subject, timestamp, sender). - * @param string $order_dir Direction of order - * (ASC = Ascending, DESC = Descending). + * @param string $order How to order them valid: + * (status (default), subject, timestamp, sender). + * @param string $order_dir Direction of order + * (ASC = Ascending, DESC = Descending). + * @param boolean $incl_read Include read messages in return. * * @return integer The number of messages this user has */ function messages_get_overview( string $order='status', - string $order_dir='ASC' + string $order_dir='ASC', + bool $incl_read=true ) { global $config; @@ -367,18 +445,32 @@ function messages_get_overview( $order .= ' DESC'; } + if (!empty($incl_read)) { + // Do not filter. + $read = ''; + } else { + // Retrieve only unread messages. + $read = 'where t.read is null'; + } + $sql = sprintf( - "SELECT tm.* FROM tmensajes tm - left join tnotification_user nu - ON tm.id_mensaje=nu.id_mensaje - AND nu.id_user='%s' - left join tnotification_group ng - ON tm.id_mensaje=ng.id_mensaje - left join tusuario_perfil up - ON ng.id_group=up.id_grupo - AND (ng.id_group=0 OR up.id_grupo=ng.id_group) - ORDER BY %s", + 'SELECT * FROM ( + SELECT tm.*, utimestamp_read > 0 as "read" FROM tmensajes tm + LEFT JOIN tnotification_user nu + ON tm.id_mensaje=nu.id_mensaje + LEFT JOIN (tnotification_group ng + INNER JOIN tusuario_perfil up + ON ng.id_group=up.id_grupo + AND up.id_grupo=ng.id_group + ) ON tm.id_mensaje=ng.id_mensaje + WHERE utimestamp_erased is null + AND (up.id_usuario="%s" OR nu.id_user="%s" OR ng.id_group=0) + ) t + %s + ORDER BY %s', $config['id_user'], + $config['id_user'], + $read, $order ); diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 03f0b07963..3005e9a47c 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -81,14 +81,19 @@ function get_notification_targets(int $id_message) if (is_array($ret)) { foreach ($ret as $row) { - array_push($targets['users'], $row['id_user']); + array_push( + $targets['users'], + get_user_fullname($row['id_user']) + ); } } - $ret = $targets['groups'] = db_get_all_rows_sql( + $ret = db_get_all_rows_sql( sprintf( - 'SELECT id_group + 'SELECT COALESCE(tg.nombre,ng.id_group) as "id_group" FROM tnotification_group ng + LEFT JOIN tgrupo tg + ON tg.id_grupo=ng.id_group WHERE ng.id_mensaje = %d', $id_message ) @@ -96,9 +101,49 @@ function get_notification_targets(int $id_message) if (is_array($ret)) { foreach ($ret as $row) { + if ($row['id_group'] == '0') { + $row['id_group'] = ''.__('All').''; + } + array_push($targets['groups'], $row['id_group']); } } return $targets; } + + +/** + * Check if current user has grants to read this notification + * + * @param integer $id_message Target message. + * + * @return boolean true, read available. False if not. + */ +function check_notification_readable(int $id_message) +{ + global $config; + + if (empty($id_message)) { + return false; + } + + $sql = sprintf( + 'SELECT tm.*, utimestamp_read > 0 as "read" FROM tmensajes tm + LEFT JOIN tnotification_user nu + ON tm.id_mensaje=nu.id_mensaje + AND tm.id_mensaje=%d + LEFT JOIN (tnotification_group ng + INNER JOIN tusuario_perfil up + ON ng.id_group=up.id_grupo + AND up.id_grupo=ng.id_group + ) ON tm.id_mensaje=ng.id_mensaje + WHERE utimestamp_erased is null + AND (up.id_usuario="%s" OR nu.id_user="%s" OR ng.id_group=0)', + $id_message, + $config['id_user'], + $config['id_user'] + ); + + return (bool) db_get_value_sql($sql); +} diff --git a/pandora_console/operation/messages/message_edit.php b/pandora_console/operation/messages/message_edit.php index a92abc19e8..b284bc3d13 100644 --- a/pandora_console/operation/messages/message_edit.php +++ b/pandora_console/operation/messages/message_edit.php @@ -90,7 +90,7 @@ if ($read_message) { messages_process_read($message_id); } - if ($message == false) { + if ($message === false) { echo '
'.__('This message does not exist in the system').'
'; return; // Move out of this page and go processing other pages. diff --git a/pandora_console/operation/messages/message_list.php b/pandora_console/operation/messages/message_list.php index 49ecfe14dd..4a6d48a397 100644 --- a/pandora_console/operation/messages/message_list.php +++ b/pandora_console/operation/messages/message_list.php @@ -109,18 +109,20 @@ if ($show_sent) { // Sent view. $num_messages = messages_get_count_sent($config['id_user']); if ($num_messages > 0 && !is_ajax()) { - echo '

'.__('You have').' '.$num_messages.''.__('sent message(s)').'.

'; + echo '

'.__('You have').' '.$num_messages.' '.__('sent message(s)').'.

'; } $messages = messages_get_overview_sent('', 'DESC'); } else { // Messages received. - $num_messages = messages_get_count($config['id_user']); + $num_messages = messages_get_count($config['id_user'], true); if ($num_messages > 0 && !is_ajax()) { - echo '

'.__('You have').' '.$num_messages.''.__('unread message(s)').'.

'; + $unread_messages = messages_get_count($config['id_user']); + echo '

'.__('You have').' '.$unread_messages.' '.__('unread message(s)').'.

'; + $messages = messages_get_overview(); + } else { + $messages = messages_get_overview('status', 'ASC', false); } - - $messages = messages_get_overview(); } if (empty($messages)) { @@ -168,7 +170,7 @@ if (empty($messages)) { $message_id = $message['id_mensaje']; $data = []; $data[0] = ''; - if ($message['status'] == 1) { + if ($message['read'] == 1) { if ($show_sent) { $data[0] .= ''; $data[0] .= html_print_image('images/email_open.png', true, ['border' => 0, 'title' => __('Click to read')]); From 397f2964da997b91a7f36463f1eb8d7eec2c19cd Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 31 Jan 2019 15:16:56 +0100 Subject: [PATCH 022/249] Added messages notification ball Former-commit-id: c44a99cf63bc7451890389e4d234fd8aa7b62cbc --- pandora_console/general/header.php | 4 +++- .../include/functions_notifications.php | 16 ++++++++++++++++ pandora_console/include/styles/pandora.css | 17 +++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index c26bed8762..1edcf76b77 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -16,6 +16,7 @@ require_once ("include/functions_messages.php"); require_once ('include/functions_servers.php'); +require_once ('include/functions_notifications.php'); // Check permissions @@ -65,6 +66,7 @@ config_check(); $table->style[8] = $table->style[9] = $table->style['qr'] = + $table->style['notifications'] = 'width: 22px; text-align:center; height: 22px; padding-right: 9px;padding-left: 9px;'; $table->style[7] = 'width: 20px; padding-right: 9px;'; $table->style['searchbar'] = 'width: 180px; min-width: 180px;'; @@ -360,7 +362,7 @@ config_check(); $table->data[0][9] .= ''; } - + $table->data[0]['notifications'] = notifications_print_ball(); html_print_table($table); diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 3005e9a47c..5c9bb71885 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -147,3 +147,19 @@ function check_notification_readable(int $id_message) return (bool) db_get_value_sql($sql); } + +/** + * Print the notification ball to see unread messages + * + * @return string with HTML code of notification ball + */ +function notifications_print_ball() { + $num_notifications = messages_get_count(); + $class_status = $num_notifications == 0 + ? 'notification-ball-no-messages' + : 'notification-ball-new-messages'; + return + "
+ $num_notifications +
"; +} diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index f42c64f70a..15d81dbbb5 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4912,6 +4912,23 @@ div#dialog_messages table th:last-child { text-align: right; } +.notification-ball { + border: white solid 2px; + border-radius: 50px; + width: 18px; + height: 18px; + display: flex; + justify-content: center; + align-items: center; +} + +.notification-ball-no-messages { + background-color: #82b92e; +} +.notification-ball-new-messages { + background-color: #fc4444; +} + /* --- JQUERY-UI --- */ .ui-button-text-only .ui-button-text { font-family: "nunito", sans-serif; From 95f3c063a51ef417ed3f98262396382751796cc5 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 31 Jan 2019 16:27:55 +0100 Subject: [PATCH 023/249] Added tnotification_source_group_user table Former-commit-id: e1b542a76ceb0e80f49904c16a98e44c14fff1ff --- .../pandoradb_migrate_6.0_to_7.0.mysql.sql | 19 +++++++++++++++++++ pandora_console/pandoradb.sql | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index e62e76efd5..482fcb8f4e 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1953,6 +1953,25 @@ CREATE TABLE `tnotification_source_group` ( `id_source` BIGINT(20) UNSIGNED NOT NULL, `id_group` mediumint(4) unsigned NOT NULL, PRIMARY KEY (`id_source`,`id_group`), + INDEX (`id_group`), FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- ---------------------------------------------------------------------- +-- Table `tnotification_source_user` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_source_group_user` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL, + `id_user` VARCHAR(60), + `enabled` INT(1) DEFAULT NULL, + `also_mail` INT(1) DEFAULT NULL, + PRIMARY KEY (`id_source`,`id_user`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_group`) REFERENCES `tnotification_source_group`(`id_group`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; \ No newline at end of file diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index c70650c70b..daae31bf5d 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -1246,10 +1246,29 @@ CREATE TABLE `tnotification_source_group` ( `id_source` BIGINT(20) UNSIGNED NOT NULL, `id_group` mediumint(4) unsigned NOT NULL, PRIMARY KEY (`id_source`,`id_group`), + INDEX (`id_group`), FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +-- ---------------------------------------------------------------------- +-- Table `tnotification_source_user` +-- ---------------------------------------------------------------------- +CREATE TABLE `tnotification_source_group_user` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL, + `id_user` VARCHAR(60), + `enabled` INT(1) DEFAULT NULL, + `also_mail` INT(1) DEFAULT NULL, + PRIMARY KEY (`id_source`,`id_user`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_group`) REFERENCES `tnotification_source_group`(`id_group`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + -- ---------------------------------------------------------------------- -- Table `tnews` -- ---------------------------------------------------------------------- From b589826c8602f4c93096a3825af7453c8ef4b053 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 31 Jan 2019 19:11:59 +0100 Subject: [PATCH 024/249] Added HTML switch element Former-commit-id: 426557a47577fd9b5b2002ed02d70f1effb92162 --- pandora_console/include/functions.php | 11 +++++ pandora_console/include/functions_html.php | 19 ++++++++ pandora_console/include/styles/pandora.css | 56 ++++++++++++++++++++++ 3 files changed, 86 insertions(+) diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index 6741f08bc1..bce19cadda 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -3516,4 +3516,15 @@ function mask2cidr($mask){ return 32-log(($long ^ $base)+1,2); } +/** + * Convert the checkbox result to 1 or 0 + * + * @param string $value Param returned by swith fomulary. + * + * @return int 1 if value is "on". 0 otherwise. + */ +function switch_to_int(string $value) { + return $value === "on" ? 1 : 0; +} + ?> diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index a3e3358c82..8510b5e259 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -2580,4 +2580,23 @@ function html_print_csrf_error () { ); return true; } + +/** + * Print an swith button + * + * @param array $atributes. Valid params: + * name: Usefull to handle in forms + * value: If is checked or not + * @return string with HTML of button + */ +function html_print_switch ($attributes = array()) { + + $name_html = isset($attributes['name']) ? "name = {$attributes['name']}" : ''; + $checked_html = (bool)$attributes['value'] ? 'checked' : ''; + return + ""; +} ?> diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 15d81dbbb5..6256d1a7c0 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -5175,3 +5175,59 @@ input[type="submit"].ui-button-dialog { width: 90px !important; } /* --- END - JQUERY-UI --- */ + +/* --- SWITCH --- */ +.p-switch { + position: relative; + display: inline-block; + width: 30px; + height: 17px; +} + +.p-switch input { + opacity: 0; + width: 0; + height: 0; +} + +.p-slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: #ccc; + -webkit-transition: 0.4s; + transition: 0.4s; + border-radius: 34px; +} + +.p-slider:before { + position: absolute; + content: ""; + height: 13px; + width: 13px; + left: 2px; + bottom: 2px; + background-color: white; + -webkit-transition: 0.4s; + transition: 0.4s; + border-radius: 50%; +} + +input:checked + .p-slider { + background-color: #82b92e; +} + +input:focus + .p-slider { + box-shadow: 0 0 1px #82b92e; +} + +input:checked + .p-slider:before { + -webkit-transform: translateX(13px); + -ms-transform: translateX(13px); + transform: translateX(13px); +} + +/* --- END SWITCH --- */ From 01bc0775bcaaef3140de22afc40b600c90ea83c6 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 31 Jan 2019 19:13:51 +0100 Subject: [PATCH 025/249] Added notification global configuration (only enable and disable) Former-commit-id: 850d4dd1d8e30fc66623308b8ab148eaeadb5015 --- pandora_console/godmode/menu.php | 5 +- pandora_console/godmode/setup/setup.php | 12 ++++ .../godmode/setup/setup_notifications.php | 66 +++++++++++++++++++ .../include/functions_notifications.php | 54 +++++++++++++-- pandora_console/include/styles/pandora.css | 10 +++ 5 files changed, 140 insertions(+), 7 deletions(-) create mode 100644 pandora_console/godmode/setup/setup_notifications.php diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index 8ad895ff35..854a897349 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -271,7 +271,10 @@ if (check_acl ($config['id_user'], 0, "PM")) { $sub2["godmode/setup/setup&section=ehorus"]["text"] = __('eHorus'); $sub2["godmode/setup/setup&section=ehorus"]["refr"] = 0; - + + $sub2["godmode/setup/setup&section=notifications"]["text"] = __('Notifications'); + $sub2["godmode/setup/setup&section=notifications"]["refr"] = 0; + if ($config['activate_gis']) { $sub2["godmode/setup/gis"]["text"] = __('Map conections GIS'); } diff --git a/pandora_console/godmode/setup/setup.php b/pandora_console/godmode/setup/setup.php index 1b4f2a208c..59652d6f1a 100644 --- a/pandora_console/godmode/setup/setup.php +++ b/pandora_console/godmode/setup/setup.php @@ -101,6 +101,11 @@ $buttons['ehorus'] = array('active' => false, 'text' => '' . html_print_image("images/ehorus/ehorus.png", true, array ("title" => __('eHorus'))) . ''); +// FIXME: Not definitive icon +$buttons['notifications'] = array('active' => false, + 'text' => '' . + html_print_image("images/alerts_template.png", true, array ("title" => __('Notifications'))) . ''); + $help_header = ''; if (enterprise_installed()) { $subpage = setup_enterprise_add_subsection_main($section, $buttons, $help_header); @@ -132,6 +137,10 @@ switch ($section) { $buttons['ehorus']['active'] = true; $subpage = ' » ' . __('eHorus'); break; + case 'notifications': + $buttons['notifications']['active'] = true; + $subpage = ' » ' . __('Notifications'); + break; } // Header @@ -167,6 +176,9 @@ switch ($section) { case "ehorus": require_once($config['homedir'] . "/godmode/setup/setup_ehorus.php"); break; + case "notifications": + require_once($config['homedir'] . "/godmode/setup/setup_notifications.php"); + break; default: enterprise_hook('setup_enterprise_select_tab', array($section)); break; diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php new file mode 100644 index 0000000000..f598a00a9c --- /dev/null +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -0,0 +1,66 @@ + $enable_value), + array('id' => $source['id']) + ); + return $res && $carry; + }, true); +} + +// Notification table. It is just a wrapper. +$table_content = new StdClass(); +$table_content->data = array(); +$table_content->width = '100%'; +$table_content->id = 'notifications-wrapper'; +$table_content->class = 'databox filters'; +$table_content->size['name'] = '30%'; +$table_remote->style['name'] = 'font-weight: bold'; + +// Print each source configuration +$table_content->data = array_map(function ($source) { + return notifications_print_global_source_configuration($source); +}, notifications_get_all_sources()); +$table_content->data[] = html_print_submit_button( + __('Update'), 'update_button', false, 'class="sub upd" style="display: flex; "', true +); + +echo '
'; +html_print_input_hidden('update_config', 1); +html_print_table($table_content); +echo '
'; + diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 5c9bb71885..c59b44f1fd 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -42,15 +42,24 @@ function get_notification_source_id(string $source) } return db_get_value_sql( - sprintf( - 'SELECT id - FROM `tnotification_source` - WHERE lower(`description`) = lower("%s")', - $source - ) + "SELECT id + FROM `tnotification_source` + WHERE `description` LIKE '{$source}%'" ); } +/** + * Converts description into a handable identifier + * + * @param string $desc Full description + * + * @return string First word in lowercase. Empty string if no word detected. + */ +function notifications_desc_to_id(string $desc) { + preg_match('/^[a-zA-Z]*/', $desc, $matches); + $match = $matches[0]; + return isset($match) ? $match : ''; +} /** * Retrieve all targets for given message. @@ -148,6 +157,15 @@ function check_notification_readable(int $id_message) return (bool) db_get_value_sql($sql); } +/** + * Return all info from tnotification_source + * + * @return array with sources info + */ +function notifications_get_all_sources() { + return mysql_db_get_all_rows_in_table('tnotification_source'); +} + /** * Print the notification ball to see unread messages * @@ -163,3 +181,27 @@ function notifications_print_ball() { $num_notifications "; } + +/** + * Print notification configuration global + * + * @param array notification source data + * + * @return string with HTML of source configuration + */ +function notifications_print_global_source_configuration($source) { + + // Get some values to generate the title + $switch_values = array ( + 'name' => "enable-" . notifications_desc_to_id($source['description']), + 'value' => $source['enabled'] + ); + // Generate the title + $html_title = "
"; + $html_title .= html_print_switch($switch_values); + $html_title .= "

{$source['description']}

"; + $html_title .= "
"; + + // Return all html + return $html_title; +} diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 6256d1a7c0..924e147895 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4929,6 +4929,16 @@ div#dialog_messages table th:last-child { background-color: #fc4444; } +.global-config-notification-title { + display: flex; + flex-direction: row; + align-items: center; +} + +.global-config-notification-title h2 { + margin-left: 10px; +} + /* --- JQUERY-UI --- */ .ui-button-text-only .ui-button-text { font-family: "nunito", sans-serif; From 75eaa875c93847a7759f818e6da1ecca5bfc43d1 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 31 Jan 2019 19:43:13 +0100 Subject: [PATCH 026/249] Added checkboxes to notifications global configuration Former-commit-id: 79df159f003292dfef697773fe8daa25b77f04c2 --- .../godmode/setup/setup_notifications.php | 6 +++++- .../include/functions_notifications.php | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index f598a00a9c..40a4031dbb 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -32,10 +32,14 @@ if (get_parameter('update_config', 0)) { $id = notifications_desc_to_id($source['description']); if (empty($id)) return false; $enable_value = switch_to_int(get_parameter("enable-$id")); + $mail_value = (int)get_parameter("mail-{$id}", 0); + $user_value = (int)get_parameter("user-{$id}", 0); $res = mysql_db_process_sql_update( 'tnotification_source', array( - 'enabled' => $enable_value), + 'enabled' => $enable_value, + 'user_editable' => $user_value, + 'also_mail' => $mail_value), array('id' => $source['id']) ); return $res && $carry; diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index c59b44f1fd..d7810417db 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -192,8 +192,9 @@ function notifications_print_ball() { function notifications_print_global_source_configuration($source) { // Get some values to generate the title + $id = notifications_desc_to_id($source['description']); $switch_values = array ( - 'name' => "enable-" . notifications_desc_to_id($source['description']), + 'name' => "enable-" . $id, 'value' => $source['enabled'] ); // Generate the title @@ -202,6 +203,17 @@ function notifications_print_global_source_configuration($source) { $html_title .= "

{$source['description']}

"; $html_title .= ""; + // Generate the checkboxes and time select + $html_checkboxes = "
"; + $html_checkboxes .= " "; + $html_checkboxes .= html_print_checkbox("mail-$id", 1, $source['also_mail'], true); + $html_checkboxes .= __('Also email users with notification content'); + $html_checkboxes .= "
"; + $html_checkboxes .= html_print_checkbox("user-$id", 1, $source['user_editable'], true); + $html_checkboxes .= __('Users cannot modify notification preferences'); + $html_checkboxes .= " "; + $html_checkboxes .= "
"; + // Return all html - return $html_title; + return $html_title . $html_checkboxes; } From 1c0a5ca247930bae3b6378b053d7876e16ad7d62 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 31 Jan 2019 20:11:43 +0100 Subject: [PATCH 027/249] Added pospone select (fixme) Former-commit-id: 428b4424a15ef54c4d95a2eb4af07a334366577a --- .../godmode/setup/setup_notifications.php | 5 +++- .../include/functions_notifications.php | 23 ++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 40a4031dbb..c105b89e62 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -34,12 +34,15 @@ if (get_parameter('update_config', 0)) { $enable_value = switch_to_int(get_parameter("enable-$id")); $mail_value = (int)get_parameter("mail-{$id}", 0); $user_value = (int)get_parameter("user-{$id}", 0); + $postpone_value = (int)get_parameter("postpone-{$id}", 0); $res = mysql_db_process_sql_update( 'tnotification_source', array( 'enabled' => $enable_value, 'user_editable' => $user_value, - 'also_mail' => $mail_value), + 'also_mail' => $mail_value, + 'max_postpone_time' => $postpone_value + ), array('id' => $source['id']) ); return $res && $carry; diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index d7810417db..85bcf5caf3 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -27,6 +27,7 @@ * ============================================================================ */ +define('NOTIFICATIONS_POSTPONE_FOREVER', -1); /** * Retrieves source ID for given source. @@ -214,6 +215,26 @@ function notifications_print_global_source_configuration($source) { $html_checkboxes .= " "; $html_checkboxes .= ""; + // Generate the select with the time + $html_select_pospone = __('Users can postpone notifications up to'); + $html_select_pospone .= html_print_select ( + array( + SECONDS_5MINUTES => __('5 minutes'), + SECONDS_15MINUTES => __('15 minutes'), + SECONDS_12HOURS => __('12 hours'), + SECONDS_1DAY => __('1 day'), + SECONDS_1WEEK => __('1 week'), + SECONDS_15DAYS => __('15 days'), + SECONDS_1MONTH => __('1 month'), + NOTIFICATIONS_POSTPONE_FOREVER => __('forever')), + "postpone-{$id}", + $source['max_postpone_time'], + '', + '', + 0, + true + ); + // Return all html - return $html_title . $html_checkboxes; + return $html_title . $html_checkboxes . $html_select_pospone; } From c5805e439efdd0a84c515697bd21ddddbe3d039c Mon Sep 17 00:00:00 2001 From: samucarc Date: Fri, 1 Feb 2019 12:38:31 +0100 Subject: [PATCH 028/249] Fixed filter by name of agents in events when they contain spaces Former-commit-id: 93557e0ef296d1683acd86cb70ce2da6677e3e6c --- pandora_console/operation/events/events.build_query.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/operation/events/events.build_query.php b/pandora_console/operation/events/events.build_query.php index c06d2ac6c9..fc58b4ac15 100755 --- a/pandora_console/operation/events/events.build_query.php +++ b/pandora_console/operation/events/events.build_query.php @@ -167,7 +167,7 @@ if ($meta) { $id_agent = get_parameter('id_agent',0); if($id_agent){ $sql_post .= " AND agent_name IN (SELECT nombre FROM tmetaconsole_agent WHERE - id_tagente =".$id_agent." AND alias LIKE '".io_safe_input($text_agent)."')"; + id_tagente =".$id_agent." AND alias LIKE '".$text_agent."')"; $filter_resume['agent'] = $text_agent; } } From 315a51c5e76a6e7cd6332f9796d1c05685d503e7 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Fri, 1 Feb 2019 13:46:58 +0100 Subject: [PATCH 029/249] Added only read selector global notification setup Former-commit-id: bd6262cda30c0bb5a63b106e6c3832efbcfc63b9 --- .../include/functions_notifications.php | 53 ++++++++++++++++++- pandora_console/include/styles/pandora.css | 27 ++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 85bcf5caf3..9dfca6bf99 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -167,6 +167,31 @@ function notifications_get_all_sources() { return mysql_db_get_all_rows_in_table('tnotification_source'); } +function notifications_get_user_sources_for_select($source_id) { + $users = db_get_all_rows_filter( + 'tnotification_source_user', + array('id_source' => $source_id), + 'id_user' + ); + // If fails or no one is selected, return empty array + if ($users === false) return array(); + + return index_array($users, 'id_user', 'id_user'); +} + +function notifications_get_group_sources_for_select($source_id) { + $users = db_get_all_rows_filter( + 'tnotification_source_group tnsg + INNER JOIN tgrupo tg ON tnsg.id_group = tg.id_grupo', + array('id_source' => $source_id), + array ('tnsg.id_group', 'tg.nombre') + ); + // If fails or no one is selected, return empty array + if ($users === false) return array(); + + return index_array($users, 'id_group', 'nombre'); +} + /** * Print the notification ball to see unread messages * @@ -204,6 +229,12 @@ function notifications_print_global_source_configuration($source) { $html_title .= "

{$source['description']}

"; $html_title .= ""; + // Generate the html for title + $html_selectors = "
"; + $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users'); + $html_selectors .= notifications_print_source_select_box(notifications_get_group_sources_for_select($source['id']), 'groups'); + $html_selectors .= "
"; + // Generate the checkboxes and time select $html_checkboxes = "
"; $html_checkboxes .= " "; @@ -236,5 +267,25 @@ function notifications_print_global_source_configuration($source) { ); // Return all html - return $html_title . $html_checkboxes . $html_select_pospone; + return $html_title . $html_selectors . $html_checkboxes . $html_select_pospone; +} + +function notifications_print_source_select_box($info_selec, $id) { + + $title = $id == "users" ? __('Notified users') : __('Notified groups'); + $add_title = $id == "users" ? __('Add users') : __('Add groups'); + $delete_title = $id == "users" ? __('Delete users') : __('Delete groups'); + + // Generate the HTML + $html_select = "
"; + $html_select .= "
"; + $html_select .= "

$title

"; + $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}[]", 0, false, '', '', true, true); + $html_select .= "
"; + $html_select .= "
"; + $html_select .= html_print_image('images/input_add.png', true, array('title' => $add_title)); + $html_select .= html_print_image('images/input_delete.png', true, array('title' => $delete_title)); + $html_select .= "
"; + $html_select .= "
"; + return $html_select; } diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 924e147895..e1545c8d5d 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4939,6 +4939,33 @@ div#dialog_messages table th:last-child { margin-left: 10px; } +.global-config-notification-selectors { + display: flex; + flex-direction: row; + margin-bottom: 10px; +} + +.global-config-notification-selectors h4 { + margin: 0; +} + +.global-config-notification-single-selector { + display: flex; + width: 100%; + padding: 0 10px; +} + +.global-config-notification-single-selector :first-child, +.global-config-notification-single-selector :first-child select { + width: 99%; +} + +.global-config-notification-single-selector :last-child { + flex-direction: column; + display: flex; + justify-content: flex-end; +} + /* --- JQUERY-UI --- */ .ui-button-text-only .ui-button-text { font-family: "nunito", sans-serif; From a8b85d2593cb289b00a00a3e8f77a14532823cf6 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Fri, 1 Feb 2019 13:53:22 +0100 Subject: [PATCH 030/249] Added missing docs Former-commit-id: 807c7466b60e4c8ecb77fb8d94102300e9bcd780 --- .../include/functions_notifications.php | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 9dfca6bf99..d5cd4ac97f 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -167,6 +167,13 @@ function notifications_get_all_sources() { return mysql_db_get_all_rows_in_table('tnotification_source'); } +/** + * Return the user sources to be inserted into a select + * + * @param int $source_id Source database identificator + * + * @return array with the user id in keys and user id in value too + */ function notifications_get_user_sources_for_select($source_id) { $users = db_get_all_rows_filter( 'tnotification_source_user', @@ -179,6 +186,14 @@ function notifications_get_user_sources_for_select($source_id) { return index_array($users, 'id_user', 'id_user'); } + +/** + * Return the groups sources to be inserted into a select + * + * @param int $source_id Source database identificator + * + * @return array with the group id in keys and group name in value + */ function notifications_get_group_sources_for_select($source_id) { $users = db_get_all_rows_filter( 'tnotification_source_group tnsg @@ -270,6 +285,14 @@ function notifications_print_global_source_configuration($source) { return $html_title . $html_selectors . $html_checkboxes . $html_select_pospone; } +/** + * Print select boxes of notified users or groups + * + * @param array $info_selec All info required for build the selector + * @param string $id users|groups + * + * @return string HTML with the generated selector + */ function notifications_print_source_select_box($info_selec, $id) { $title = $id == "users" ? __('Notified users') : __('Notified groups'); @@ -280,6 +303,7 @@ function notifications_print_source_select_box($info_selec, $id) { $html_select = "
"; $html_select .= "
"; $html_select .= "

$title

"; + // Put a true if empty sources to avoid to sow the 'None' value $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}[]", 0, false, '', '', true, true); $html_select .= "
"; $html_select .= "
"; From 50030b69332bd93a29957e9d213bd5aabfe7e80d Mon Sep 17 00:00:00 2001 From: fermin831 Date: Fri, 1 Feb 2019 14:48:52 +0100 Subject: [PATCH 031/249] Added notify all users and disable on first load Former-commit-id: d193a8375ce00f3f2cf2c1fc181d4eef47c92eb2 --- .../include/functions_notifications.php | 28 +++++++++++++------ pandora_console/include/styles/pandora.css | 4 +++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index d5cd4ac97f..3d62dc0429 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -195,16 +195,16 @@ function notifications_get_user_sources_for_select($source_id) { * @return array with the group id in keys and group name in value */ function notifications_get_group_sources_for_select($source_id) { - $users = db_get_all_rows_filter( + $groups = db_get_all_rows_filter( 'tnotification_source_group tnsg - INNER JOIN tgrupo tg ON tnsg.id_group = tg.id_grupo', + LEFT JOIN tgrupo tg ON tnsg.id_group = tg.id_grupo', array('id_source' => $source_id), - array ('tnsg.id_group', 'tg.nombre') + array ('tnsg.id_group', 'IFNULL(tg.nombre, "All") AS name') ); // If fails or no one is selected, return empty array - if ($users === false) return array(); + if ($groups === false) return array(); - return index_array($users, 'id_group', 'nombre'); + return index_array($groups, 'id_group', 'name'); } /** @@ -238,6 +238,12 @@ function notifications_print_global_source_configuration($source) { 'name' => "enable-" . $id, 'value' => $source['enabled'] ); + + // Search if group all is set and handle that situation + $source_groups = notifications_get_group_sources_for_select($source['id']); + $is_group_all = isset($source_groups["0"]); + if($is_group_all) unset($source_groups["0"]); + // Generate the title $html_title = "
"; $html_title .= html_print_switch($switch_values); @@ -246,13 +252,16 @@ function notifications_print_global_source_configuration($source) { // Generate the html for title $html_selectors = "
"; - $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users'); - $html_selectors .= notifications_print_source_select_box(notifications_get_group_sources_for_select($source['id']), 'groups'); + $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $is_group_all); + $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $is_group_all); $html_selectors .= "
"; // Generate the checkboxes and time select $html_checkboxes = "
"; $html_checkboxes .= " "; + $html_checkboxes .= html_print_checkbox("all-$id", 1, $is_group_all, true, false, 'notifications_disable_source(event)'); + $html_checkboxes .= __('Notify all users'); + $html_checkboxes .= "
"; $html_checkboxes .= html_print_checkbox("mail-$id", 1, $source['also_mail'], true); $html_checkboxes .= __('Also email users with notification content'); $html_checkboxes .= "
"; @@ -290,10 +299,11 @@ function notifications_print_global_source_configuration($source) { * * @param array $info_selec All info required for build the selector * @param string $id users|groups + * @param bool $disabled Disable the selectors * * @return string HTML with the generated selector */ -function notifications_print_source_select_box($info_selec, $id) { +function notifications_print_source_select_box($info_selec, $id, $disabled) { $title = $id == "users" ? __('Notified users') : __('Notified groups'); $add_title = $id == "users" ? __('Add users') : __('Add groups'); @@ -304,7 +314,7 @@ function notifications_print_source_select_box($info_selec, $id) { $html_select .= "
"; $html_select .= "

$title

"; // Put a true if empty sources to avoid to sow the 'None' value - $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}[]", 0, false, '', '', true, true); + $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}[]", 0, false, '', '', true, true, true,'', $disabled); $html_select .= "
"; $html_select .= "
"; $html_select .= html_print_image('images/input_add.png', true, array('title' => $add_title)); diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index e1545c8d5d..aee1b9dc5d 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4939,6 +4939,10 @@ div#dialog_messages table th:last-child { margin-left: 10px; } +.global-config-notification-checkboxes :first-child { + font-weight: bold; +} + .global-config-notification-selectors { display: flex; flex-direction: row; From d2a3d3bbbcdb800df3463e07e79f63d1eaae865e Mon Sep 17 00:00:00 2001 From: fermin831 Date: Mon, 4 Feb 2019 10:41:35 +0100 Subject: [PATCH 032/249] Added all users in global notifications config Former-commit-id: d4bf0067f3ffe2e4fdef25158579716bdfd78d5d --- .../godmode/setup/setup_notifications.php | 8 +++- .../include/functions_notifications.php | 47 +++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index c105b89e62..d3c846aebf 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -35,7 +35,8 @@ if (get_parameter('update_config', 0)) { $mail_value = (int)get_parameter("mail-{$id}", 0); $user_value = (int)get_parameter("user-{$id}", 0); $postpone_value = (int)get_parameter("postpone-{$id}", 0); - $res = mysql_db_process_sql_update( + $all_users = (int)get_parameter("all-{$id}", 0); + $res = db_process_sql_update( 'tnotification_source', array( 'enabled' => $enable_value, @@ -45,7 +46,10 @@ if (get_parameter('update_config', 0)) { ), array('id' => $source['id']) ); - return $res && $carry; + $all_users_res = $all_users + ? notifications_add_group_to_source($source['id'], array(0)) + : notifications_remove_group_from_source($source['id'], array(0)); + return $all_users_res && $res && $carry; }, true); } diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 3d62dc0429..921b5c55e1 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -207,6 +207,53 @@ function notifications_get_group_sources_for_select($source_id) { return index_array($groups, 'id_group', 'name'); } +/** + * Delete a set of groups from notification source + * + * @param int Source id + * @param array Id of groups to be deleted + * + * @return bool True if success. False otherwise. + */ +function notifications_remove_group_from_source ($source_id, $groups) { + // Source id is mandatory + if (!isset($source_id)) return false; + + // Delete from database + return db_process_sql_delete ( + 'tnotification_source_group', + array( + 'id_group' => $groups, + 'id_source' => $source_id + ) + ) !== false; +} + +/** + * Insert a set of groups to notification source + * + * @param int Source id + * @param array Id of groups to be deleted + * + * @return bool True if success. False otherwise. + */ +function notifications_add_group_to_source ($source_id, $groups) { + // Source id is mandatory + if (!isset($source_id)) return false; + + // Insert into database all groups passed + $res = true; + foreach ($groups as $group) { + $res = db_process_sql_insert( + 'tnotification_source_group', + array( + 'id_group' => $group, + 'id_source' => $source_id) + ) !== false; + } + return $res; +} + /** * Print the notification ball to see unread messages * From 54f0bc1a038a5de061438f2b25b45011eef93cf6 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Mon, 4 Feb 2019 11:02:52 +0100 Subject: [PATCH 033/249] Disable selec boxes when click notify all users on notifications global config Former-commit-id: 93a3a0007a3a8dfabfec5d0b9ead7d185aeee81b --- .../godmode/setup/setup_notifications.php | 20 +++++++++++++++++++ .../include/functions_notifications.php | 9 +++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index d3c846aebf..06e6a85b63 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -75,3 +75,23 @@ html_print_input_hidden('update_config', 1); html_print_table($table_content); echo ''; +?> + diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 921b5c55e1..24013b92fd 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -299,8 +299,8 @@ function notifications_print_global_source_configuration($source) { // Generate the html for title $html_selectors = "
"; - $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $is_group_all); - $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $is_group_all); + $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $id, $is_group_all); + $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $id, $is_group_all); $html_selectors .= "
"; // Generate the checkboxes and time select @@ -346,11 +346,12 @@ function notifications_print_global_source_configuration($source) { * * @param array $info_selec All info required for build the selector * @param string $id users|groups + * @param string $source_id Id of source * @param bool $disabled Disable the selectors * * @return string HTML with the generated selector */ -function notifications_print_source_select_box($info_selec, $id, $disabled) { +function notifications_print_source_select_box($info_selec, $id, $source_id, $disabled) { $title = $id == "users" ? __('Notified users') : __('Notified groups'); $add_title = $id == "users" ? __('Add users') : __('Add groups'); @@ -361,7 +362,7 @@ function notifications_print_source_select_box($info_selec, $id, $disabled) { $html_select .= "
"; $html_select .= "

$title

"; // Put a true if empty sources to avoid to sow the 'None' value - $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}[]", 0, false, '', '', true, true, true,'', $disabled); + $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}-{$source_id}[]", 0, false, '', '', true, true, true,'', $disabled); $html_select .= "
"; $html_select .= "
"; $html_select .= html_print_image('images/input_add.png', true, array('title' => $add_title)); From 20e0508e01122f2461cceaabe83d96b0e9ab53b6 Mon Sep 17 00:00:00 2001 From: daniel Date: Mon, 4 Feb 2019 12:10:52 +0100 Subject: [PATCH 034/249] fixed pdf report Former-commit-id: 515b8f06f3584c6aaa1a32ea29a2f555e7afccad --- .../include/functions_reporting.php | 8 +- .../include/functions_reporting_html.php | 279 +++++++++++------- pandora_console/include/styles/pandora.css | 48 +-- pandora_console/include/styles/pandoraPDF.css | 71 +++++ pandora_console/index.php | 1 - 5 files changed, 269 insertions(+), 138 deletions(-) create mode 100644 pandora_console/include/styles/pandoraPDF.css diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index 03c5427d60..a4dbe7685d 100755 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -261,7 +261,7 @@ function reporting_make_reporting_data( } if (isset($content['style']['name_label'])) { - // Add macros name + // Add macros name. $items_label = []; $items_label['type'] = $content['type']; $items_label['id_agent'] = $content['id_agent']; @@ -272,11 +272,10 @@ function reporting_make_reporting_data( $metaconsole_on = is_metaconsole(); $server_name = $content['server_name']; - // Metaconsole connection + // Metaconsole connection. if ($metaconsole_on && $server_name != '') { $connection = metaconsole_get_connection($server_name); if (!metaconsole_load_external_db($connection)) { - // ui_print_error_message ("Error connecting to ".$server_name); continue; } } @@ -889,7 +888,6 @@ function reporting_SLA( if ($metaconsole_on && $server_name != '') { $connection = metaconsole_get_connection($server_name); if (!metaconsole_load_external_db($connection)) { - // ui_print_error_message ("Error connecting to ".$server_name); continue; } } @@ -898,7 +896,7 @@ function reporting_SLA( || modules_is_not_init($sla['id_agent_module']) ) { if ($metaconsole_on) { - // Restore db connection + // Restore db connection. metaconsole_restore_db(); } diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index 8bc7c973f3..84396cfb91 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -102,12 +102,12 @@ function html_do_report_info($report) $date_today = date($config['date_format']); - $html = '
'.' - - - - - '; + $html = '
'.__('Generated').': '.$date_today.'
'.__('Report date').':
+ + + + + '; if (isset($report['period'])) { if (is_numeric($report['datetime']) && is_numeric($report['period'])) { $html .= ''; @@ -119,10 +119,10 @@ function html_do_report_info($report) } $html .= ' - - - -
'.__('Generated').': '.$date_today.'
'.__('Report date').': '.date($config['date_format'], ($report['datetime'] - $report['period'])).'
'.__('Description').': '.io_safe_output($report['description']).'
'.'
'; + + '.__('Description').': '.io_safe_output($report['description']).' + + '.'
'; echo $html; } @@ -397,9 +397,20 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) } -function reporting_html_SLA($table, $item, $mini) +function reporting_html_SLA($table, $item, $mini, $pdf=0) { - $style = db_get_value('style', 'treport_content', 'id_rc', $item['id_rc']); + if ($table === false) { + $table = new stdClass(); + $table->width = '99%'; + $table->class = 'table_beauty'; + } + + $style = db_get_value( + 'style', + 'treport_content', + 'id_rc', + $item['id_rc'] + ); $style = json_decode(io_safe_output($style), true); $same_agent_in_resume = ''; @@ -423,7 +434,9 @@ function reporting_html_SLA($table, $item, $mini) $table->data['sla']['cell'] = $item['failed']; } else { if (!empty($item['planned_downtimes'])) { - $downtimes_table = reporting_html_planned_downtimes_table($item['planned_downtimes']); + $downtimes_table = reporting_html_planned_downtimes_table( + $item['planned_downtimes'] + ); if (!empty($downtimes_table)) { $table->colspan['planned_downtime']['cell'] = 3; @@ -459,7 +472,7 @@ function reporting_html_SLA($table, $item, $mini) $table1->headstyle[4] = 'text-align: right'; $table1->headstyle[5] = 'text-align: right'; - // second_table for time globals + // Second_table for time globals. $table2 = new stdClass(); $table2->width = '99%'; @@ -490,7 +503,7 @@ function reporting_html_SLA($table, $item, $mini) $table2->headstyle[5] = 'text-align: right'; $table2->headstyle[6] = 'text-align: right'; - // third_table for time globals + // Third_table for time globals. $table3 = new stdClass(); $table3->width = '99%'; @@ -520,15 +533,23 @@ function reporting_html_SLA($table, $item, $mini) foreach ($item['data'] as $sla) { if (isset($sla)) { - $the_first_men_time = get_agent_first_time(io_safe_output($sla['agent'])); + $the_first_men_time = get_agent_first_time( + io_safe_output($sla['agent']) + ); - // first_table + // First_table. $row = []; $row[] = $sla['agent']; $row[] = $sla['module']; if (is_numeric($sla['dinamic_text'])) { - $row[] = sla_truncate($sla['max'], $config['graph_precision']).' / '.sla_truncate($sla['min'], $config['graph_precision']); + $row[] = sla_truncate( + $sla['max'], + $config['graph_precision'] + ).' / '.sla_truncate( + $sla['min'], + $config['graph_precision'] + ); } else { $row[] = $sla['dinamic_text']; } @@ -550,47 +571,64 @@ function reporting_html_SLA($table, $item, $mini) $row[] = ''.__('Fail').''; } - // second table for time globals + // Second table for time globals. $row2 = []; $row2[] = $sla['agent'].' -- ['.$sla['module'].']'; if ($sla['time_total'] != 0) { - $row2[] = human_time_description_raw($sla['time_total']); + $row2[] = human_time_description_raw( + $sla['time_total'] + ); } else { $row2[] = '--'; } if ($sla['time_error'] != 0) { - $row2[] = ''.human_time_description_raw($sla['time_error'], true).''; + $row2[] = ''.human_time_description_raw( + $sla['time_error'], + true + ).''; } else { $row2[] = '--'; } if ($sla['time_ok'] != 0) { - $row2[] = ''.human_time_description_raw($sla['time_ok'], true).''; + $row2[] = ''.human_time_description_raw( + $sla['time_ok'], + true + ).''; } else { $row2[] = '--'; } if ($sla['time_unknown'] != 0) { - $row2[] = ''.human_time_description_raw($sla['time_unknown'], true).''; + $row2[] = ''.human_time_description_raw( + $sla['time_unknown'], + true + ).''; } else { $row2[] = '--'; } if ($sla['time_not_init'] != 0) { - $row2[] = ''.human_time_description_raw($sla['time_not_init'], true).''; + $row2[] = ''.human_time_description_raw( + $sla['time_not_init'], + true + ).''; } else { $row2[] = '--'; } if ($sla['time_downtime'] != 0) { - $row2[] = ''.human_time_description_raw($sla['time_downtime'], true).''; + $row2[] = ''.human_time_description_raw( + $sla['time_downtime'], + true + ).''; } else { $row2[] = '--'; } - // third table for checks globals + // Third table for checks globals. $row3 = []; $row3[] = $sla['agent'].' -- ['.$sla['module'].']'; $row3[] = $sla['checks_total']; @@ -605,11 +643,20 @@ function reporting_html_SLA($table, $item, $mini) } $table->colspan['sla']['cell'] = 2; - $table->data['sla']['cell'] = html_print_table($table1, true); + $table->data['sla']['cell'] = html_print_table( + $table1, + true + ); $table->colspan['time_global']['cell'] = 2; - $table->data['time_global']['cell'] = html_print_table($table2, true); + $table->data['time_global']['cell'] = html_print_table( + $table2, + true + ); $table->colspan['checks_global']['cell'] = 2; - $table->data['checks_global']['cell'] = html_print_table($table3, true); + $table->data['checks_global']['cell'] = html_print_table( + $table3, + true + ); } else { $table->colspan['error']['cell'] = 3; $table->data['error']['cell'] = __('There are no Agent/Modules defined'); @@ -631,9 +678,12 @@ function reporting_html_SLA($table, $item, $mini) } $table->colspan['charts']['cell'] = 2; - $table->data['charts']['cell'] = html_print_table($table1, true); + $table->data['charts']['cell'] = html_print_table( + $table1, + true + ); - // table_legend_graphs; + // Table_legend_graphs. $table1 = new stdClass(); $table1->width = '99%'; $table1->data = []; @@ -669,9 +719,16 @@ function reporting_html_SLA($table, $item, $mini) $table1->data[0][11] = ''.__('Ignore time').''; $table->colspan['legend']['cell'] = 2; - $table->data['legend']['cell'] = html_print_table($table1, true); + $table->data['legend']['cell'] = html_print_table( + $table1, + true + ); } } + + if ($pdf !== 0) { + return html_print_table($table, true); + } } @@ -794,7 +851,7 @@ function reporting_html_event_report_group($table, $item, $pdf=0) } foreach ($item['data'] as $k => $event) { - // First pass along the class of this row + // First pass along the class of this row. if ($item['show_summary_group']) { $table1->cellclass[$k][1] = $table1->cellclass[$k][2] = $table1->cellclass[$k][4] = $table1->cellclass[$k][5] = $table1->cellclass[$k][6] = $table1->cellclass[$k][7] = get_priority_class($event['criticity']); } else { @@ -1559,53 +1616,53 @@ function reporting_html_group_report($table, $item) $table->colspan['group_report']['cell'] = 3; $table->cellstyle['group_report']['cell'] = 'text-align: center;'; $table->data['group_report']['cell'] = " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
".__('Total')."
".__('Unknown')."
".__('Agents')."
".$item['data']['group_stats']['total_agents']."
".$item['data']['group_stats']['agents_unknown']."
".__('Total')."
".__('Normal')."
".__('Critical')."
".__('Warning')."
".__('Unknown')."
".__('Not init')."
".__('Monitors')."
".$item['data']['group_stats']['monitor_checks']."
".$item['data']['group_stats']['monitor_ok']."
".$item['data']['group_stats']['monitor_critical']."
".$item['data']['group_stats']['monitor_warning']."
".$item['data']['group_stats']['monitor_unknown']."
".$item['data']['group_stats']['monitor_not_init']."
".__('Defined')."
".__('Fired')."
".__('Alerts')."
".$item['data']['group_stats']['monitor_alerts']."
".$item['data']['group_stats']['monitor_alerts_fired']."
".__('Last %s', human_time_description_raw($item['date']['period']))."
".__('Events')."
".$item['data']['count_events'].'
'; + + +
".__('Total')."
+
".__('Unknown')."
+ + +
".__('Agents')."
+
".$item['data']['group_stats']['total_agents']."
+
".$item['data']['group_stats']['agents_unknown']."
+ + + +
".__('Total')."
+
".__('Normal')."
+
".__('Critical')."
+
".__('Warning')."
+
".__('Unknown')."
+
".__('Not init')."
+ + +
".__('Monitors')."
+
".$item['data']['group_stats']['monitor_checks']."
+
".$item['data']['group_stats']['monitor_ok']."
+
".$item['data']['group_stats']['monitor_critical']."
+
".$item['data']['group_stats']['monitor_warning']."
+
".$item['data']['group_stats']['monitor_unknown']."
+
".$item['data']['group_stats']['monitor_not_init']."
+ + + +
".__('Defined')."
+
".__('Fired')."
+ + +
".__('Alerts')."
+
".$item['data']['group_stats']['monitor_alerts']."
+
".$item['data']['group_stats']['monitor_alerts_fired']."
+ + + +
".__('Last %s', human_time_description_raw($item['date']['period']))."
+ + +
".__('Events')."
+
".$item['data']['count_events'].'
+ + '; } @@ -2302,15 +2359,15 @@ function reporting_html_url(&$table, $item, $key) $table->colspan['data']['cell'] = 3; $table->cellstyle['data']['cell'] = 'text-align: left;'; $table->data['data']['cell'] = ' - '; + '; // TODO: make this dynamic and get the height if the iframe to resize this item $table->data['data']['cell'] .= ' - '; + '; } @@ -2635,8 +2692,8 @@ function get_agent_first_time($agent_name) $utimestamp = db_get_all_rows_sql( 'SELECT utimestamp FROM tagente_datos WHERE id_agente_modulo IN - (SELECT id_agente_modulo FROM tagente_modulo WHERE id_agente = '.$id.') - ORDER BY utimestamp ASC LIMIT 1' + (SELECT id_agente_modulo FROM tagente_modulo WHERE id_agente = '.$id.') + ORDER BY utimestamp ASC LIMIT 1' ); $utimestamp = $utimestamp[0]['utimestamp']; @@ -2878,7 +2935,7 @@ function reporting_get_stats_summary($data, $graph_width, $graph_height) $table_sum->data[] = $tdata; $output = '
- '.__('Summary').''.html_print_table($table_sum, true).'
'; + '.__('Summary').''.html_print_table($table_sum, true).''; return $output; } @@ -3459,12 +3516,12 @@ function reporting_get_agents_by_status($data, $graph_width=250, $graph_height=1 if (!defined('METACONSOLE')) { $agents_data = '
- '.__('Agents by status').''.html_print_table($table_agent, true).'
'; + '.__('Agents by status').''.html_print_table($table_agent, true).''; } else { $table_agent->style = []; $table_agent->class = 'tactical_view'; $agents_data = '
- '.__('Agents by status').''.html_print_table($table_agent, true).'
'; + '.__('Agents by status').''.html_print_table($table_agent, true).''; } return $agents_data; @@ -3487,7 +3544,7 @@ function reporting_get_total_agents_and_monitors($data, $graph_width=250, $graph $total_data[3] = $total_module <= 0 ? '-' : $total_module; $table_total->data[] = $total_data; $total_agent_module = '
- '.__('Total agents and monitors').''.html_print_table($table_total, true).'
'; + '.__('Total agents and monitors').''.html_print_table($table_total, true).''; return $total_agent_module; } @@ -3506,12 +3563,12 @@ function reporting_get_total_servers($num_servers) if (!defined('METACONSOLE')) { $node_overview = '
- '.__('Node overview').''.html_print_table($table_node, true).'
'; + '.__('Node overview').''.html_print_table($table_node, true).''; } else { $table_node->style = []; $table_node->class = 'tactical_view'; $node_overview = '
- '.__('Node overview').''.html_print_table($table_node, true).'
'; + '.__('Node overview').''.html_print_table($table_node, true).''; } return $node_overview; @@ -3555,7 +3612,7 @@ function reporting_get_events($data, $links=false) if (!defined('METACONSOLE')) { $event_view = '
- '.__('Events by severity').''.html_print_table($table_events, true).'
'; + '.__('Events by severity').''.html_print_table($table_events, true).''; } else { $table_events->class = 'tactical_view'; $table_events->styleTable = 'text-align:center;'; @@ -3565,7 +3622,7 @@ function reporting_get_events($data, $links=false) $table_events->size[3] = '10%'; $event_view = '
- '.__('Important Events by Criticity').''.html_print_table($table_events, true).'
'; + '.__('Important Events by Criticity').''.html_print_table($table_events, true).''; } return $event_view; @@ -3597,9 +3654,9 @@ function reporting_get_last_activity() case 'mysql': $sql = sprintf( 'SELECT id_usuario,accion,fecha,ip_origen,descripcion,utimestamp - FROM tsesion - WHERE (`utimestamp` > UNIX_TIMESTAMP(NOW()) - '.SECONDS_1WEEK.") - AND `id_usuario` = '%s' ORDER BY `utimestamp` DESC LIMIT 5", + FROM tsesion + WHERE (`utimestamp` > UNIX_TIMESTAMP(NOW()) - '.SECONDS_1WEEK.") + AND `id_usuario` = '%s' ORDER BY `utimestamp` DESC LIMIT 5", $config['id_user'] ); break; @@ -3607,9 +3664,9 @@ function reporting_get_last_activity() case 'postgresql': $sql = sprintf( "SELECT \"id_usuario\", accion, fecha, \"ip_origen\", descripcion, utimestamp - FROM tsesion - WHERE (\"utimestamp\" > ceil(date_part('epoch', CURRENT_TIMESTAMP)) - ".SECONDS_1WEEK.") - AND \"id_usuario\" = '%s' ORDER BY \"utimestamp\" DESC LIMIT 5", + FROM tsesion + WHERE (\"utimestamp\" > ceil(date_part('epoch', CURRENT_TIMESTAMP)) - ".SECONDS_1WEEK.") + AND \"id_usuario\" = '%s' ORDER BY \"utimestamp\" DESC LIMIT 5", $config['id_user'] ); break; @@ -3617,9 +3674,9 @@ function reporting_get_last_activity() case 'oracle': $sql = sprintf( "SELECT id_usuario, accion, fecha, ip_origen, descripcion, utimestamp - FROM tsesion - WHERE ((utimestamp > ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - '.SECONDS_1WEEK.") - AND id_usuario = '%s') AND rownum <= 10 ORDER BY utimestamp DESC", + FROM tsesion + WHERE ((utimestamp > ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - '.SECONDS_1WEEK.") + AND id_usuario = '%s') AND rownum <= 10 ORDER BY utimestamp DESC", $config['id_user'] ); break; @@ -3797,7 +3854,7 @@ function reporting_get_event_histogram($events, $text_header_event=false) if (!defined('METACONSOLE')) { if (!$text_header_event) { $event_graph = '
- '.$text_header_event.''.html_print_table($table, true).'
'; + '.$text_header_event.''.html_print_table($table, true).''; } else { $table->class = 'noclass'; $event_graph = html_print_table($table, true); @@ -3895,9 +3952,9 @@ function reporting_get_event_histogram_meta($width) $time_condition = 'utimestamp > '.$bottom.' AND utimestamp < '.$top; $sql = sprintf( 'SELECT criticity,utimestamp - FROM tmetaconsole_event - WHERE %s %s %s - ORDER BY criticity DESC', + FROM tmetaconsole_event + WHERE %s %s %s + ORDER BY criticity DESC', $time_condition, $groups_condition, $status_condition @@ -3981,7 +4038,7 @@ function reporting_get_event_histogram_meta($width) if (!$text_header_event) { $event_graph = '
- '.$text_header_event.''.html_print_table($table, true).'
'; + '.$text_header_event.''.html_print_table($table, true).''; } else { $table->class = 'noclass'; $event_graph = html_print_table($table, true); diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index f42c64f70a..cd5a3d8eaf 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -1,24 +1,30 @@ -/* -Author: The Pandora FMS team -Name: Default theme -Description: The default Pandora FMS theme layout - -// Pandora FMS - http://pandorafms.com -// ========================================================== -// Copyright (c) 2004-2011 Artica Soluciones Tecnológicas S.L - -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; version 2 - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -*/ +/** + * Extension to manage a list of gateways and the node address where they should + * point to. + * + * @category Extensions + * @package Pandora FMS + * @subpackage Community + * @version 1.0.0 + * @license See below + * + * ______ ___ _______ _______ ________ + * | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __| + * | __/| _ | | _ || _ | _| _ | | ___| |__ | + * |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______| + * + * ============================================================================ + * Copyright (c) 2005-2019 Artica Soluciones Tecnologicas + * Please see http://pandorafms.org for full contribution list + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation for version 2. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * ============================================================================ + */ /* Tree view styles */ @import url(tree.css); diff --git a/pandora_console/include/styles/pandoraPDF.css b/pandora_console/include/styles/pandoraPDF.css new file mode 100644 index 0000000000..10dc892ec6 --- /dev/null +++ b/pandora_console/include/styles/pandoraPDF.css @@ -0,0 +1,71 @@ +/** + * Extension to manage a list of gateways and the node address where they should + * point to. + * + * @category Extensions + * @package Pandora FMS + * @subpackage Community + * @version 1.0.0 + * @license See below + * + * ______ ___ _______ _______ ________ + * | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __| + * | __/| _ | | _ || _ | _| _ | | ___| |__ | + * |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______| + * + * ============================================================================ + * Copyright (c) 2005-2019 Artica Soluciones Tecnologicas + * Please see http://pandorafms.org for full contribution list + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation for version 2. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * ============================================================================ + */ + +.content_table { + width: 100%; + font-size: 20pt !important; + page-break-inside: avoid; + border-collapse: collapse; +} + +.content_table tr th, +.content_table tr td { + padding: 10px; +} + +thead.header_tr tr { + background: #e6e6e6; +} +thead.header_tr tr th { + font-weight: normal; + text-align: right; +} +thead.header_tr tr th.th_first { + font-weight: bold; + text-align: left; +} + +.table_beauty { + font-size: 20pt !important; + border-collapse: collapse; + width: 100%; +} + +.table_beauty tr td { + font-size: 20pt !important; + padding: 5px; + border: 0.1pt solid #acacac; +} + +.table_beauty tr td table { + font-size: 20pt !important; +} + +.table_beauty tr td table tr td { + font-size: 20pt !important; +} diff --git a/pandora_console/index.php b/pandora_console/index.php index ad4b93465a..321b5956dc 100755 --- a/pandora_console/index.php +++ b/pandora_console/index.php @@ -1363,4 +1363,3 @@ require 'include/php_to_js_values.php'; if (__PAN_XHPROF__ === 1) { pandora_xhprof_display_result('node_index'); } - From 53947de42a13f96717e33606c2eae87014b990b6 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 4 Feb 2019 19:14:02 +0100 Subject: [PATCH 035/249] minor changes - constants style Former-commit-id: 3482cb88dc0884ea3c1742eb8fef4ac7c603a849 --- pandora_console/include/constants.php | 955 +++++++++++++------------- 1 file changed, 485 insertions(+), 470 deletions(-) diff --git a/pandora_console/include/constants.php b/pandora_console/include/constants.php index 22f46257dc..cd1b907c0a 100644 --- a/pandora_console/include/constants.php +++ b/pandora_console/include/constants.php @@ -1,552 +1,567 @@ +define('MAP_SOURCE_GROUP', 0); +define('MAP_SOURCE_IP_MASK', 1); + +define('NETWORKMAP_DEFAULT_WIDTH', 800); +define('NETWORKMAP_DEFAULT_HEIGHT', 800); + +// Background options. +define('CENTER', 0); +define('MOSAIC', 1); +define('STRECH', 2); +define('FIT_WIDTH', 3); +define('FIT_HEIGH', 4); + +// Items of maps. +define('ITEM_TYPE_AGENT_NETWORKMAP', 0); +define('ITEM_TYPE_MODULE_NETWORKMAP', 1); +define('ITEM_TYPE_EDGE_NETWORKMAP', 2); +define('ITEM_TYPE_FICTIONAL_NODE', 3); +define('ITEM_TYPE_MODULEGROUP_NETWORKMAP', 4); +define('ITEM_TYPE_GROUP_NETWORKMAP', 5); +define('ITEM_TYPE_POLICY_NETWORKMAP', 6); + +// Another constants new networkmap. +define('DEFAULT_NODE_WIDTH', 30); +define('DEFAULT_NODE_HEIGHT', 30); +define('DEFAULT_NODE_SHAPE', 'circle'); +define('DEFAULT_NODE_COLOR', COL_NOTINIT); +define('DEFAULT_NODE_IMAGE', 'images/networkmap/unknown.png'); + +define('NODE_IMAGE_PADDING', 5); From c15357dc03d235e0e0225b7527784831529b1ef7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 4 Feb 2019 19:16:30 +0100 Subject: [PATCH 036/249] Servers get server string name Former-commit-id: 6988fc5972c72c23131704e9dcb45328755b0ee8 --- pandora_console/include/functions_servers.php | 1425 +++++++++-------- 1 file changed, 788 insertions(+), 637 deletions(-) diff --git a/pandora_console/include/functions_servers.php b/pandora_console/include/functions_servers.php index 6bd255e88d..856864b4a3 100644 --- a/pandora_console/include/functions_servers.php +++ b/pandora_console/include/functions_servers.php @@ -1,24 +1,32 @@ 0, 'status' => 1); - db_process_sql_update('trecon_task', $values, array('id_rt' => $id_recon_task)); +function servers_force_recon_task($id_recon_task) +{ + $values = [ + 'utimestamp' => 0, + 'status' => 1, + ]; + db_process_sql_update('trecon_task', $values, ['id_rt' => $id_recon_task]); } + /** * This function will get several metrics from the database to get info about server performance - * @return array with several data + * + * @return array with several data */ -function servers_get_performance () { - - global $config; - - $data = array(); - $data["total_modules"] = 0; - $data["total_remote_modules"] = 0; - $data["total_local_modules"] = 0; - $data["avg_interval_total_modules"] = array(); - $data["avg_interval_remote_modules"] = array(); - $data["avg_interval_local_modules"] = 0; - $data["local_modules_rate"] = 0; - $data["network_modules_rate"] = 0; - - if ($config["realtimestats"] == 1) { - - $counts = db_get_all_rows_sql (" +function servers_get_performance() +{ + global $config; + + $data = []; + $data['total_modules'] = 0; + $data['total_remote_modules'] = 0; + $data['total_local_modules'] = 0; + $data['avg_interval_total_modules'] = []; + $data['avg_interval_remote_modules'] = []; + $data['avg_interval_local_modules'] = 0; + $data['local_modules_rate'] = 0; + $data['network_modules_rate'] = 0; + + if ($config['realtimestats'] == 1) { + $counts = db_get_all_rows_sql( + ' SELECT tagente_modulo.id_modulo, COUNT(tagente_modulo.id_agente_modulo) modules FROM tagente_modulo, tagente_estado, tagente @@ -95,94 +119,108 @@ function servers_get_performance () { AND (utimestamp > 0 OR (id_tipo_modulo = 100 OR (id_tipo_modulo > 21 AND id_tipo_modulo < 23))) AND tagente.disabled = 0 - GROUP BY tagente_modulo.id_modulo"); - - if (empty($counts)) { - $counts = array(); - } - - foreach($counts as $c) { - switch($c['id_modulo']) { - case MODULE_DATA: - $data["total_local_modules"] = $c['modules']; - break; - case MODULE_NETWORK: - $data["total_network_modules"] = $c['modules']; - break; - case MODULE_PLUGIN: - $data["total_plugin_modules"] = $c['modules']; - break; - case MODULE_PREDICTION: - $data["total_prediction_modules"] = $c['modules']; - break; - case MODULE_WMI: - $data["total_wmi_modules"] = $c['modules']; - break; - case MODULE_WEB: - $data["total_web_modules"] = $c['modules']; - break; - } - - if($c['id_modulo'] != MODULE_DATA) { - $data["total_remote_modules"] += $c['modules']; - } - - $data["total_modules"] += $c['modules']; - } - } - else { - $counts = db_get_all_rows_sql (" + GROUP BY tagente_modulo.id_modulo' + ); + + if (empty($counts)) { + $counts = []; + } + + foreach ($counts as $c) { + switch ($c['id_modulo']) { + case MODULE_DATA: + $data['total_local_modules'] = $c['modules']; + break; + + case MODULE_NETWORK: + $data['total_network_modules'] = $c['modules']; + break; + + case MODULE_PLUGIN: + $data['total_plugin_modules'] = $c['modules']; + break; + + case MODULE_PREDICTION: + $data['total_prediction_modules'] = $c['modules']; + break; + + case MODULE_WMI: + $data['total_wmi_modules'] = $c['modules']; + break; + + case MODULE_WEB: + $data['total_web_modules'] = $c['modules']; + break; + } + + if ($c['id_modulo'] != MODULE_DATA) { + $data['total_remote_modules'] += $c['modules']; + } + + $data['total_modules'] += $c['modules']; + } + } else { + $counts = db_get_all_rows_sql( + ' SELECT server_type, my_modules modules FROM tserver - GROUP BY server_type"); - - if (empty($counts)) { - $counts = array(); - } - - foreach ($counts as $c) { - switch ($c['server_type']) { - case SERVER_TYPE_DATA: - $data["total_local_modules"] = $c['modules']; - break; - case SERVER_TYPE_NETWORK: - case SERVER_TYPE_SNMP: - case SERVER_TYPE_ENTERPRISE_ICMP: - case SERVER_TYPE_ENTERPRISE_SNMP: - $data["total_network_modules"] = $c['modules']; - break; - case SERVER_TYPE_PLUGIN: - $data["total_plugin_modules"] = $c['modules']; - break; - case SERVER_TYPE_PREDICTION: - $data["total_prediction_modules"] = $c['modules']; - break; - case SERVER_TYPE_WMI: - $data["total_wmi_modules"] = $c['modules']; - break; - case SERVER_TYPE_WEB: - $data["total_web_modules"] = $c['modules']; - break; - case SERVER_TYPE_EXPORT: - case SERVER_TYPE_INVENTORY: - case SERVER_TYPE_EVENT: - case SERVER_TYPE_RECON: - case SERVER_TYPE_SYSLOG: - break; - } - - if ($c['server_type'] != SERVER_TYPE_DATA) { - $data["total_remote_modules"] += $c['modules']; - } - - $data["total_modules"] += $c['modules']; - } - } - - $interval_avgs = array(); - - // Avg of modules interval when modules have module_interval > 0 - $interval_avgs_modules = db_get_all_rows_sql (" + GROUP BY server_type' + ); + + if (empty($counts)) { + $counts = []; + } + + foreach ($counts as $c) { + switch ($c['server_type']) { + case SERVER_TYPE_DATA: + $data['total_local_modules'] = $c['modules']; + break; + + case SERVER_TYPE_NETWORK: + case SERVER_TYPE_SNMP: + case SERVER_TYPE_ENTERPRISE_ICMP: + case SERVER_TYPE_ENTERPRISE_SNMP: + $data['total_network_modules'] = $c['modules']; + break; + + case SERVER_TYPE_PLUGIN: + $data['total_plugin_modules'] = $c['modules']; + break; + + case SERVER_TYPE_PREDICTION: + $data['total_prediction_modules'] = $c['modules']; + break; + + case SERVER_TYPE_WMI: + $data['total_wmi_modules'] = $c['modules']; + break; + + case SERVER_TYPE_WEB: + $data['total_web_modules'] = $c['modules']; + break; + + case SERVER_TYPE_EXPORT: + case SERVER_TYPE_INVENTORY: + case SERVER_TYPE_EVENT: + case SERVER_TYPE_RECON: + case SERVER_TYPE_SYSLOG: + break; + } + + if ($c['server_type'] != SERVER_TYPE_DATA) { + $data['total_remote_modules'] += $c['modules']; + } + + $data['total_modules'] += $c['modules']; + } + } + + $interval_avgs = []; + + // Avg of modules interval when modules have module_interval > 0 + $interval_avgs_modules = db_get_all_rows_sql( + ' SELECT count(tagente_modulo.id_modulo) modules , tagente_modulo.id_modulo, AVG(tagente_modulo.module_interval) avg_interval @@ -194,20 +232,22 @@ function servers_get_performance () { AND delete_pending = 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente - GROUP BY tagente_modulo.id_modulo"); - - if (empty($interval_avgs_modules)) { - $interval_avgs_modules = array(); - } - - // Transform into a easily format - foreach ($interval_avgs_modules as $iamodules) { - $interval_avgs[$iamodules['id_modulo']]['avg_interval'] = $iamodules['avg_interval']; - $interval_avgs[$iamodules['id_modulo']]['modules'] = $iamodules['modules']; - } - - // Avg of agents interval when modules have module_interval == 0 - $interval_avgs_agents = db_get_all_rows_sql (" + GROUP BY tagente_modulo.id_modulo' + ); + + if (empty($interval_avgs_modules)) { + $interval_avgs_modules = []; + } + + // Transform into a easily format + foreach ($interval_avgs_modules as $iamodules) { + $interval_avgs[$iamodules['id_modulo']]['avg_interval'] = $iamodules['avg_interval']; + $interval_avgs[$iamodules['id_modulo']]['modules'] = $iamodules['modules']; + } + + // Avg of agents interval when modules have module_interval == 0 + $interval_avgs_agents = db_get_all_rows_sql( + ' SELECT count(tagente_modulo.id_modulo) modules , tagente_modulo.id_modulo, AVG(tagente.intervalo) avg_interval FROM tagente_modulo, tagente_estado, tagente @@ -218,82 +258,86 @@ function servers_get_performance () { AND delete_pending = 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente - GROUP BY tagente_modulo.id_modulo"); - - if (empty($interval_avgs_agents)) { - $interval_avgs_agents = array(); - } - - // Merge with the previous calculated array - foreach ($interval_avgs_agents as $iaagents) { - if (!isset($interval_avgs[$iaagents['id_modulo']]['modules'])) { - $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = $iaagents['avg_interval']; - $interval_avgs[$iaagents['id_modulo']]['modules'] = $iaagents['modules']; - } - else { - $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = servers_get_avg_interval($interval_avgs[$iaagents['id_modulo']], $iaagents); - $interval_avgs[$iaagents['id_modulo']]['modules'] += $iaagents['modules']; - } - } - - foreach ($interval_avgs as $id_modulo => $ia) { - switch($id_modulo) { - case MODULE_DATA: - $data["avg_interval_local_modules"] = $ia['avg_interval']; - $data["local_modules_rate"] = - servers_get_rate($data["avg_interval_local_modules"], $data["total_local_modules"]); - break; - case MODULE_NETWORK: - $data["avg_interval_network_modules"] = $ia['avg_interval']; - $data["network_modules_rate"] = - servers_get_rate($data["avg_interval_network_modules"], - $data["total_network_modules"]); - break; - case MODULE_PLUGIN: - $data["avg_interval_plugin_modules"] = $ia['avg_interval']; - $data["plugin_modules_rate"] = servers_get_rate($data["avg_interval_plugin_modules"], $data["total_plugin_modules"]); - break; - case MODULE_PREDICTION: - $data["avg_interval_prediction_modules"] = $ia['avg_interval']; - $data["prediction_modules_rate"] = servers_get_rate($data["avg_interval_prediction_modules"], $data["total_prediction_modules"]); - break; - case MODULE_WMI: - $data["avg_interval_wmi_modules"] = $ia['avg_interval']; - $data["wmi_modules_rate"] = servers_get_rate($data["avg_interval_wmi_modules"], $data["total_wmi_modules"]); - break; - case MODULE_WEB: - $data["avg_interval_web_modules"] = $ia['avg_interval']; - $data["web_modules_rate"] = servers_get_rate($data["avg_interval_web_modules"], $data["total_web_modules"]); - break; - } - - if ($id_modulo != MODULE_DATA) { - $data["avg_interval_remote_modules"][] = $ia['avg_interval']; - } - - $data["avg_interval_total_modules"][] = $ia['avg_interval']; - } - - if (empty($data["avg_interval_remote_modules"])) { - $data["avg_interval_remote_modules"] = 0; - } - else { - $data["avg_interval_remote_modules"] = array_sum($data["avg_interval_remote_modules"]) / count($data["avg_interval_remote_modules"]); - } - - if (empty($data["avg_interval_total_modules"])) { - $data["avg_interval_total_modules"] = 0; - } - else { - $data["avg_interval_total_modules"] = array_sum($data["avg_interval_total_modules"]) / count($data["avg_interval_total_modules"]); - } - - $data["remote_modules_rate"] = servers_get_rate($data["avg_interval_remote_modules"], $data["total_remote_modules"]); - $data["total_modules_rate"] = servers_get_rate($data["avg_interval_total_modules"], $data["total_modules"]); - - return ($data); + GROUP BY tagente_modulo.id_modulo' + ); + + if (empty($interval_avgs_agents)) { + $interval_avgs_agents = []; + } + + // Merge with the previous calculated array + foreach ($interval_avgs_agents as $iaagents) { + if (!isset($interval_avgs[$iaagents['id_modulo']]['modules'])) { + $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = $iaagents['avg_interval']; + $interval_avgs[$iaagents['id_modulo']]['modules'] = $iaagents['modules']; + } else { + $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = servers_get_avg_interval($interval_avgs[$iaagents['id_modulo']], $iaagents); + $interval_avgs[$iaagents['id_modulo']]['modules'] += $iaagents['modules']; + } + } + + foreach ($interval_avgs as $id_modulo => $ia) { + switch ($id_modulo) { + case MODULE_DATA: + $data['avg_interval_local_modules'] = $ia['avg_interval']; + $data['local_modules_rate'] = servers_get_rate($data['avg_interval_local_modules'], $data['total_local_modules']); + break; + + case MODULE_NETWORK: + $data['avg_interval_network_modules'] = $ia['avg_interval']; + $data['network_modules_rate'] = servers_get_rate( + $data['avg_interval_network_modules'], + $data['total_network_modules'] + ); + break; + + case MODULE_PLUGIN: + $data['avg_interval_plugin_modules'] = $ia['avg_interval']; + $data['plugin_modules_rate'] = servers_get_rate($data['avg_interval_plugin_modules'], $data['total_plugin_modules']); + break; + + case MODULE_PREDICTION: + $data['avg_interval_prediction_modules'] = $ia['avg_interval']; + $data['prediction_modules_rate'] = servers_get_rate($data['avg_interval_prediction_modules'], $data['total_prediction_modules']); + break; + + case MODULE_WMI: + $data['avg_interval_wmi_modules'] = $ia['avg_interval']; + $data['wmi_modules_rate'] = servers_get_rate($data['avg_interval_wmi_modules'], $data['total_wmi_modules']); + break; + + case MODULE_WEB: + $data['avg_interval_web_modules'] = $ia['avg_interval']; + $data['web_modules_rate'] = servers_get_rate($data['avg_interval_web_modules'], $data['total_web_modules']); + break; + } + + if ($id_modulo != MODULE_DATA) { + $data['avg_interval_remote_modules'][] = $ia['avg_interval']; + } + + $data['avg_interval_total_modules'][] = $ia['avg_interval']; + } + + if (empty($data['avg_interval_remote_modules'])) { + $data['avg_interval_remote_modules'] = 0; + } else { + $data['avg_interval_remote_modules'] = (array_sum($data['avg_interval_remote_modules']) / count($data['avg_interval_remote_modules'])); + } + + if (empty($data['avg_interval_total_modules'])) { + $data['avg_interval_total_modules'] = 0; + } else { + $data['avg_interval_total_modules'] = (array_sum($data['avg_interval_total_modules']) / count($data['avg_interval_total_modules'])); + } + + $data['remote_modules_rate'] = servers_get_rate($data['avg_interval_remote_modules'], $data['total_remote_modules']); + $data['total_modules_rate'] = servers_get_rate($data['avg_interval_total_modules'], $data['total_modules']); + + return ($data); } + /** * Get avg interval * @@ -302,15 +346,19 @@ function servers_get_performance () { * * @return float number of avg modules between two parts */ - -function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2) { - $total_modules = $modules_avg_interval1['modules'] + $modules_avg_interval2['modules']; - - $parcial1 = $modules_avg_interval1['avg_interval'] * $modules_avg_interval1['modules']; - $parcial2 = $modules_avg_interval2['avg_interval'] * $modules_avg_interval2['modules']; - - return ($parcial1 + $parcial2) / $total_modules; + + +function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2) +{ + $total_modules = ($modules_avg_interval1['modules'] + $modules_avg_interval2['modules']); + + $parcial1 = ($modules_avg_interval1['avg_interval'] * $modules_avg_interval1['modules']); + $parcial2 = ($modules_avg_interval2['avg_interval'] * $modules_avg_interval2['modules']); + + return (($parcial1 + $parcial2) / $total_modules); } + + /** * Get server rate * @@ -319,13 +367,12 @@ function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2 * * @return float number of modules processed by second */ -function servers_get_rate($avg_interval, $num_modules) { - - return $avg_interval > 0 ? - ($num_modules / $avg_interval) : - 0; +function servers_get_rate($avg_interval, $num_modules) +{ + return $avg_interval > 0 ? ($num_modules / $avg_interval) : 0; } + /** * This function will get all the server information in an array or a specific server * @@ -333,300 +380,321 @@ function servers_get_rate($avg_interval, $num_modules) { * * @return mixed False in case the server doesn't exist or an array with info. */ -function servers_get_info ($id_server = -1) { - global $config; - - if (is_array ($id_server)) { - $select_id = " WHERE id_server IN (".implode (",", $id_server).")"; - } - elseif ($id_server > 0) { - $select_id = " WHERE id_server IN (".(int) $id_server.")"; - } - else { - $select_id = ""; - } - - $sql = " +function servers_get_info($id_server=-1) +{ + global $config; + + if (is_array($id_server)) { + $select_id = ' WHERE id_server IN ('.implode(',', $id_server).')'; + } else if ($id_server > 0) { + $select_id = ' WHERE id_server IN ('.(int) $id_server.')'; + } else { + $select_id = ''; + } + + $sql = ' SELECT * - FROM tserver " . $select_id . " - ORDER BY server_type"; - $result = db_get_all_rows_sql ($sql); - $time = get_system_time (); - - if (empty ($result)) { - return false; - } - - $return = array (); - foreach ($result as $server) { - switch ($server['server_type']) { - case SERVER_TYPE_DATA: - $server["img"] = html_print_image ("images/data.png", true, array ("title" => __('Data server'))); - $server["type"] = "data"; - $id_modulo = 1; - break; - case SERVER_TYPE_NETWORK: - $server["img"] = html_print_image ("images/network.png", true, array ("title" => __('Network server'))); - $server["type"] = "network"; - $id_modulo = 2; - break; - case SERVER_TYPE_SNMP: - $server["img"] = html_print_image ("images/snmp.png", true, array ("title" => __('SNMP Trap server'))); - $server["type"] = "snmp"; - $id_modulo = 0; - break; - case SERVER_TYPE_RECON: - $server["img"] = html_print_image ("images/recon.png", true, array ("title" => __('Recon server'))); - $server["type"] = "recon"; - $id_modulo = 0; - break; - case SERVER_TYPE_PLUGIN: - $server["img"] = html_print_image ("images/plugin.png", true, array ("title" => __('Plugin server'))); - $server["type"] = "plugin"; - $id_modulo = 4; - break; - case SERVER_TYPE_PREDICTION: - $server["img"] = html_print_image ("images/chart_bar.png", true, array ("title" => __('Prediction server'))); - $server["type"] = "prediction"; - $id_modulo = 5; - break; - case SERVER_TYPE_WMI: - $server["img"] = html_print_image ("images/wmi.png", true, array ("title" => __('WMI server'))); - $server["type"] = "wmi"; - $id_modulo = 6; - break; - case SERVER_TYPE_EXPORT: - $server["img"] = html_print_image ("images/server_export.png", true, array ("title" => __('Export server'))); - $server["type"] = "export"; - $id_modulo = 0; - break; - case SERVER_TYPE_INVENTORY: - $server["img"] = html_print_image ("images/page_white_text.png", true, array ("title" => __('Inventory server'))); - $server["type"] = "inventory"; - $id_modulo = 0; - break; - case SERVER_TYPE_WEB: - $server["img"] = html_print_image ("images/world.png", true, array ("title" => __('Web server'))); - $server["type"] = "web"; - $id_modulo = 0; - break; - case SERVER_TYPE_EVENT: - $server["img"] = html_print_image ("images/lightning_go.png", true, array ("title" => __('Event server'))); - $server["type"] = "event"; - $id_modulo = 2; - break; - case SERVER_TYPE_ENTERPRISE_ICMP: - $server["img"] = html_print_image ("images/network.png", true, array ("title" => __('Enterprise ICMP server'))); - $server["type"] = "enterprise icmp"; - $id_modulo = 2; - break; - case SERVER_TYPE_ENTERPRISE_SNMP: - $server["img"] = html_print_image ("images/network.png", true, array ("title" => __('Enterprise SNMP server'))); - $server["type"] = "enterprise snmp"; - $id_modulo = 2; - break; - case SERVER_TYPE_ENTERPRISE_SATELLITE: - $server["img"] = html_print_image ("images/satellite.png", true, array ("title" => __('Enterprise Satellite server'))); - $server["type"] = "enterprise satellite"; - $id_modulo = 0; - break; - case SERVER_TYPE_ENTERPRISE_TRANSACTIONAL: - $server["img"] = html_print_image ("images/transactional_map.png", true, array ("title" => __('Enterprise Transactional server'))); - $server["type"] = "enterprise transactional"; - $id_modulo = 0; - break; - case SERVER_TYPE_MAINFRAME: - $server["img"] = html_print_image ("images/mainframe.png", true, array ("title" => __('Mainframe server'))); - $server["type"] = "mainframe"; - $id_modulo = 0; - break; - case SERVER_TYPE_SYNC: - $server["img"] = html_print_image ("images/sync.png", true, array ("title" => __('Sync server'))); - $server["type"] = "sync"; - $id_modulo = 0; - break; - case SERVER_TYPE_WUX: - $server["img"] = html_print_image ("images/icono-wux.png", true, array ("title" => __('Wux server'))); - $server["type"] = "wux"; - $id_modulo = 0; - break; - case SERVER_TYPE_SYSLOG: - $server["img"] = html_print_image ("images/syslog.png", true, array ("title" => __('Syslog server'))); - $server["type"] = "syslog"; - $id_modulo = 0; - break; - case SERVER_TYPE_AUTOPROVISION: - $server["img"] = html_print_image ("images/autoprovision.png", true, array ("title" => __('Autoprovision server'))); - $server["type"] = "autoprovision"; - $id_modulo = 0; - break; - case SERVER_TYPE_MIGRATION: - $server["img"] = html_print_image ("images/migration.png", true, array ("title" => __('Migration server'))); - $server["type"] = "migration"; - $id_modulo = 0; - break; - default: - $server["img"] = ''; - $server["type"] = "unknown"; - $id_modulo = 0; - break; - } - - if ($config["realtimestats"] == 0) { - // --------------------------------------------------------------- - // Take data from database if not realtime stats - // --------------------------------------------------------------- - - $server["lag"] = db_get_sql ("SELECT lag_time FROM tserver WHERE id_server = ".$server["id_server"]); - $server["module_lag"] = db_get_sql ("SELECT lag_modules FROM tserver WHERE id_server = ".$server["id_server"]); - $server["modules"] = db_get_sql ("SELECT my_modules FROM tserver WHERE id_server = ".$server["id_server"]); - $server["modules_total"] = db_get_sql ("SELECT total_modules_running FROM tserver WHERE id_server = ".$server["id_server"]); - - } - else { - - // --------------------------------------------------------------- - // Take data in realtime - // --------------------------------------------------------------- - - - - $server["module_lag"] = 0; - $server["lag"] = 0; - - // Inventory server - if ($server["server_type"] == SERVER_TYPE_INVENTORY) { - - // Get modules exported by this server - $server["modules"] = db_get_sql ("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente AND tagente.server_name = '" . $server["name"] . "'"); - - // Get total exported modules - $server["modules_total"] = db_get_sql ("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente"); - - $interval_esc = db_escape_key_identifier ("interval"); - - // Get the module lag - $server["module_lag"] = db_get_sql ("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) AS module_lag + FROM tserver '.$select_id.' + ORDER BY server_type'; + $result = db_get_all_rows_sql($sql); + $time = get_system_time(); + + if (empty($result)) { + return false; + } + + $return = []; + foreach ($result as $server) { + switch ($server['server_type']) { + case SERVER_TYPE_DATA: + $server['img'] = html_print_image('images/data.png', true, ['title' => __('Data server')]); + $server['type'] = 'data'; + $id_modulo = 1; + break; + + case SERVER_TYPE_NETWORK: + $server['img'] = html_print_image('images/network.png', true, ['title' => __('Network server')]); + $server['type'] = 'network'; + $id_modulo = 2; + break; + + case SERVER_TYPE_SNMP: + $server['img'] = html_print_image('images/snmp.png', true, ['title' => __('SNMP Trap server')]); + $server['type'] = 'snmp'; + $id_modulo = 0; + break; + + case SERVER_TYPE_RECON: + $server['img'] = html_print_image('images/recon.png', true, ['title' => __('Recon server')]); + $server['type'] = 'recon'; + $id_modulo = 0; + break; + + case SERVER_TYPE_PLUGIN: + $server['img'] = html_print_image('images/plugin.png', true, ['title' => __('Plugin server')]); + $server['type'] = 'plugin'; + $id_modulo = 4; + break; + + case SERVER_TYPE_PREDICTION: + $server['img'] = html_print_image('images/chart_bar.png', true, ['title' => __('Prediction server')]); + $server['type'] = 'prediction'; + $id_modulo = 5; + break; + + case SERVER_TYPE_WMI: + $server['img'] = html_print_image('images/wmi.png', true, ['title' => __('WMI server')]); + $server['type'] = 'wmi'; + $id_modulo = 6; + break; + + case SERVER_TYPE_EXPORT: + $server['img'] = html_print_image('images/server_export.png', true, ['title' => __('Export server')]); + $server['type'] = 'export'; + $id_modulo = 0; + break; + + case SERVER_TYPE_INVENTORY: + $server['img'] = html_print_image('images/page_white_text.png', true, ['title' => __('Inventory server')]); + $server['type'] = 'inventory'; + $id_modulo = 0; + break; + + case SERVER_TYPE_WEB: + $server['img'] = html_print_image('images/world.png', true, ['title' => __('Web server')]); + $server['type'] = 'web'; + $id_modulo = 0; + break; + + case SERVER_TYPE_EVENT: + $server['img'] = html_print_image('images/lightning_go.png', true, ['title' => __('Event server')]); + $server['type'] = 'event'; + $id_modulo = 2; + break; + + case SERVER_TYPE_ENTERPRISE_ICMP: + $server['img'] = html_print_image('images/network.png', true, ['title' => __('Enterprise ICMP server')]); + $server['type'] = 'enterprise icmp'; + $id_modulo = 2; + break; + + case SERVER_TYPE_ENTERPRISE_SNMP: + $server['img'] = html_print_image('images/network.png', true, ['title' => __('Enterprise SNMP server')]); + $server['type'] = 'enterprise snmp'; + $id_modulo = 2; + break; + + case SERVER_TYPE_ENTERPRISE_SATELLITE: + $server['img'] = html_print_image('images/satellite.png', true, ['title' => __('Enterprise Satellite server')]); + $server['type'] = 'enterprise satellite'; + $id_modulo = 0; + break; + + case SERVER_TYPE_ENTERPRISE_TRANSACTIONAL: + $server['img'] = html_print_image('images/transactional_map.png', true, ['title' => __('Enterprise Transactional server')]); + $server['type'] = 'enterprise transactional'; + $id_modulo = 0; + break; + + case SERVER_TYPE_MAINFRAME: + $server['img'] = html_print_image('images/mainframe.png', true, ['title' => __('Mainframe server')]); + $server['type'] = 'mainframe'; + $id_modulo = 0; + break; + + case SERVER_TYPE_SYNC: + $server['img'] = html_print_image('images/sync.png', true, ['title' => __('Sync server')]); + $server['type'] = 'sync'; + $id_modulo = 0; + break; + + case SERVER_TYPE_WUX: + $server['img'] = html_print_image('images/icono-wux.png', true, ['title' => __('Wux server')]); + $server['type'] = 'wux'; + $id_modulo = 0; + break; + + case SERVER_TYPE_SYSLOG: + $server['img'] = html_print_image('images/syslog.png', true, ['title' => __('Syslog server')]); + $server['type'] = 'syslog'; + $id_modulo = 0; + break; + + case SERVER_TYPE_AUTOPROVISION: + $server['img'] = html_print_image('images/autoprovision.png', true, ['title' => __('Autoprovision server')]); + $server['type'] = 'autoprovision'; + $id_modulo = 0; + break; + + case SERVER_TYPE_MIGRATION: + $server['img'] = html_print_image('images/migration.png', true, ['title' => __('Migration server')]); + $server['type'] = 'migration'; + $id_modulo = 0; + break; + + default: + $server['img'] = ''; + $server['type'] = 'unknown'; + $id_modulo = 0; + break; + } + + if ($config['realtimestats'] == 0) { + // --------------------------------------------------------------- + // Take data from database if not realtime stats + // --------------------------------------------------------------- + $server['lag'] = db_get_sql('SELECT lag_time FROM tserver WHERE id_server = '.$server['id_server']); + $server['module_lag'] = db_get_sql('SELECT lag_modules FROM tserver WHERE id_server = '.$server['id_server']); + $server['modules'] = db_get_sql('SELECT my_modules FROM tserver WHERE id_server = '.$server['id_server']); + $server['modules_total'] = db_get_sql('SELECT total_modules_running FROM tserver WHERE id_server = '.$server['id_server']); + } else { + // --------------------------------------------------------------- + // Take data in realtime + // --------------------------------------------------------------- + $server['module_lag'] = 0; + $server['lag'] = 0; + + // Inventory server + if ($server['server_type'] == SERVER_TYPE_INVENTORY) { + // Get modules exported by this server + $server['modules'] = db_get_sql("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente AND tagente.server_name = '".$server['name']."'"); + + // Get total exported modules + $server['modules_total'] = db_get_sql('SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente'); + + $interval_esc = db_escape_key_identifier('interval'); + + // Get the module lag + $server['module_lag'] = db_get_sql( + 'SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) AS module_lag FROM tagente, tagent_module_inventory WHERE utimestamp > 0 AND tagent_module_inventory.id_agente = tagente.id_agente - AND tagent_module_inventory." . $interval_esc . " > 0 - AND tagente.server_name = '" . $server["name"] . "' - AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory." . $interval_esc . " * 10) - AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory." . $interval_esc); - - // Get the lag - $server["lag"] = db_get_sql ("SELECT AVG(UNIX_TIMESTAMP() - utimestamp - tagent_module_inventory." . $interval_esc . ") + AND tagent_module_inventory.'.$interval_esc." > 0 + AND tagente.server_name = '".$server['name']."' + AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory.".$interval_esc.' * 10) + AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory.'.$interval_esc + ); + + // Get the lag + $server['lag'] = db_get_sql( + 'SELECT AVG(UNIX_TIMESTAMP() - utimestamp - tagent_module_inventory.'.$interval_esc.') FROM tagente, tagent_module_inventory WHERE utimestamp > 0 AND tagent_module_inventory.id_agente = tagente.id_agente - AND tagent_module_inventory." . $interval_esc . " > 0 - AND tagente.server_name = '" . $server["name"] . "' - AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory." . $interval_esc . " * 10) - AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory." . $interval_esc); - // Export server - } - else if ($server["server_type"] == SERVER_TYPE_EXPORT) { - - // Get modules exported by this server - $server["modules"] = db_get_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo, tserver_export WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export = tserver_export.id AND tserver_export.id_export_server = " . $server["id_server"]); - - // Get total exported modules - $server["modules_total"] = db_get_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export != 0"); - - $server["lag"] = 0; - $server["module_lag"] = 0; - - } - // Recon server - else if ($server["server_type"] == SERVER_TYPE_RECON) { - - $server["name"] = ''.$server["name"].''; - - //Total jobs running on this recon server - $server["modules"] = db_get_sql ("SELECT COUNT(id_rt) + AND tagent_module_inventory.'.$interval_esc." > 0 + AND tagente.server_name = '".$server['name']."' + AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory.".$interval_esc.' * 10) + AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory.'.$interval_esc + ); + // Export server + } else if ($server['server_type'] == SERVER_TYPE_EXPORT) { + // Get modules exported by this server + $server['modules'] = db_get_sql('SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo, tserver_export WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export = tserver_export.id AND tserver_export.id_export_server = '.$server['id_server']); + + // Get total exported modules + $server['modules_total'] = db_get_sql('SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export != 0'); + + $server['lag'] = 0; + $server['module_lag'] = 0; + } + // Recon server + else if ($server['server_type'] == SERVER_TYPE_RECON) { + $server['name'] = ''.$server['name'].''; + + // Total jobs running on this recon server + $server['modules'] = db_get_sql( + 'SELECT COUNT(id_rt) FROM trecon_task - WHERE id_recon_server = ".$server["id_server"]); - - //Total recon jobs (all servers) - $server["modules_total"] = db_get_sql ("SELECT COUNT(status) FROM trecon_task"); - - //Lag (take average active time of all active tasks) - $server["module_lag"] = 0; - - switch ($config["dbtype"]) { - case "mysql": - $server["lag"] = db_get_sql ("SELECT UNIX_TIMESTAMP() - utimestamp from trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - - $server["module_lag"] = db_get_sql ("SELECT COUNT(id_rt) FROM trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - break; - case "postgresql": - $server["lag"] = db_get_sql ("SELECT ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp from trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - - $server["module_lag"] = db_get_sql ("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - break; - case "oracle": - $server["lag"] = db_get_sql ("SELECT ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp from trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - - $server["module_lag"] = db_get_sql ("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - break; - } - } - else { - - // --------------------------------------------------------------- - // Data, Plugin, WMI, Network and Others - - $server["modules"] = db_get_sql ("SELECT count(tagente_estado.id_agente_modulo) FROM tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = ".$server["id_server"]); - - $server["modules_total"] = db_get_sql ("SELECT count(tagente_estado.id_agente_modulo) FROM tserver, tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = tserver.id_server AND tserver.server_type = ".$server["server_type"]); - - // Remote servers LAG Calculation (server_type != 0) - if ($server["server_type"] != 0) { - switch ($config["dbtype"]) { - case "mysql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + WHERE id_recon_server = '.$server['id_server'] + ); + + // Total recon jobs (all servers) + $server['modules_total'] = db_get_sql('SELECT COUNT(status) FROM trecon_task'); + + // Lag (take average active time of all active tasks) + $server['module_lag'] = 0; + + switch ($config['dbtype']) { + case 'mysql': + $server['lag'] = db_get_sql('SELECT UNIX_TIMESTAMP() - utimestamp from trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + + $server['module_lag'] = db_get_sql('SELECT COUNT(id_rt) FROM trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + break; + + case 'postgresql': + $server['lag'] = db_get_sql("SELECT ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp from trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server['id_server']); + + $server['module_lag'] = db_get_sql("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server['id_server']); + break; + + case 'oracle': + $server['lag'] = db_get_sql("SELECT ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp from trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + + $server['module_lag'] = db_get_sql("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + break; + } + } else { + // --------------------------------------------------------------- + // Data, Plugin, WMI, Network and Others + $server['modules'] = db_get_sql('SELECT count(tagente_estado.id_agente_modulo) FROM tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = '.$server['id_server']); + + $server['modules_total'] = db_get_sql('SELECT count(tagente_estado.id_agente_modulo) FROM tserver, tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = tserver.id_server AND tserver.server_type = '.$server['server_type']); + + // Remote servers LAG Calculation (server_type != 0) + if ($server['server_type'] != 0) { + switch ($config['dbtype']) { + case 'mysql': + $result = db_get_row_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND running_by = ".$server["id_server"]." + AND running_by = '.$server['id_server'].' AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) - AND (UNIX_TIMESTAMP() - utimestamp) > current_interval"); - break; - case "postgresql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND (UNIX_TIMESTAMP() - utimestamp) > current_interval' + ); + break; + + case 'postgresql': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND running_by = ".$server["id_server"]." + AND running_by = ".$server['id_server']." AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) < ( current_interval * 10) - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > current_interval"); - break; - case "oracle": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > current_interval" + ); + break; + + case 'oracle': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND running_by = ".$server["id_server"]." - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp) < ( current_interval * 10) - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) - utimestamp) * (" . SECONDS_1DAY . ")) > current_interval"); - break; - } - } - else { - // Local/Dataserver server LAG calculation: - switch ($config["dbtype"]) { - case "mysql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND running_by = '.$server['id_server']." + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp) < ( current_interval * 10) + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) - utimestamp) * (".SECONDS_1DAY.')) > current_interval' + ); + break; + } + } else { + // Local/Dataserver server LAG calculation: + switch ($config['dbtype']) { + case 'mysql': + $result = db_get_row_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente @@ -635,11 +703,14 @@ function servers_get_info ($id_server = -1) { AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) - AND running_by = ".$server["id_server"]." - AND (UNIX_TIMESTAMP() - utimestamp) > (current_interval * 1.1)"); - break; - case "postgresql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND running_by = '.$server['id_server'].' + AND (UNIX_TIMESTAMP() - utimestamp) > (current_interval * 1.1)' + ); + break; + + case 'postgresql': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente @@ -648,11 +719,14 @@ function servers_get_info ($id_server = -1) { AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) < ( current_interval * 10) - AND running_by = ".$server["id_server"]." - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > (current_interval * 1.1)"); - break; - case "oracle": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND running_by = ".$server['id_server']." + AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > (current_interval * 1.1)" + ); + break; + + case 'oracle': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente @@ -660,52 +734,51 @@ function servers_get_info ($id_server = -1) { AND tagente_modulo.id_tipo_modulo < 5 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp) < ( current_interval * 10) - AND running_by = ".$server["id_server"]." - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp) > (current_interval * 1.1)"); - break; - } - } - - // Lag over current_interval * 2 is not lag, it's a timed out module - - if (!empty ($result["lag"])) { - $server["lag"] = $result["lag"]; - } - - if (!empty ($result["module_lag"])) { - $server["module_lag"] = $result["module_lag"]; - } - } - } // Take data for realtime mode - - if (isset($server["module_lag"])) - $server["lag_txt"] = - ($server["lag"] == 0 ? - '-' - : - human_time_description_raw($server["lag"])) . " / " . $server["module_lag"]; - else - $server["lag_txt"] = ""; - - if ($server["modules_total"] > 0) { - $server["load"] = round ($server["modules"] / $server["modules_total"] * 100); - } - else { - $server["load"] = 0; - } - - //Push the raw data on the return stack - $return[$server["id_server"]] = $server; - } // Main foreach - - return $return; + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp) < ( current_interval * 10) + AND running_by = '.$server['id_server']." + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp) > (current_interval * 1.1)' + ); + break; + } + } + + // Lag over current_interval * 2 is not lag, it's a timed out module + if (!empty($result['lag'])) { + $server['lag'] = $result['lag']; + } + + if (!empty($result['module_lag'])) { + $server['module_lag'] = $result['module_lag']; + } + } + } //end if + + if (isset($server['module_lag'])) { + $server['lag_txt'] = ($server['lag'] == 0 ? '-' : human_time_description_raw($server['lag'])).' / '.$server['module_lag']; + } else { + $server['lag_txt'] = ''; + } + + if ($server['modules_total'] > 0) { + $server['load'] = round(($server['modules'] / $server['modules_total'] * 100)); + } else { + $server['load'] = 0; + } + + // Push the raw data on the return stack + $return[$server['id_server']] = $server; + } //end foreach + + return $return; } -function servers_get_servers_type($type) { - return db_get_all_rows_filter('tserver', array('server_type' => $type)); + +function servers_get_servers_type($type) +{ + return db_get_all_rows_filter('tserver', ['server_type' => $type]); } + /** * Get the server name. * @@ -713,41 +786,46 @@ function servers_get_servers_type($type) { * * @return string Name of the given server */ -function servers_get_name ($id_server) { - return (string) db_get_value ('name', 'tserver', 'id_server', (int) $id_server); +function servers_get_name($id_server) +{ + return (string) db_get_value('name', 'tserver', 'id_server', (int) $id_server); } + /** * Get the presence of .conf and .md5 into remote_config dir - * + * * @param string Agent name - * + * * @return true if files exist and are writable */ -function servers_check_remote_config ($server_name) { - global $config; - - $server_md5 = md5 ($server_name, false); - - $filenames = array(); - $filenames['md5'] = io_safe_output($config["remote_config"]) - . "/md5/" . $server_md5 . ".srv.md5"; - $filenames['conf'] = io_safe_output($config["remote_config"]) - . "/conf/" . $server_md5 . ".srv.conf"; - - if (! isset ($filenames['conf'])) - return false; - if (! isset ($filenames['md5'])) - return false; - - return (file_exists ($filenames['conf']) - && is_writable ($filenames['conf']) - && file_exists ($filenames['md5']) - && is_writable ($filenames['md5'])); +function servers_check_remote_config($server_name) +{ + global $config; + + $server_md5 = md5($server_name, false); + + $filenames = []; + $filenames['md5'] = io_safe_output($config['remote_config']).'/md5/'.$server_md5.'.srv.md5'; + $filenames['conf'] = io_safe_output($config['remote_config']).'/conf/'.$server_md5.'.srv.conf'; + + if (! isset($filenames['conf'])) { + return false; + } + + if (! isset($filenames['md5'])) { + return false; + } + + return (file_exists($filenames['conf']) + && is_writable($filenames['conf']) + && file_exists($filenames['md5']) + && is_writable($filenames['md5'])); } + /** * Return a string containing image tag for a given target id (server) * TODO: Make this print_servertype_icon and move to functions_ui.php. Make XHTML compatible. Make string translatable @@ -758,72 +836,87 @@ function servers_check_remote_config ($server_name) { * * @return string Fully formatted IMG HTML tag with icon */ -function servers_show_type ($id) { - global $config; - - switch ($id) { - case 1: - return html_print_image("images/database.png", true, array("title" => get_product_name() . " Data server")); - break; - case 2: - return html_print_image("images/network.png", true, array("title" => get_product_name() . " Network server")); - break; - case 4: - return html_print_image("images/plugin.png", true, array("title" => get_product_name() . " Plugin server")); - break; - case 5: - return html_print_image("images/chart_bar.png", true, array("title" => get_product_name() . " Prediction server")); - break; - case 6: - return html_print_image("images/wmi.png", true, array("title" => get_product_name() . " WMI server")); - break; - case 7: - return html_print_image("images/server_web.png", true, array("title" => get_product_name() . " WEB server")); - break; - case 8: - return html_print_image("images/module-wux.png", true, array("title" => get_product_name() . " WUX server")); - break; - default: - return "--"; - break; - } +function servers_show_type($id) +{ + global $config; + + switch ($id) { + case 1: + return html_print_image('images/database.png', true, ['title' => get_product_name().' Data server']); + + break; + case 2: + return html_print_image('images/network.png', true, ['title' => get_product_name().' Network server']); + + break; + case 4: + return html_print_image('images/plugin.png', true, ['title' => get_product_name().' Plugin server']); + + break; + case 5: + return html_print_image('images/chart_bar.png', true, ['title' => get_product_name().' Prediction server']); + + break; + case 6: + return html_print_image('images/wmi.png', true, ['title' => get_product_name().' WMI server']); + + break; + case 7: + return html_print_image('images/server_web.png', true, ['title' => get_product_name().' WEB server']); + + break; + case 8: + return html_print_image('images/module-wux.png', true, ['title' => get_product_name().' WUX server']); + + break; + default: + return '--'; + break; + } } + /** * Get the numbers of servers up. * * This check assumes that server_keepalive should be at least 15 minutes. * - * @return int The number of servers alive. + * @return integer The number of servers alive. */ -function servers_check_status () { - global $config; - - switch ($config["dbtype"]) { - case "mysql": - $sql = "SELECT COUNT(id_server) +function servers_check_status() +{ + global $config; + + switch ($config['dbtype']) { + case 'mysql': + $sql = 'SELECT COUNT(id_server) FROM tserver WHERE status = 1 - AND keepalive > NOW() - INTERVAL server_keepalive*2 SECOND"; - break; - case "postgresql": - $sql = "SELECT COUNT(id_server) + AND keepalive > NOW() - INTERVAL server_keepalive*2 SECOND'; + break; + + case 'postgresql': + $sql = "SELECT COUNT(id_server) FROM tserver WHERE status = 1 AND keepalive > NOW() - INTERVAL 'server_keepalive*2 SECOND'"; - break; - case "oracle": - $sql = "SELECT COUNT(id_server) + break; + + case 'oracle': + $sql = "SELECT COUNT(id_server) FROM tserver WHERE status = 1 AND keepalive > systimestamp - INTERVAL 'server_keepalive*2' SECOND"; - break; - } - $status = (int) db_get_sql ($sql); //Cast as int will assure a number value - // This function should just ack of server down, not set it down. - return $status; + break; + } + + $status = (int) db_get_sql($sql); + // Cast as int will assure a number value + // This function should just ack of server down, not set it down. + return $status; } + /** * @deprecated use servers_get_info instead * Get statistical information for a given server @@ -832,8 +925,66 @@ function servers_check_status () { * * @return array Server info array */ -function servers_get_status ($id_server) { - $serverinfo = servers_get_info ($id_server); - return $serverinfo[$id_server]; +function servers_get_status($id_server) +{ + $serverinfo = servers_get_info($id_server); + return $serverinfo[$id_server]; +} + + +/** + * Return server name based on identifier. + * + * @param integer $server Server identifier. + * + * @return string Server name + */ +function get_server_string_name(int $server) +{ + switch ($server) { + case SERVER_TYPE_DATA: + return __('Data server'); + + case SERVER_TYPE_NETWORK: + return __('Network server'); + + case SERVER_TYPE_SNMP: + return __('SNMP server'); + + case SERVER_TYPE_ENTERPRISE_ICMP: + return __('Enterprise ICMP server'); + + case SERVER_TYPE_ENTERPRISE_SNMP: + return __('Enterprise SNMP server'); + + case SERVER_TYPE_PLUGIN: + return __('Plugin server'); + + case SERVER_TYPE_PREDICTION: + return __('Prediction Server'); + + case SERVER_TYPE_WMI: + return __('WMI server'); + + case SERVER_TYPE_WEB: + return __('Web server'); + + case SERVER_TYPE_EXPORT: + return __('Export server'); + + case SERVER_TYPE_INVENTORY: + return __('Inventory server'); + + case SERVER_TYPE_EVENT: + return __('Event server'); + + case SERVER_TYPE_RECON: + return __('Discovery server'); + + case SERVER_TYPE_SYSLOG: + return __('Syslog server'); + + default: + return __('N/A'); + } } -?> From 89af077b52dcf2bc49fa8ca3cee437c6e2361e86 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 4 Feb 2019 19:16:30 +0100 Subject: [PATCH 037/249] Servers get server string name Former-commit-id: e67755e9a86872ba65c5768191cba80fbd879322 --- pandora_console/include/functions_servers.php | 1425 +++++++++-------- 1 file changed, 788 insertions(+), 637 deletions(-) diff --git a/pandora_console/include/functions_servers.php b/pandora_console/include/functions_servers.php index 6bd255e88d..bc5fd590f3 100644 --- a/pandora_console/include/functions_servers.php +++ b/pandora_console/include/functions_servers.php @@ -1,24 +1,32 @@ 0, 'status' => 1); - db_process_sql_update('trecon_task', $values, array('id_rt' => $id_recon_task)); +function servers_force_recon_task($id_recon_task) +{ + $values = [ + 'utimestamp' => 0, + 'status' => 1, + ]; + db_process_sql_update('trecon_task', $values, ['id_rt' => $id_recon_task]); } + /** * This function will get several metrics from the database to get info about server performance - * @return array with several data + * + * @return array with several data */ -function servers_get_performance () { - - global $config; - - $data = array(); - $data["total_modules"] = 0; - $data["total_remote_modules"] = 0; - $data["total_local_modules"] = 0; - $data["avg_interval_total_modules"] = array(); - $data["avg_interval_remote_modules"] = array(); - $data["avg_interval_local_modules"] = 0; - $data["local_modules_rate"] = 0; - $data["network_modules_rate"] = 0; - - if ($config["realtimestats"] == 1) { - - $counts = db_get_all_rows_sql (" +function servers_get_performance() +{ + global $config; + + $data = []; + $data['total_modules'] = 0; + $data['total_remote_modules'] = 0; + $data['total_local_modules'] = 0; + $data['avg_interval_total_modules'] = []; + $data['avg_interval_remote_modules'] = []; + $data['avg_interval_local_modules'] = 0; + $data['local_modules_rate'] = 0; + $data['network_modules_rate'] = 0; + + if ($config['realtimestats'] == 1) { + $counts = db_get_all_rows_sql( + ' SELECT tagente_modulo.id_modulo, COUNT(tagente_modulo.id_agente_modulo) modules FROM tagente_modulo, tagente_estado, tagente @@ -95,94 +119,108 @@ function servers_get_performance () { AND (utimestamp > 0 OR (id_tipo_modulo = 100 OR (id_tipo_modulo > 21 AND id_tipo_modulo < 23))) AND tagente.disabled = 0 - GROUP BY tagente_modulo.id_modulo"); - - if (empty($counts)) { - $counts = array(); - } - - foreach($counts as $c) { - switch($c['id_modulo']) { - case MODULE_DATA: - $data["total_local_modules"] = $c['modules']; - break; - case MODULE_NETWORK: - $data["total_network_modules"] = $c['modules']; - break; - case MODULE_PLUGIN: - $data["total_plugin_modules"] = $c['modules']; - break; - case MODULE_PREDICTION: - $data["total_prediction_modules"] = $c['modules']; - break; - case MODULE_WMI: - $data["total_wmi_modules"] = $c['modules']; - break; - case MODULE_WEB: - $data["total_web_modules"] = $c['modules']; - break; - } - - if($c['id_modulo'] != MODULE_DATA) { - $data["total_remote_modules"] += $c['modules']; - } - - $data["total_modules"] += $c['modules']; - } - } - else { - $counts = db_get_all_rows_sql (" + GROUP BY tagente_modulo.id_modulo' + ); + + if (empty($counts)) { + $counts = []; + } + + foreach ($counts as $c) { + switch ($c['id_modulo']) { + case MODULE_DATA: + $data['total_local_modules'] = $c['modules']; + break; + + case MODULE_NETWORK: + $data['total_network_modules'] = $c['modules']; + break; + + case MODULE_PLUGIN: + $data['total_plugin_modules'] = $c['modules']; + break; + + case MODULE_PREDICTION: + $data['total_prediction_modules'] = $c['modules']; + break; + + case MODULE_WMI: + $data['total_wmi_modules'] = $c['modules']; + break; + + case MODULE_WEB: + $data['total_web_modules'] = $c['modules']; + break; + } + + if ($c['id_modulo'] != MODULE_DATA) { + $data['total_remote_modules'] += $c['modules']; + } + + $data['total_modules'] += $c['modules']; + } + } else { + $counts = db_get_all_rows_sql( + ' SELECT server_type, my_modules modules FROM tserver - GROUP BY server_type"); - - if (empty($counts)) { - $counts = array(); - } - - foreach ($counts as $c) { - switch ($c['server_type']) { - case SERVER_TYPE_DATA: - $data["total_local_modules"] = $c['modules']; - break; - case SERVER_TYPE_NETWORK: - case SERVER_TYPE_SNMP: - case SERVER_TYPE_ENTERPRISE_ICMP: - case SERVER_TYPE_ENTERPRISE_SNMP: - $data["total_network_modules"] = $c['modules']; - break; - case SERVER_TYPE_PLUGIN: - $data["total_plugin_modules"] = $c['modules']; - break; - case SERVER_TYPE_PREDICTION: - $data["total_prediction_modules"] = $c['modules']; - break; - case SERVER_TYPE_WMI: - $data["total_wmi_modules"] = $c['modules']; - break; - case SERVER_TYPE_WEB: - $data["total_web_modules"] = $c['modules']; - break; - case SERVER_TYPE_EXPORT: - case SERVER_TYPE_INVENTORY: - case SERVER_TYPE_EVENT: - case SERVER_TYPE_RECON: - case SERVER_TYPE_SYSLOG: - break; - } - - if ($c['server_type'] != SERVER_TYPE_DATA) { - $data["total_remote_modules"] += $c['modules']; - } - - $data["total_modules"] += $c['modules']; - } - } - - $interval_avgs = array(); - - // Avg of modules interval when modules have module_interval > 0 - $interval_avgs_modules = db_get_all_rows_sql (" + GROUP BY server_type' + ); + + if (empty($counts)) { + $counts = []; + } + + foreach ($counts as $c) { + switch ($c['server_type']) { + case SERVER_TYPE_DATA: + $data['total_local_modules'] = $c['modules']; + break; + + case SERVER_TYPE_NETWORK: + case SERVER_TYPE_SNMP: + case SERVER_TYPE_ENTERPRISE_ICMP: + case SERVER_TYPE_ENTERPRISE_SNMP: + $data['total_network_modules'] = $c['modules']; + break; + + case SERVER_TYPE_PLUGIN: + $data['total_plugin_modules'] = $c['modules']; + break; + + case SERVER_TYPE_PREDICTION: + $data['total_prediction_modules'] = $c['modules']; + break; + + case SERVER_TYPE_WMI: + $data['total_wmi_modules'] = $c['modules']; + break; + + case SERVER_TYPE_WEB: + $data['total_web_modules'] = $c['modules']; + break; + + case SERVER_TYPE_EXPORT: + case SERVER_TYPE_INVENTORY: + case SERVER_TYPE_EVENT: + case SERVER_TYPE_RECON: + case SERVER_TYPE_SYSLOG: + break; + } + + if ($c['server_type'] != SERVER_TYPE_DATA) { + $data['total_remote_modules'] += $c['modules']; + } + + $data['total_modules'] += $c['modules']; + } + } + + $interval_avgs = []; + + // Avg of modules interval when modules have module_interval > 0 + $interval_avgs_modules = db_get_all_rows_sql( + ' SELECT count(tagente_modulo.id_modulo) modules , tagente_modulo.id_modulo, AVG(tagente_modulo.module_interval) avg_interval @@ -194,20 +232,22 @@ function servers_get_performance () { AND delete_pending = 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente - GROUP BY tagente_modulo.id_modulo"); - - if (empty($interval_avgs_modules)) { - $interval_avgs_modules = array(); - } - - // Transform into a easily format - foreach ($interval_avgs_modules as $iamodules) { - $interval_avgs[$iamodules['id_modulo']]['avg_interval'] = $iamodules['avg_interval']; - $interval_avgs[$iamodules['id_modulo']]['modules'] = $iamodules['modules']; - } - - // Avg of agents interval when modules have module_interval == 0 - $interval_avgs_agents = db_get_all_rows_sql (" + GROUP BY tagente_modulo.id_modulo' + ); + + if (empty($interval_avgs_modules)) { + $interval_avgs_modules = []; + } + + // Transform into a easily format + foreach ($interval_avgs_modules as $iamodules) { + $interval_avgs[$iamodules['id_modulo']]['avg_interval'] = $iamodules['avg_interval']; + $interval_avgs[$iamodules['id_modulo']]['modules'] = $iamodules['modules']; + } + + // Avg of agents interval when modules have module_interval == 0 + $interval_avgs_agents = db_get_all_rows_sql( + ' SELECT count(tagente_modulo.id_modulo) modules , tagente_modulo.id_modulo, AVG(tagente.intervalo) avg_interval FROM tagente_modulo, tagente_estado, tagente @@ -218,82 +258,86 @@ function servers_get_performance () { AND delete_pending = 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente - GROUP BY tagente_modulo.id_modulo"); - - if (empty($interval_avgs_agents)) { - $interval_avgs_agents = array(); - } - - // Merge with the previous calculated array - foreach ($interval_avgs_agents as $iaagents) { - if (!isset($interval_avgs[$iaagents['id_modulo']]['modules'])) { - $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = $iaagents['avg_interval']; - $interval_avgs[$iaagents['id_modulo']]['modules'] = $iaagents['modules']; - } - else { - $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = servers_get_avg_interval($interval_avgs[$iaagents['id_modulo']], $iaagents); - $interval_avgs[$iaagents['id_modulo']]['modules'] += $iaagents['modules']; - } - } - - foreach ($interval_avgs as $id_modulo => $ia) { - switch($id_modulo) { - case MODULE_DATA: - $data["avg_interval_local_modules"] = $ia['avg_interval']; - $data["local_modules_rate"] = - servers_get_rate($data["avg_interval_local_modules"], $data["total_local_modules"]); - break; - case MODULE_NETWORK: - $data["avg_interval_network_modules"] = $ia['avg_interval']; - $data["network_modules_rate"] = - servers_get_rate($data["avg_interval_network_modules"], - $data["total_network_modules"]); - break; - case MODULE_PLUGIN: - $data["avg_interval_plugin_modules"] = $ia['avg_interval']; - $data["plugin_modules_rate"] = servers_get_rate($data["avg_interval_plugin_modules"], $data["total_plugin_modules"]); - break; - case MODULE_PREDICTION: - $data["avg_interval_prediction_modules"] = $ia['avg_interval']; - $data["prediction_modules_rate"] = servers_get_rate($data["avg_interval_prediction_modules"], $data["total_prediction_modules"]); - break; - case MODULE_WMI: - $data["avg_interval_wmi_modules"] = $ia['avg_interval']; - $data["wmi_modules_rate"] = servers_get_rate($data["avg_interval_wmi_modules"], $data["total_wmi_modules"]); - break; - case MODULE_WEB: - $data["avg_interval_web_modules"] = $ia['avg_interval']; - $data["web_modules_rate"] = servers_get_rate($data["avg_interval_web_modules"], $data["total_web_modules"]); - break; - } - - if ($id_modulo != MODULE_DATA) { - $data["avg_interval_remote_modules"][] = $ia['avg_interval']; - } - - $data["avg_interval_total_modules"][] = $ia['avg_interval']; - } - - if (empty($data["avg_interval_remote_modules"])) { - $data["avg_interval_remote_modules"] = 0; - } - else { - $data["avg_interval_remote_modules"] = array_sum($data["avg_interval_remote_modules"]) / count($data["avg_interval_remote_modules"]); - } - - if (empty($data["avg_interval_total_modules"])) { - $data["avg_interval_total_modules"] = 0; - } - else { - $data["avg_interval_total_modules"] = array_sum($data["avg_interval_total_modules"]) / count($data["avg_interval_total_modules"]); - } - - $data["remote_modules_rate"] = servers_get_rate($data["avg_interval_remote_modules"], $data["total_remote_modules"]); - $data["total_modules_rate"] = servers_get_rate($data["avg_interval_total_modules"], $data["total_modules"]); - - return ($data); + GROUP BY tagente_modulo.id_modulo' + ); + + if (empty($interval_avgs_agents)) { + $interval_avgs_agents = []; + } + + // Merge with the previous calculated array + foreach ($interval_avgs_agents as $iaagents) { + if (!isset($interval_avgs[$iaagents['id_modulo']]['modules'])) { + $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = $iaagents['avg_interval']; + $interval_avgs[$iaagents['id_modulo']]['modules'] = $iaagents['modules']; + } else { + $interval_avgs[$iaagents['id_modulo']]['avg_interval'] = servers_get_avg_interval($interval_avgs[$iaagents['id_modulo']], $iaagents); + $interval_avgs[$iaagents['id_modulo']]['modules'] += $iaagents['modules']; + } + } + + foreach ($interval_avgs as $id_modulo => $ia) { + switch ($id_modulo) { + case MODULE_DATA: + $data['avg_interval_local_modules'] = $ia['avg_interval']; + $data['local_modules_rate'] = servers_get_rate($data['avg_interval_local_modules'], $data['total_local_modules']); + break; + + case MODULE_NETWORK: + $data['avg_interval_network_modules'] = $ia['avg_interval']; + $data['network_modules_rate'] = servers_get_rate( + $data['avg_interval_network_modules'], + $data['total_network_modules'] + ); + break; + + case MODULE_PLUGIN: + $data['avg_interval_plugin_modules'] = $ia['avg_interval']; + $data['plugin_modules_rate'] = servers_get_rate($data['avg_interval_plugin_modules'], $data['total_plugin_modules']); + break; + + case MODULE_PREDICTION: + $data['avg_interval_prediction_modules'] = $ia['avg_interval']; + $data['prediction_modules_rate'] = servers_get_rate($data['avg_interval_prediction_modules'], $data['total_prediction_modules']); + break; + + case MODULE_WMI: + $data['avg_interval_wmi_modules'] = $ia['avg_interval']; + $data['wmi_modules_rate'] = servers_get_rate($data['avg_interval_wmi_modules'], $data['total_wmi_modules']); + break; + + case MODULE_WEB: + $data['avg_interval_web_modules'] = $ia['avg_interval']; + $data['web_modules_rate'] = servers_get_rate($data['avg_interval_web_modules'], $data['total_web_modules']); + break; + } + + if ($id_modulo != MODULE_DATA) { + $data['avg_interval_remote_modules'][] = $ia['avg_interval']; + } + + $data['avg_interval_total_modules'][] = $ia['avg_interval']; + } + + if (empty($data['avg_interval_remote_modules'])) { + $data['avg_interval_remote_modules'] = 0; + } else { + $data['avg_interval_remote_modules'] = (array_sum($data['avg_interval_remote_modules']) / count($data['avg_interval_remote_modules'])); + } + + if (empty($data['avg_interval_total_modules'])) { + $data['avg_interval_total_modules'] = 0; + } else { + $data['avg_interval_total_modules'] = (array_sum($data['avg_interval_total_modules']) / count($data['avg_interval_total_modules'])); + } + + $data['remote_modules_rate'] = servers_get_rate($data['avg_interval_remote_modules'], $data['total_remote_modules']); + $data['total_modules_rate'] = servers_get_rate($data['avg_interval_total_modules'], $data['total_modules']); + + return ($data); } + /** * Get avg interval * @@ -302,15 +346,19 @@ function servers_get_performance () { * * @return float number of avg modules between two parts */ - -function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2) { - $total_modules = $modules_avg_interval1['modules'] + $modules_avg_interval2['modules']; - - $parcial1 = $modules_avg_interval1['avg_interval'] * $modules_avg_interval1['modules']; - $parcial2 = $modules_avg_interval2['avg_interval'] * $modules_avg_interval2['modules']; - - return ($parcial1 + $parcial2) / $total_modules; + + +function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2) +{ + $total_modules = ($modules_avg_interval1['modules'] + $modules_avg_interval2['modules']); + + $parcial1 = ($modules_avg_interval1['avg_interval'] * $modules_avg_interval1['modules']); + $parcial2 = ($modules_avg_interval2['avg_interval'] * $modules_avg_interval2['modules']); + + return (($parcial1 + $parcial2) / $total_modules); } + + /** * Get server rate * @@ -319,13 +367,12 @@ function servers_get_avg_interval($modules_avg_interval1, $modules_avg_interval2 * * @return float number of modules processed by second */ -function servers_get_rate($avg_interval, $num_modules) { - - return $avg_interval > 0 ? - ($num_modules / $avg_interval) : - 0; +function servers_get_rate($avg_interval, $num_modules) +{ + return $avg_interval > 0 ? ($num_modules / $avg_interval) : 0; } + /** * This function will get all the server information in an array or a specific server * @@ -333,300 +380,321 @@ function servers_get_rate($avg_interval, $num_modules) { * * @return mixed False in case the server doesn't exist or an array with info. */ -function servers_get_info ($id_server = -1) { - global $config; - - if (is_array ($id_server)) { - $select_id = " WHERE id_server IN (".implode (",", $id_server).")"; - } - elseif ($id_server > 0) { - $select_id = " WHERE id_server IN (".(int) $id_server.")"; - } - else { - $select_id = ""; - } - - $sql = " +function servers_get_info($id_server=-1) +{ + global $config; + + if (is_array($id_server)) { + $select_id = ' WHERE id_server IN ('.implode(',', $id_server).')'; + } else if ($id_server > 0) { + $select_id = ' WHERE id_server IN ('.(int) $id_server.')'; + } else { + $select_id = ''; + } + + $sql = ' SELECT * - FROM tserver " . $select_id . " - ORDER BY server_type"; - $result = db_get_all_rows_sql ($sql); - $time = get_system_time (); - - if (empty ($result)) { - return false; - } - - $return = array (); - foreach ($result as $server) { - switch ($server['server_type']) { - case SERVER_TYPE_DATA: - $server["img"] = html_print_image ("images/data.png", true, array ("title" => __('Data server'))); - $server["type"] = "data"; - $id_modulo = 1; - break; - case SERVER_TYPE_NETWORK: - $server["img"] = html_print_image ("images/network.png", true, array ("title" => __('Network server'))); - $server["type"] = "network"; - $id_modulo = 2; - break; - case SERVER_TYPE_SNMP: - $server["img"] = html_print_image ("images/snmp.png", true, array ("title" => __('SNMP Trap server'))); - $server["type"] = "snmp"; - $id_modulo = 0; - break; - case SERVER_TYPE_RECON: - $server["img"] = html_print_image ("images/recon.png", true, array ("title" => __('Recon server'))); - $server["type"] = "recon"; - $id_modulo = 0; - break; - case SERVER_TYPE_PLUGIN: - $server["img"] = html_print_image ("images/plugin.png", true, array ("title" => __('Plugin server'))); - $server["type"] = "plugin"; - $id_modulo = 4; - break; - case SERVER_TYPE_PREDICTION: - $server["img"] = html_print_image ("images/chart_bar.png", true, array ("title" => __('Prediction server'))); - $server["type"] = "prediction"; - $id_modulo = 5; - break; - case SERVER_TYPE_WMI: - $server["img"] = html_print_image ("images/wmi.png", true, array ("title" => __('WMI server'))); - $server["type"] = "wmi"; - $id_modulo = 6; - break; - case SERVER_TYPE_EXPORT: - $server["img"] = html_print_image ("images/server_export.png", true, array ("title" => __('Export server'))); - $server["type"] = "export"; - $id_modulo = 0; - break; - case SERVER_TYPE_INVENTORY: - $server["img"] = html_print_image ("images/page_white_text.png", true, array ("title" => __('Inventory server'))); - $server["type"] = "inventory"; - $id_modulo = 0; - break; - case SERVER_TYPE_WEB: - $server["img"] = html_print_image ("images/world.png", true, array ("title" => __('Web server'))); - $server["type"] = "web"; - $id_modulo = 0; - break; - case SERVER_TYPE_EVENT: - $server["img"] = html_print_image ("images/lightning_go.png", true, array ("title" => __('Event server'))); - $server["type"] = "event"; - $id_modulo = 2; - break; - case SERVER_TYPE_ENTERPRISE_ICMP: - $server["img"] = html_print_image ("images/network.png", true, array ("title" => __('Enterprise ICMP server'))); - $server["type"] = "enterprise icmp"; - $id_modulo = 2; - break; - case SERVER_TYPE_ENTERPRISE_SNMP: - $server["img"] = html_print_image ("images/network.png", true, array ("title" => __('Enterprise SNMP server'))); - $server["type"] = "enterprise snmp"; - $id_modulo = 2; - break; - case SERVER_TYPE_ENTERPRISE_SATELLITE: - $server["img"] = html_print_image ("images/satellite.png", true, array ("title" => __('Enterprise Satellite server'))); - $server["type"] = "enterprise satellite"; - $id_modulo = 0; - break; - case SERVER_TYPE_ENTERPRISE_TRANSACTIONAL: - $server["img"] = html_print_image ("images/transactional_map.png", true, array ("title" => __('Enterprise Transactional server'))); - $server["type"] = "enterprise transactional"; - $id_modulo = 0; - break; - case SERVER_TYPE_MAINFRAME: - $server["img"] = html_print_image ("images/mainframe.png", true, array ("title" => __('Mainframe server'))); - $server["type"] = "mainframe"; - $id_modulo = 0; - break; - case SERVER_TYPE_SYNC: - $server["img"] = html_print_image ("images/sync.png", true, array ("title" => __('Sync server'))); - $server["type"] = "sync"; - $id_modulo = 0; - break; - case SERVER_TYPE_WUX: - $server["img"] = html_print_image ("images/icono-wux.png", true, array ("title" => __('Wux server'))); - $server["type"] = "wux"; - $id_modulo = 0; - break; - case SERVER_TYPE_SYSLOG: - $server["img"] = html_print_image ("images/syslog.png", true, array ("title" => __('Syslog server'))); - $server["type"] = "syslog"; - $id_modulo = 0; - break; - case SERVER_TYPE_AUTOPROVISION: - $server["img"] = html_print_image ("images/autoprovision.png", true, array ("title" => __('Autoprovision server'))); - $server["type"] = "autoprovision"; - $id_modulo = 0; - break; - case SERVER_TYPE_MIGRATION: - $server["img"] = html_print_image ("images/migration.png", true, array ("title" => __('Migration server'))); - $server["type"] = "migration"; - $id_modulo = 0; - break; - default: - $server["img"] = ''; - $server["type"] = "unknown"; - $id_modulo = 0; - break; - } - - if ($config["realtimestats"] == 0) { - // --------------------------------------------------------------- - // Take data from database if not realtime stats - // --------------------------------------------------------------- - - $server["lag"] = db_get_sql ("SELECT lag_time FROM tserver WHERE id_server = ".$server["id_server"]); - $server["module_lag"] = db_get_sql ("SELECT lag_modules FROM tserver WHERE id_server = ".$server["id_server"]); - $server["modules"] = db_get_sql ("SELECT my_modules FROM tserver WHERE id_server = ".$server["id_server"]); - $server["modules_total"] = db_get_sql ("SELECT total_modules_running FROM tserver WHERE id_server = ".$server["id_server"]); - - } - else { - - // --------------------------------------------------------------- - // Take data in realtime - // --------------------------------------------------------------- - - - - $server["module_lag"] = 0; - $server["lag"] = 0; - - // Inventory server - if ($server["server_type"] == SERVER_TYPE_INVENTORY) { - - // Get modules exported by this server - $server["modules"] = db_get_sql ("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente AND tagente.server_name = '" . $server["name"] . "'"); - - // Get total exported modules - $server["modules_total"] = db_get_sql ("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente"); - - $interval_esc = db_escape_key_identifier ("interval"); - - // Get the module lag - $server["module_lag"] = db_get_sql ("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) AS module_lag + FROM tserver '.$select_id.' + ORDER BY server_type'; + $result = db_get_all_rows_sql($sql); + $time = get_system_time(); + + if (empty($result)) { + return false; + } + + $return = []; + foreach ($result as $server) { + switch ($server['server_type']) { + case SERVER_TYPE_DATA: + $server['img'] = html_print_image('images/data.png', true, ['title' => __('Data server')]); + $server['type'] = 'data'; + $id_modulo = 1; + break; + + case SERVER_TYPE_NETWORK: + $server['img'] = html_print_image('images/network.png', true, ['title' => __('Network server')]); + $server['type'] = 'network'; + $id_modulo = 2; + break; + + case SERVER_TYPE_SNMP: + $server['img'] = html_print_image('images/snmp.png', true, ['title' => __('SNMP Trap server')]); + $server['type'] = 'snmp'; + $id_modulo = 0; + break; + + case SERVER_TYPE_RECON: + $server['img'] = html_print_image('images/recon.png', true, ['title' => __('Recon server')]); + $server['type'] = 'recon'; + $id_modulo = 0; + break; + + case SERVER_TYPE_PLUGIN: + $server['img'] = html_print_image('images/plugin.png', true, ['title' => __('Plugin server')]); + $server['type'] = 'plugin'; + $id_modulo = 4; + break; + + case SERVER_TYPE_PREDICTION: + $server['img'] = html_print_image('images/chart_bar.png', true, ['title' => __('Prediction server')]); + $server['type'] = 'prediction'; + $id_modulo = 5; + break; + + case SERVER_TYPE_WMI: + $server['img'] = html_print_image('images/wmi.png', true, ['title' => __('WMI server')]); + $server['type'] = 'wmi'; + $id_modulo = 6; + break; + + case SERVER_TYPE_EXPORT: + $server['img'] = html_print_image('images/server_export.png', true, ['title' => __('Export server')]); + $server['type'] = 'export'; + $id_modulo = 0; + break; + + case SERVER_TYPE_INVENTORY: + $server['img'] = html_print_image('images/page_white_text.png', true, ['title' => __('Inventory server')]); + $server['type'] = 'inventory'; + $id_modulo = 0; + break; + + case SERVER_TYPE_WEB: + $server['img'] = html_print_image('images/world.png', true, ['title' => __('Web server')]); + $server['type'] = 'web'; + $id_modulo = 0; + break; + + case SERVER_TYPE_EVENT: + $server['img'] = html_print_image('images/lightning_go.png', true, ['title' => __('Event server')]); + $server['type'] = 'event'; + $id_modulo = 2; + break; + + case SERVER_TYPE_ENTERPRISE_ICMP: + $server['img'] = html_print_image('images/network.png', true, ['title' => __('Enterprise ICMP server')]); + $server['type'] = 'enterprise icmp'; + $id_modulo = 2; + break; + + case SERVER_TYPE_ENTERPRISE_SNMP: + $server['img'] = html_print_image('images/network.png', true, ['title' => __('Enterprise SNMP server')]); + $server['type'] = 'enterprise snmp'; + $id_modulo = 2; + break; + + case SERVER_TYPE_ENTERPRISE_SATELLITE: + $server['img'] = html_print_image('images/satellite.png', true, ['title' => __('Enterprise Satellite server')]); + $server['type'] = 'enterprise satellite'; + $id_modulo = 0; + break; + + case SERVER_TYPE_ENTERPRISE_TRANSACTIONAL: + $server['img'] = html_print_image('images/transactional_map.png', true, ['title' => __('Enterprise Transactional server')]); + $server['type'] = 'enterprise transactional'; + $id_modulo = 0; + break; + + case SERVER_TYPE_MAINFRAME: + $server['img'] = html_print_image('images/mainframe.png', true, ['title' => __('Mainframe server')]); + $server['type'] = 'mainframe'; + $id_modulo = 0; + break; + + case SERVER_TYPE_SYNC: + $server['img'] = html_print_image('images/sync.png', true, ['title' => __('Sync server')]); + $server['type'] = 'sync'; + $id_modulo = 0; + break; + + case SERVER_TYPE_WUX: + $server['img'] = html_print_image('images/icono-wux.png', true, ['title' => __('Wux server')]); + $server['type'] = 'wux'; + $id_modulo = 0; + break; + + case SERVER_TYPE_SYSLOG: + $server['img'] = html_print_image('images/syslog.png', true, ['title' => __('Syslog server')]); + $server['type'] = 'syslog'; + $id_modulo = 0; + break; + + case SERVER_TYPE_AUTOPROVISION: + $server['img'] = html_print_image('images/autoprovision.png', true, ['title' => __('Autoprovision server')]); + $server['type'] = 'autoprovision'; + $id_modulo = 0; + break; + + case SERVER_TYPE_MIGRATION: + $server['img'] = html_print_image('images/migration.png', true, ['title' => __('Migration server')]); + $server['type'] = 'migration'; + $id_modulo = 0; + break; + + default: + $server['img'] = ''; + $server['type'] = 'unknown'; + $id_modulo = 0; + break; + } + + if ($config['realtimestats'] == 0) { + // --------------------------------------------------------------- + // Take data from database if not realtime stats + // --------------------------------------------------------------- + $server['lag'] = db_get_sql('SELECT lag_time FROM tserver WHERE id_server = '.$server['id_server']); + $server['module_lag'] = db_get_sql('SELECT lag_modules FROM tserver WHERE id_server = '.$server['id_server']); + $server['modules'] = db_get_sql('SELECT my_modules FROM tserver WHERE id_server = '.$server['id_server']); + $server['modules_total'] = db_get_sql('SELECT total_modules_running FROM tserver WHERE id_server = '.$server['id_server']); + } else { + // --------------------------------------------------------------- + // Take data in realtime + // --------------------------------------------------------------- + $server['module_lag'] = 0; + $server['lag'] = 0; + + // Inventory server + if ($server['server_type'] == SERVER_TYPE_INVENTORY) { + // Get modules exported by this server + $server['modules'] = db_get_sql("SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente AND tagente.server_name = '".$server['name']."'"); + + // Get total exported modules + $server['modules_total'] = db_get_sql('SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) FROM tagente, tagent_module_inventory WHERE tagente.disabled=0 AND tagent_module_inventory.id_agente = tagente.id_agente'); + + $interval_esc = db_escape_key_identifier('interval'); + + // Get the module lag + $server['module_lag'] = db_get_sql( + 'SELECT COUNT(tagent_module_inventory.id_agent_module_inventory) AS module_lag FROM tagente, tagent_module_inventory WHERE utimestamp > 0 AND tagent_module_inventory.id_agente = tagente.id_agente - AND tagent_module_inventory." . $interval_esc . " > 0 - AND tagente.server_name = '" . $server["name"] . "' - AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory." . $interval_esc . " * 10) - AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory." . $interval_esc); - - // Get the lag - $server["lag"] = db_get_sql ("SELECT AVG(UNIX_TIMESTAMP() - utimestamp - tagent_module_inventory." . $interval_esc . ") + AND tagent_module_inventory.'.$interval_esc." > 0 + AND tagente.server_name = '".$server['name']."' + AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory.".$interval_esc.' * 10) + AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory.'.$interval_esc + ); + + // Get the lag + $server['lag'] = db_get_sql( + 'SELECT AVG(UNIX_TIMESTAMP() - utimestamp - tagent_module_inventory.'.$interval_esc.') FROM tagente, tagent_module_inventory WHERE utimestamp > 0 AND tagent_module_inventory.id_agente = tagente.id_agente - AND tagent_module_inventory." . $interval_esc . " > 0 - AND tagente.server_name = '" . $server["name"] . "' - AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory." . $interval_esc . " * 10) - AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory." . $interval_esc); - // Export server - } - else if ($server["server_type"] == SERVER_TYPE_EXPORT) { - - // Get modules exported by this server - $server["modules"] = db_get_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo, tserver_export WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export = tserver_export.id AND tserver_export.id_export_server = " . $server["id_server"]); - - // Get total exported modules - $server["modules_total"] = db_get_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export != 0"); - - $server["lag"] = 0; - $server["module_lag"] = 0; - - } - // Recon server - else if ($server["server_type"] == SERVER_TYPE_RECON) { - - $server["name"] = ''.$server["name"].''; - - //Total jobs running on this recon server - $server["modules"] = db_get_sql ("SELECT COUNT(id_rt) + AND tagent_module_inventory.'.$interval_esc." > 0 + AND tagente.server_name = '".$server['name']."' + AND (UNIX_TIMESTAMP() - utimestamp) < (tagent_module_inventory.".$interval_esc.' * 10) + AND (UNIX_TIMESTAMP() - utimestamp) > tagent_module_inventory.'.$interval_esc + ); + // Export server + } else if ($server['server_type'] == SERVER_TYPE_EXPORT) { + // Get modules exported by this server + $server['modules'] = db_get_sql('SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo, tserver_export WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export = tserver_export.id AND tserver_export.id_export_server = '.$server['id_server']); + + // Get total exported modules + $server['modules_total'] = db_get_sql('SELECT COUNT(tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.id_export != 0'); + + $server['lag'] = 0; + $server['module_lag'] = 0; + } + // Recon server + else if ($server['server_type'] == SERVER_TYPE_RECON) { + $server['name'] = ''.$server['name'].''; + + // Total jobs running on this recon server + $server['modules'] = db_get_sql( + 'SELECT COUNT(id_rt) FROM trecon_task - WHERE id_recon_server = ".$server["id_server"]); - - //Total recon jobs (all servers) - $server["modules_total"] = db_get_sql ("SELECT COUNT(status) FROM trecon_task"); - - //Lag (take average active time of all active tasks) - $server["module_lag"] = 0; - - switch ($config["dbtype"]) { - case "mysql": - $server["lag"] = db_get_sql ("SELECT UNIX_TIMESTAMP() - utimestamp from trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - - $server["module_lag"] = db_get_sql ("SELECT COUNT(id_rt) FROM trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - break; - case "postgresql": - $server["lag"] = db_get_sql ("SELECT ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp from trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - - $server["module_lag"] = db_get_sql ("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - break; - case "oracle": - $server["lag"] = db_get_sql ("SELECT ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp from trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - - $server["module_lag"] = db_get_sql ("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) > (utimestamp + interval_sweep) AND id_recon_server = ".$server["id_server"]); - break; - } - } - else { - - // --------------------------------------------------------------- - // Data, Plugin, WMI, Network and Others - - $server["modules"] = db_get_sql ("SELECT count(tagente_estado.id_agente_modulo) FROM tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = ".$server["id_server"]); - - $server["modules_total"] = db_get_sql ("SELECT count(tagente_estado.id_agente_modulo) FROM tserver, tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = tserver.id_server AND tserver.server_type = ".$server["server_type"]); - - // Remote servers LAG Calculation (server_type != 0) - if ($server["server_type"] != 0) { - switch ($config["dbtype"]) { - case "mysql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + WHERE id_recon_server = '.$server['id_server'] + ); + + // Total recon jobs (all servers) + $server['modules_total'] = db_get_sql('SELECT COUNT(status) FROM trecon_task'); + + // Lag (take average active time of all active tasks) + $server['module_lag'] = 0; + + switch ($config['dbtype']) { + case 'mysql': + $server['lag'] = db_get_sql('SELECT UNIX_TIMESTAMP() - utimestamp from trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + + $server['module_lag'] = db_get_sql('SELECT COUNT(id_rt) FROM trecon_task WHERE UNIX_TIMESTAMP() > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + break; + + case 'postgresql': + $server['lag'] = db_get_sql("SELECT ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp from trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server['id_server']); + + $server['module_lag'] = db_get_sql("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil(date_part('epoch', CURRENT_TIMESTAMP)) > (utimestamp + interval_sweep) AND id_recon_server = ".$server['id_server']); + break; + + case 'oracle': + $server['lag'] = db_get_sql("SELECT ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp from trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + + $server['module_lag'] = db_get_sql("SELECT COUNT(id_rt) FROM trecon_task WHERE ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) > (utimestamp + interval_sweep) AND id_recon_server = '.$server['id_server']); + break; + } + } else { + // --------------------------------------------------------------- + // Data, Plugin, WMI, Network and Others + $server['modules'] = db_get_sql('SELECT count(tagente_estado.id_agente_modulo) FROM tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = '.$server['id_server']); + + $server['modules_total'] = db_get_sql('SELECT count(tagente_estado.id_agente_modulo) FROM tserver, tagente_estado, tagente_modulo, tagente WHERE tagente.disabled=0 AND tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.running_by = tserver.id_server AND tserver.server_type = '.$server['server_type']); + + // Remote servers LAG Calculation (server_type != 0) + if ($server['server_type'] != 0) { + switch ($config['dbtype']) { + case 'mysql': + $result = db_get_row_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND running_by = ".$server["id_server"]." + AND running_by = '.$server['id_server'].' AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) - AND (UNIX_TIMESTAMP() - utimestamp) > current_interval"); - break; - case "postgresql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND (UNIX_TIMESTAMP() - utimestamp) > current_interval' + ); + break; + + case 'postgresql': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND running_by = ".$server["id_server"]." + AND running_by = ".$server['id_server']." AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) < ( current_interval * 10) - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > current_interval"); - break; - case "oracle": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > current_interval" + ); + break; + + case 'oracle': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND running_by = ".$server["id_server"]." - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp) < ( current_interval * 10) - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) - utimestamp) * (" . SECONDS_1DAY . ")) > current_interval"); - break; - } - } - else { - // Local/Dataserver server LAG calculation: - switch ($config["dbtype"]) { - case "mysql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND running_by = '.$server['id_server']." + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp) < ( current_interval * 10) + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) - utimestamp) * (".SECONDS_1DAY.')) > current_interval' + ); + break; + } + } else { + // Local/Dataserver server LAG calculation: + switch ($config['dbtype']) { + case 'mysql': + $result = db_get_row_sql( + 'SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(UNIX_TIMESTAMP() - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente @@ -635,11 +703,14 @@ function servers_get_info ($id_server = -1) { AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 AND (UNIX_TIMESTAMP() - utimestamp) < ( current_interval * 10) - AND running_by = ".$server["id_server"]." - AND (UNIX_TIMESTAMP() - utimestamp) > (current_interval * 1.1)"); - break; - case "postgresql": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND running_by = '.$server['id_server'].' + AND (UNIX_TIMESTAMP() - utimestamp) > (current_interval * 1.1)' + ); + break; + + case 'postgresql': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente @@ -648,11 +719,14 @@ function servers_get_info ($id_server = -1) { AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) < ( current_interval * 10) - AND running_by = ".$server["id_server"]." - AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > (current_interval * 1.1)"); - break; - case "oracle": - $result = db_get_row_sql ("SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente + AND running_by = ".$server['id_server']." + AND (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - utimestamp) > (current_interval * 1.1)" + ); + break; + + case 'oracle': + $result = db_get_row_sql( + "SELECT COUNT(tagente_modulo.id_agente_modulo) AS module_lag, AVG(ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.")) - utimestamp - current_interval) AS lag FROM tagente_estado, tagente_modulo, tagente WHERE utimestamp > 0 AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente @@ -660,52 +734,51 @@ function servers_get_info ($id_server = -1) { AND tagente_modulo.id_tipo_modulo < 5 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND current_interval > 0 - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp) < ( current_interval * 10) - AND running_by = ".$server["id_server"]." - AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - utimestamp) > (current_interval * 1.1)"); - break; - } - } - - // Lag over current_interval * 2 is not lag, it's a timed out module - - if (!empty ($result["lag"])) { - $server["lag"] = $result["lag"]; - } - - if (!empty ($result["module_lag"])) { - $server["module_lag"] = $result["module_lag"]; - } - } - } // Take data for realtime mode - - if (isset($server["module_lag"])) - $server["lag_txt"] = - ($server["lag"] == 0 ? - '-' - : - human_time_description_raw($server["lag"])) . " / " . $server["module_lag"]; - else - $server["lag_txt"] = ""; - - if ($server["modules_total"] > 0) { - $server["load"] = round ($server["modules"] / $server["modules_total"] * 100); - } - else { - $server["load"] = 0; - } - - //Push the raw data on the return stack - $return[$server["id_server"]] = $server; - } // Main foreach - - return $return; + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp) < ( current_interval * 10) + AND running_by = '.$server['id_server']." + AND (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - utimestamp) > (current_interval * 1.1)' + ); + break; + } + } + + // Lag over current_interval * 2 is not lag, it's a timed out module + if (!empty($result['lag'])) { + $server['lag'] = $result['lag']; + } + + if (!empty($result['module_lag'])) { + $server['module_lag'] = $result['module_lag']; + } + } + } //end if + + if (isset($server['module_lag'])) { + $server['lag_txt'] = ($server['lag'] == 0 ? '-' : human_time_description_raw($server['lag'])).' / '.$server['module_lag']; + } else { + $server['lag_txt'] = ''; + } + + if ($server['modules_total'] > 0) { + $server['load'] = round(($server['modules'] / $server['modules_total'] * 100)); + } else { + $server['load'] = 0; + } + + // Push the raw data on the return stack + $return[$server['id_server']] = $server; + } //end foreach + + return $return; } -function servers_get_servers_type($type) { - return db_get_all_rows_filter('tserver', array('server_type' => $type)); + +function servers_get_servers_type($type) +{ + return db_get_all_rows_filter('tserver', ['server_type' => $type]); } + /** * Get the server name. * @@ -713,41 +786,46 @@ function servers_get_servers_type($type) { * * @return string Name of the given server */ -function servers_get_name ($id_server) { - return (string) db_get_value ('name', 'tserver', 'id_server', (int) $id_server); +function servers_get_name($id_server) +{ + return (string) db_get_value('name', 'tserver', 'id_server', (int) $id_server); } + /** * Get the presence of .conf and .md5 into remote_config dir - * + * * @param string Agent name - * + * * @return true if files exist and are writable */ -function servers_check_remote_config ($server_name) { - global $config; - - $server_md5 = md5 ($server_name, false); - - $filenames = array(); - $filenames['md5'] = io_safe_output($config["remote_config"]) - . "/md5/" . $server_md5 . ".srv.md5"; - $filenames['conf'] = io_safe_output($config["remote_config"]) - . "/conf/" . $server_md5 . ".srv.conf"; - - if (! isset ($filenames['conf'])) - return false; - if (! isset ($filenames['md5'])) - return false; - - return (file_exists ($filenames['conf']) - && is_writable ($filenames['conf']) - && file_exists ($filenames['md5']) - && is_writable ($filenames['md5'])); +function servers_check_remote_config($server_name) +{ + global $config; + + $server_md5 = md5($server_name, false); + + $filenames = []; + $filenames['md5'] = io_safe_output($config['remote_config']).'/md5/'.$server_md5.'.srv.md5'; + $filenames['conf'] = io_safe_output($config['remote_config']).'/conf/'.$server_md5.'.srv.conf'; + + if (! isset($filenames['conf'])) { + return false; + } + + if (! isset($filenames['md5'])) { + return false; + } + + return (file_exists($filenames['conf']) + && is_writable($filenames['conf']) + && file_exists($filenames['md5']) + && is_writable($filenames['md5'])); } + /** * Return a string containing image tag for a given target id (server) * TODO: Make this print_servertype_icon and move to functions_ui.php. Make XHTML compatible. Make string translatable @@ -758,72 +836,87 @@ function servers_check_remote_config ($server_name) { * * @return string Fully formatted IMG HTML tag with icon */ -function servers_show_type ($id) { - global $config; - - switch ($id) { - case 1: - return html_print_image("images/database.png", true, array("title" => get_product_name() . " Data server")); - break; - case 2: - return html_print_image("images/network.png", true, array("title" => get_product_name() . " Network server")); - break; - case 4: - return html_print_image("images/plugin.png", true, array("title" => get_product_name() . " Plugin server")); - break; - case 5: - return html_print_image("images/chart_bar.png", true, array("title" => get_product_name() . " Prediction server")); - break; - case 6: - return html_print_image("images/wmi.png", true, array("title" => get_product_name() . " WMI server")); - break; - case 7: - return html_print_image("images/server_web.png", true, array("title" => get_product_name() . " WEB server")); - break; - case 8: - return html_print_image("images/module-wux.png", true, array("title" => get_product_name() . " WUX server")); - break; - default: - return "--"; - break; - } +function servers_show_type($id) +{ + global $config; + + switch ($id) { + case 1: + return html_print_image('images/database.png', true, ['title' => get_product_name().' Data server']); + + break; + case 2: + return html_print_image('images/network.png', true, ['title' => get_product_name().' Network server']); + + break; + case 4: + return html_print_image('images/plugin.png', true, ['title' => get_product_name().' Plugin server']); + + break; + case 5: + return html_print_image('images/chart_bar.png', true, ['title' => get_product_name().' Prediction server']); + + break; + case 6: + return html_print_image('images/wmi.png', true, ['title' => get_product_name().' WMI server']); + + break; + case 7: + return html_print_image('images/server_web.png', true, ['title' => get_product_name().' WEB server']); + + break; + case 8: + return html_print_image('images/module-wux.png', true, ['title' => get_product_name().' WUX server']); + + break; + default: + return '--'; + break; + } } + /** * Get the numbers of servers up. * * This check assumes that server_keepalive should be at least 15 minutes. * - * @return int The number of servers alive. + * @return integer The number of servers alive. */ -function servers_check_status () { - global $config; - - switch ($config["dbtype"]) { - case "mysql": - $sql = "SELECT COUNT(id_server) +function servers_check_status() +{ + global $config; + + switch ($config['dbtype']) { + case 'mysql': + $sql = 'SELECT COUNT(id_server) FROM tserver WHERE status = 1 - AND keepalive > NOW() - INTERVAL server_keepalive*2 SECOND"; - break; - case "postgresql": - $sql = "SELECT COUNT(id_server) + AND keepalive > NOW() - INTERVAL server_keepalive*2 SECOND'; + break; + + case 'postgresql': + $sql = "SELECT COUNT(id_server) FROM tserver WHERE status = 1 AND keepalive > NOW() - INTERVAL 'server_keepalive*2 SECOND'"; - break; - case "oracle": - $sql = "SELECT COUNT(id_server) + break; + + case 'oracle': + $sql = "SELECT COUNT(id_server) FROM tserver WHERE status = 1 AND keepalive > systimestamp - INTERVAL 'server_keepalive*2' SECOND"; - break; - } - $status = (int) db_get_sql ($sql); //Cast as int will assure a number value - // This function should just ack of server down, not set it down. - return $status; + break; + } + + $status = (int) db_get_sql($sql); + // Cast as int will assure a number value + // This function should just ack of server down, not set it down. + return $status; } + /** * @deprecated use servers_get_info instead * Get statistical information for a given server @@ -832,8 +925,66 @@ function servers_check_status () { * * @return array Server info array */ -function servers_get_status ($id_server) { - $serverinfo = servers_get_info ($id_server); - return $serverinfo[$id_server]; +function servers_get_status($id_server) +{ + $serverinfo = servers_get_info($id_server); + return $serverinfo[$id_server]; +} + + +/** + * Return server name based on identifier. + * + * @param integer $server Server identifier. + * + * @return string Server name + */ +function servers_get_server_string_name(int $server) +{ + switch ($server) { + case SERVER_TYPE_DATA: + return __('Data server'); + + case SERVER_TYPE_NETWORK: + return __('Network server'); + + case SERVER_TYPE_SNMP: + return __('SNMP server'); + + case SERVER_TYPE_ENTERPRISE_ICMP: + return __('Enterprise ICMP server'); + + case SERVER_TYPE_ENTERPRISE_SNMP: + return __('Enterprise SNMP server'); + + case SERVER_TYPE_PLUGIN: + return __('Plugin server'); + + case SERVER_TYPE_PREDICTION: + return __('Prediction Server'); + + case SERVER_TYPE_WMI: + return __('WMI server'); + + case SERVER_TYPE_WEB: + return __('Web server'); + + case SERVER_TYPE_EXPORT: + return __('Export server'); + + case SERVER_TYPE_INVENTORY: + return __('Inventory server'); + + case SERVER_TYPE_EVENT: + return __('Event server'); + + case SERVER_TYPE_RECON: + return __('Discovery server'); + + case SERVER_TYPE_SYSLOG: + return __('Syslog server'); + + default: + return __('N/A'); + } } -?> From 8d17c9e0d0d02a4ca8b543f1e38647f1772be009 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 4 Feb 2019 19:32:54 +0100 Subject: [PATCH 038/249] minor plugintools fix Former-commit-id: d7d43777b952b483a733c7ac92776f12b5c17e62 --- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pandora_server/lib/PandoraFMS/PluginTools.pm b/pandora_server/lib/PandoraFMS/PluginTools.pm index 6b80d054d7..b4526ab68f 100644 --- a/pandora_server/lib/PandoraFMS/PluginTools.pm +++ b/pandora_server/lib/PandoraFMS/PluginTools.pm @@ -163,6 +163,8 @@ sub csv_to_obj { @hr_headers = map { $_ =~ s/\"//g; trim($_); } @hr_headers; foreach my $line (@lines) { + next if empty($line); + my $i = 0; my %hr = map { $_ =~ s/\"//g; $hr_headers[$i++] => trim($_) } split /,/, $line; From 418d497291f8ee971be4ea0c8516bf1a9e1a74b5 Mon Sep 17 00:00:00 2001 From: daniel Date: Tue, 5 Feb 2019 10:40:24 +0100 Subject: [PATCH 039/249] fixed errors pdf Former-commit-id: f7ad69f6b5e0910e5f31464ddfe94593529ef6a7 --- .../include/functions_reporting_html.php | 317 +++++++++++------- pandora_console/include/styles/pandoraPDF.css | 47 +-- 2 files changed, 226 insertions(+), 138 deletions(-) diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index 84396cfb91..d79afa08e8 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -1,25 +1,32 @@ '.__('Description').': '.io_safe_output($report['description']).' - '.'
'; + '.'
'; echo $html; } @@ -153,8 +160,6 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) $label = ''; } - // $aux = explode("-",$item['subtitle']); - // $item['subtitle'] = db_get_value ("alias","tagente","nombre",$item['agent_name']) .' -'. $aux[1]; reporting_html_header( $table, $mini, @@ -177,6 +182,7 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) switch ($item['type']) { case 'availability': + default: reporting_html_availability($table, $item); break; @@ -380,7 +386,11 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) break; case 'module_histogram_graph': - reporting_enterprise_html_module_histogram_graph($table, $item, $mini); + reporting_enterprise_html_module_histogram_graph( + $table, + $item, + $mini + ); break; } @@ -399,11 +409,7 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) function reporting_html_SLA($table, $item, $mini, $pdf=0) { - if ($table === false) { - $table = new stdClass(); - $table->width = '99%'; - $table->class = 'table_beauty'; - } + $return_pdf = ''; $style = db_get_value( 'style', @@ -411,6 +417,7 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) 'id_rc', $item['id_rc'] ); + $style = json_decode(io_safe_output($style), true); $same_agent_in_resume = ''; @@ -447,7 +454,7 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) if (isset($item['data'])) { $table1 = new stdClass(); $table1->width = '99%'; - + $table1->class = 'content_table databox'; $table1->align = []; $table1->align[0] = 'left'; $table1->align[1] = 'left'; @@ -475,6 +482,7 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) // Second_table for time globals. $table2 = new stdClass(); $table2->width = '99%'; + $table2->class = 'content_table'; $table2->align = []; $table2->align[0] = 'left'; @@ -506,6 +514,7 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) // Third_table for time globals. $table3 = new stdClass(); $table3->width = '99%'; + $table3->class = 'content_table'; $table3->align = []; $table3->align[0] = 'left'; @@ -562,12 +571,12 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) } else if (reporting_sla_is_ignored_from_array($sla)) { $row[] = ''.__('N/A').''; $row[] = ''.__('No data').''; - // Normal calculation + // Normal calculation. } else if ($sla['sla_status']) { - $row[] = ''.sla_truncate($sla['sla_value'], $config['graph_precision']).'%'.''; + $row[] = ''.sla_truncate($sla['sla_value'], $config['graph_precision']).'%'; $row[] = ''.__('OK').''; } else { - $row[] = ''.sla_truncate($sla['sla_value'], $config['graph_precision']).'%'.''; + $row[] = ''.sla_truncate($sla['sla_value'], $config['graph_precision']).'%'; $row[] = ''.__('Fail').''; } @@ -642,92 +651,131 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) } } - $table->colspan['sla']['cell'] = 2; - $table->data['sla']['cell'] = html_print_table( - $table1, - true - ); - $table->colspan['time_global']['cell'] = 2; - $table->data['time_global']['cell'] = html_print_table( - $table2, - true - ); - $table->colspan['checks_global']['cell'] = 2; - $table->data['checks_global']['cell'] = html_print_table( - $table3, - true - ); + if ($pdf === 0) { + $table->colspan['sla']['cell'] = 2; + $table->data['sla']['cell'] = html_print_table( + $table1, + true + ); + $table->colspan['time_global']['cell'] = 2; + $table->data['time_global']['cell'] = html_print_table( + $table2, + true + ); + $table->colspan['checks_global']['cell'] = 2; + $table->data['checks_global']['cell'] = html_print_table( + $table3, + true + ); + } else { + $return_pdf .= ''; + $return_pdf .= html_print_table( + $table1, + true + ); + $return_pdf .= ''; + + $return_pdf .= ''; + $return_pdf .= html_print_table( + $table2, + true + ); + $return_pdf .= ''; + + $return_pdf .= ''; + $return_pdf .= html_print_table( + $table3, + true + ); + $return_pdf .= ''; + } } else { $table->colspan['error']['cell'] = 3; $table->data['error']['cell'] = __('There are no Agent/Modules defined'); } if (!empty($item['charts'])) { - $table1 = new stdClass(); - $table1->width = '99%'; - $table1->size = []; - $table1->size[0] = '10%'; + /* + $table1 = new stdClass(); + $table1->width = '99%'; + $table1->size = []; + $table1->size[0] = '10%'; - $table1->data = []; + $table1->data = []; - foreach ($item['charts'] as $chart) { + foreach ($item['charts'] as $chart) { $table1->data[] = [ $chart['agent'].'
'.$chart['module'], $chart['chart'], ]; - } + } - $table->colspan['charts']['cell'] = 2; - $table->data['charts']['cell'] = html_print_table( - $table1, - true - ); + if ($pdf === 0) { + $table->colspan['charts']['cell'] = 2; + $table->data['charts']['cell'] = html_print_table( + $table1, + true + ); + } else { + $return_pdf .= html_print_table( + $table1, + true + ); + } - // Table_legend_graphs. - $table1 = new stdClass(); - $table1->width = '99%'; - $table1->data = []; - $table1->size = []; - $table1->size[0] = '2%'; - $table1->data[0][0] = ''; - $table1->size[1] = '14%'; - $table1->data[0][1] = ''.__('OK').''; + // Table_legend_graphs. + $table1 = new stdClass(); + $table1->width = '99%'; + $table1->data = []; + $table1->size = []; + $table1->size[0] = '2%'; + $table1->data[0][0] = ''; + $table1->size[1] = '14%'; + $table1->data[0][1] = ''.__('OK').''; - $table1->size[2] = '2%'; - $table1->data[0][2] = ''; - $table1->size[3] = '14%'; - $table1->data[0][3] = ''.__('Critical').''; + $table1->size[2] = '2%'; + $table1->data[0][2] = ''; + $table1->size[3] = '14%'; + $table1->data[0][3] = ''.__('Critical').''; - $table1->size[4] = '2%'; - $table1->data[0][4] = ''; - $table1->size[5] = '14%'; - $table1->data[0][5] = ''.__('Unknow').''; + $table1->size[4] = '2%'; + $table1->data[0][4] = ''; + $table1->size[5] = '14%'; + $table1->data[0][5] = ''.__('Unknow').''; - $table1->size[6] = '2%'; - $table1->data[0][6] = ''; - $table1->size[7] = '14%'; - $table1->data[0][7] = ''.__('Not Init').''; + $table1->size[6] = '2%'; + $table1->data[0][6] = ''; + $table1->size[7] = '14%'; + $table1->data[0][7] = ''.__('Not Init').''; - $table1->size[8] = '2%'; - $table1->data[0][8] = ''; - $table1->size[9] = '14%'; - $table1->data[0][9] = ''.__('Downtimes').''; + $table1->size[8] = '2%'; + $table1->data[0][8] = ''; + $table1->size[9] = '14%'; + $table1->data[0][9] = ''.__('Downtimes').''; - $table1->size[10] = '2%'; - $table1->data[0][10] = ''; - $table1->size[11] = '15%'; - $table1->data[0][11] = ''.__('Ignore time').''; + $table1->size[10] = '2%'; + $table1->data[0][10] = ''; + $table1->size[11] = '15%'; + $table1->data[0][11] = ''.__('Ignore time').''; - $table->colspan['legend']['cell'] = 2; - $table->data['legend']['cell'] = html_print_table( - $table1, - true - ); + if ($pdf === 0) { + $table->colspan['legend']['cell'] = 2; + $table->data['legend']['cell'] = html_print_table( + $table1, + true + ); + } else { + $return_pdf .= html_print_table( + $table1, + true + ); + } + */ } } if ($pdf !== 0) { - return html_print_table($table, true); + return $return_pdf; } } @@ -860,7 +908,7 @@ function reporting_html_event_report_group($table, $item, $pdf=0) $data = []; - // Colored box + // Colored box. switch ($event['estado']) { case 0: $img_st = 'images/star.png'; @@ -1075,9 +1123,10 @@ function reporting_html_event_report_module($table, $item, $pdf=0) $table1->cellclass[$i][1] = $table1->cellclass[$i][3] = $table1->cellclass[$i][4] = get_priority_class($event['criticity']); } - // Colored box + // Colored box. switch ($event['estado']) { case 0: + default: $img_st = 'images/star.png'; $title_st = __('New event'); break; @@ -1233,8 +1282,10 @@ function reporting_html_inventory_changes($table, $item) foreach ($item['data'] as $module_item) { $table1 = null; $table1->width = '99%'; + $table1->cellstyle = []; - $table1->cellstyle[0][0] = $table1->cellstyle[0][1] = 'background: #373737; color: #FFF;'; + $table1->cellstyle[0][0] = 'background: #373737; color: #FFF;'; + $table1->cellstyle[0][1] = 'background: #373737; color: #FFF;'; $table1->data[0][0] = $module_item['agent']; $table1->data[0][1] = $module_item['module']; @@ -1700,9 +1751,10 @@ function reporting_html_event_report_agent($table, $item, $pdf=0) } $data = []; - // Colored box + // Colored box. switch ($event['status']) { case 0: + default: $img_st = 'images/star.png'; $title_st = __('New event'); break; @@ -1738,7 +1790,7 @@ function reporting_html_event_report_agent($table, $item, $pdf=0) false, true ); - // $data[] = $event['event_type']; + $data[] = events_print_type_img($event['type'], true); $data[] = get_priority_name($event['criticity']); @@ -2361,7 +2413,7 @@ function reporting_html_url(&$table, $item, $key) $table->data['data']['cell'] = ' '; - // TODO: make this dynamic and get the height if the iframe to resize this item + // TODO: make this dynamic and get the height if the iframe to resize this item. $table->data['data']['cell'] .= ' diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 24013b92fd..cd8d977053 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -195,16 +195,37 @@ function notifications_get_user_sources_for_select($source_id) { * @return array with the group id in keys and group name in value */ function notifications_get_group_sources_for_select($source_id) { + $groups = notifications_get_group_sources ( + array('id_source' => $source_id), + array('id_group') + ); + return index_array($groups, 'id_group', 'name'); +} + +/** + * Get the group sources + * + * @param array $filter Filter of sql query. + */ +function notifications_get_group_sources ($filter = array(), $fields = array()) { + // Get only the tnotifications_source_group fields in addition to group name. + if (empty($fields)) $fields[] = "tnsg.*"; + $fields = array_map(function($field) { + if (!preg_match("/^tnsg./", $field)) $field = "tnsg.{$field}"; + return $field; + }, $fields); + + // Get groups. $groups = db_get_all_rows_filter( 'tnotification_source_group tnsg LEFT JOIN tgrupo tg ON tnsg.id_group = tg.id_grupo', - array('id_source' => $source_id), - array ('tnsg.id_group', 'IFNULL(tg.nombre, "All") AS name') + $filter, + array_merge ($fields, array('IFNULL(tg.nombre, "All") AS name')) ); + // If fails or no one is selected, return empty array if ($groups === false) return array(); - - return index_array($groups, 'id_group', 'name'); + return $groups; } /** @@ -254,6 +275,36 @@ function notifications_add_group_to_source ($source_id, $groups) { return $res; } +/** + * Get the groups that not own to a source and, for that reason, they can be + * added to the source. + * + * @param int $source_id Source id. + * @return array Indexed by id group all selectable groups. + */ +function notifications_get_group_source_not_configured ($source_id) { + $groups_selected = notifications_get_group_sources_for_select($source_id); + $all_groups = users_get_groups_for_select(false, "AR", false, true, $groups_selected); + return array_diff($all_groups, $groups_selected); +} + +/** + * Get the users that not own to a source and, for that reason, they can be + * added to the source. + * + * @param int $source_id + * @return array Indexed by id user, all selectable users. + */ +function notifications_get_user_source_not_configured ($source_id) { + $users_selected = array_keys(notifications_get_user_sources_for_select($source_id)); + $users = get_users( + 'id_user', + array('!id_user' => $users_selected), + array('id_user') + ); + return index_array($users, 'id_user', 'id_user'); +} + /** * Print the notification ball to see unread messages * @@ -365,9 +416,29 @@ function notifications_print_source_select_box($info_selec, $id, $source_id, $di $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}-{$source_id}[]", 0, false, '', '', true, true, true,'', $disabled); $html_select .= "
"; $html_select .= "
"; - $html_select .= html_print_image('images/input_add.png', true, array('title' => $add_title)); + $html_select .= html_print_image('images/input_add.png', true, array('title' => $add_title, 'onclick' => "add_source_dialog('$id', '$source_id')")); $html_select .= html_print_image('images/input_delete.png', true, array('title' => $delete_title)); $html_select .= "
"; $html_select .= "
"; return $html_select; } + +/** + * Print the select with right and left arrows to select new sources + * (groups or users). + * + * @param array $info_selec Array with source info. + * @param string $users users|groups. + * @param source $source_id Source id. + * @return string HTML with the select code. + */ +function notifications_print_two_ways_select($info_selec, $users, $source_id) { + $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "all-multi-{$users}-{$source_id}[]", 0, false, '', '', true, true, true,''); + $html_select .= "
"; + $html_select .= html_print_image('images/darrowright.png', true, array('title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'add')")); + $html_select .= html_print_image('images/darrowleft.png', true, array('title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'remove')")); + $html_select .= "
"; + $html_select .= html_print_select(true, "selected-multi-{$users}-{$source_id}[]", 0, false, '', '', true, true, true, ''); + + return $html_select; +} diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index aee1b9dc5d..31ca3b865a 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4953,7 +4953,8 @@ div#dialog_messages table th:last-child { margin: 0; } -.global-config-notification-single-selector { +.global-config-notification-single-selector, +.global_config_notifications_dialog_add select { display: flex; width: 100%; padding: 0 10px; @@ -4970,6 +4971,23 @@ div#dialog_messages table th:last-child { justify-content: flex-end; } +.global_config_notifications_dialog_add { + display: flex; + flex-direction: row; + margin: 8px; +} + +.global_config_notifications_two_ways_form_arrows { + display: flex; + flex-flow: column; + justify-content: center; + margin: 0 5px; +} + +.global_config_notifications_two_ways_form_arrows img { + margin: 15px 0; +} + /* --- JQUERY-UI --- */ .ui-button-text-only .ui-button-text { font-family: "nunito", sans-serif; From 68bdbd511c97cd7094c97fdd3a20e72325b0a05b Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 5 Feb 2019 13:46:16 +0100 Subject: [PATCH 042/249] Fixed add consecutive source elements Former-commit-id: 7763da94a48442953879538d42f36673fbdec752 --- pandora_console/godmode/setup/setup_notifications.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 8cb4152366..e5700fedef 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -158,7 +158,7 @@ function notifications_modify_two_ways_element (id, source_id, operation) { var select_end = document.getElementById( end_id + index_sufix ); - for (var i = 0; i < select.options.length; i++) { + for (var i = select.options.length - 1; i >= 0; i--) { if(select.options[i].selected ==true){ select_end.appendChild(select.options[i]); } From b4f3e94b13e6405fd34884544af2770d38abcb7f Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 5 Feb 2019 15:31:08 +0100 Subject: [PATCH 043/249] Clean dialog box on creation Former-commit-id: 824f7a968b2e196d6df98b9f5dbd48f21a7c9859 --- pandora_console/godmode/setup/setup_notifications.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index e5700fedef..373e1a7322 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -117,6 +117,10 @@ function notifications_disable_source(event) { function add_source_dialog(users, source_id) { // Display the dialog var dialog_id = 'global_config_notifications_dialog_add-' + users + '-' + source_id; + // Clean id element. + var previous_dialog = document.getElementById(dialog_id); + if (previous_dialog !== null) previous_dialog.remove(); + // Create or recreate the content. var not_dialog = document.createElement('div'); not_dialog.setAttribute('class', 'global_config_notifications_dialog_add'); not_dialog.setAttribute('id', dialog_id); From 7df3fe2dac62a51520282454b65ceab66ec2ff7a Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 5 Feb 2019 17:40:44 +0100 Subject: [PATCH 044/249] Added functionallity to Add element on notification global config Former-commit-id: b51cf2d5079019a69fd7c4344dfcff2bf38147db --- .../godmode/setup/setup_notifications.php | 68 +++++++++++++++++-- .../include/functions_notifications.php | 32 ++++++++- pandora_console/include/styles/pandora.css | 3 +- 3 files changed, 95 insertions(+), 8 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 373e1a7322..8233b84028 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -28,8 +28,7 @@ if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user return; } -// Actions -// AJAX +// AJAX actions. if (get_parameter('get_selection_two_ways_form', 0)) { $source_id = get_parameter('source_id', ''); $users = get_parameter('users', ''); @@ -45,6 +44,22 @@ if (get_parameter('get_selection_two_ways_form', 0)) { ); return; } +if (get_parameter('add_source_to_database', 0)) { + $source_id = get_parameter('source_id', ''); + $users = get_parameter('users', ''); + $elements = get_parameter('elements', array()); + $id = get_notification_source_id($source_id); + $res = $users === "users" + ? notifications_add_users_to_source($id, $elements) + : notifications_add_group_to_source($id, $elements); + $result = array( + 'result' => $res + ); + echo json_encode($result); + return; +} + +// Form actions. if (get_parameter('update_config', 0)) { $res_global = array_reduce(notifications_get_all_sources(), function($carry, $source){ $id = notifications_desc_to_id($source['description']); @@ -113,23 +128,32 @@ function notifications_disable_source(event) { }); } +// Get index of two ways element dialog. +function notifications_two_ways_element_get_dialog (id, source_id) { + return 'global_config_notifications_dialog_add-' + id + '-' + source_id; +} +// Get index of two ways element form. +function notifications_two_ways_element_get_sufix (id, source_id) { + return 'multi-' + id + '-' + source_id; +} + // Open a dialog with selector of source elements. function add_source_dialog(users, source_id) { // Display the dialog - var dialog_id = 'global_config_notifications_dialog_add-' + users + '-' + source_id; + var dialog_id = notifications_two_ways_element_get_dialog(users, source_id); // Clean id element. var previous_dialog = document.getElementById(dialog_id); if (previous_dialog !== null) previous_dialog.remove(); // Create or recreate the content. var not_dialog = document.createElement('div'); - not_dialog.setAttribute('class', 'global_config_notifications_dialog_add'); + not_dialog.setAttribute('class', 'global_config_notifications_dialog_add_wrapper'); not_dialog.setAttribute('id', dialog_id); document.body.appendChild(not_dialog); $("#" + dialog_id).dialog({ resizable: false, draggable: true, modal: true, - dialogClass: "global_config_notifications_dialog_add_wrapper", + dialogClass: "global_config_notifications_dialog_add_full", overlay: { opacity: 0.5, background: "black" @@ -153,7 +177,7 @@ function add_source_dialog(users, source_id) { // Move from selected and not selected source elements. function notifications_modify_two_ways_element (id, source_id, operation) { - var index_sufix = 'multi-' + id + '-' + source_id; + var index_sufix = notifications_two_ways_element_get_sufix (id, source_id); var start_id = operation === 'add' ? 'all-' : 'selected-'; var end_id = operation !== 'add' ? 'all-' : 'selected-'; var select = document.getElementById( @@ -168,4 +192,36 @@ function notifications_modify_two_ways_element (id, source_id, operation) { } } } + +// Add elements to database and close dialog +function notifications_add_source_element_to_database(id, source_id) { + var index = 'selected-' + notifications_two_ways_element_get_sufix (id, source_id); + var select = document.getElementById(index); + var selected = []; + for (var i = select.options.length - 1; i >= 0; i--) { + selected.push(select.options[i].value); + } + jQuery.post ("ajax.php", + {"page" : "godmode/setup/setup_notifications", + "add_source_to_database" : 1, + "users" : id, + "source_id" : source_id, + "elements": selected + }, + function (data, status) { + if (data.result) { + // Append to other element + var out_select = document.getElementById('multi-' + id + '-' + source_id); + for (var i = select.options.length - 1; i >= 0; i--) { + out_select.appendChild(select.options[i]); + } + // Close the dialog + $("#" + notifications_two_ways_element_get_dialog(id, source_id)).dialog("close"); + } else { + console.log("Cannot update element."); + } + }, + "json" + ); +} diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index cd8d977053..44bb0fb12e 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -265,7 +265,8 @@ function notifications_add_group_to_source ($source_id, $groups) { // Insert into database all groups passed $res = true; foreach ($groups as $group) { - $res = db_process_sql_insert( + if (empty($group)) continue; + $res = $res && db_process_sql_insert( 'tnotification_source_group', array( 'id_group' => $group, @@ -275,6 +276,32 @@ function notifications_add_group_to_source ($source_id, $groups) { return $res; } +/** + * Insert a set of users to notification source + * + * @param int Source id + * @param array Id of users to be deleted + * + * @return bool True if success. False otherwise. + */ + function notifications_add_users_to_source ($source_id, $users) { + // Source id is mandatory + if (!isset($source_id)) return false; + + // Insert into database all groups passed + $res = true; + foreach ($users as $user) { + if (empty($user)) continue; + $res = $res && db_process_sql_insert( + 'tnotification_source_user', + array( + 'id_user' => $user, + 'id_source' => $source_id) + ) !== false; + } + return $res; +} + /** * Get the groups that not own to a source and, for that reason, they can be * added to the source. @@ -433,12 +460,15 @@ function notifications_print_source_select_box($info_selec, $id, $source_id, $di * @return string HTML with the select code. */ function notifications_print_two_ways_select($info_selec, $users, $source_id) { + $html_select = "
"; $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "all-multi-{$users}-{$source_id}[]", 0, false, '', '', true, true, true,''); $html_select .= "
"; $html_select .= html_print_image('images/darrowright.png', true, array('title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'add')")); $html_select .= html_print_image('images/darrowleft.png', true, array('title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'remove')")); $html_select .= "
"; $html_select .= html_print_select(true, "selected-multi-{$users}-{$source_id}[]", 0, false, '', '', true, true, true, ''); + $html_select .= "
"; + $html_select .= html_print_button(__('Add'), 'Add', false, "notifications_add_source_element_to_database('$users', '$source_id')", "class='sub add'", true); return $html_select; } diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 31ca3b865a..1d4e4af4c0 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4965,7 +4965,8 @@ div#dialog_messages table th:last-child { width: 99%; } -.global-config-notification-single-selector :last-child { +.global-config-notification-single-selector :last-child, +.global_config_notifications_dialog_add_wrapper { flex-direction: column; display: flex; justify-content: flex-end; From ddcf0bbd16c6cdd3e15dd394111d75c9c17779be Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 5 Feb 2019 18:14:10 +0100 Subject: [PATCH 045/249] Added deletion on global notification config Former-commit-id: 2356bbe374e5decf929cfaaf2fc4776611b0652d --- .../godmode/setup/setup_notifications.php | 86 ++++++++++++++----- .../include/functions_notifications.php | 24 +++++- 2 files changed, 88 insertions(+), 22 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 8233b84028..bf842951aa 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -29,11 +29,13 @@ if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user } // AJAX actions. +$source_id = get_parameter('source_id', ''); +$users = get_parameter('users', ''); +$elements = get_parameter('elements', array()); +$id = empty($source_id) ? 0 : get_notification_source_id($source_id); +$is_users = $users === "users"; if (get_parameter('get_selection_two_ways_form', 0)) { - $source_id = get_parameter('source_id', ''); - $users = get_parameter('users', ''); - $id = get_notification_source_id($source_id); - $info_selec = $users === "users" + $info_selec = $is_users ? notifications_get_user_source_not_configured($id) : notifications_get_group_source_not_configured($id); @@ -45,11 +47,7 @@ if (get_parameter('get_selection_two_ways_form', 0)) { return; } if (get_parameter('add_source_to_database', 0)) { - $source_id = get_parameter('source_id', ''); - $users = get_parameter('users', ''); - $elements = get_parameter('elements', array()); - $id = get_notification_source_id($source_id); - $res = $users === "users" + $res = $is_users ? notifications_add_users_to_source($id, $elements) : notifications_add_group_to_source($id, $elements); $result = array( @@ -58,6 +56,16 @@ if (get_parameter('add_source_to_database', 0)) { echo json_encode($result); return; } +if (get_parameter('remove_source_on_database', 0)) { + $res = $is_users + ? notifications_remove_users_from_source($id, $elements) + : notifications_remove_group_from_source($id, $elements); + $result = array( + 'result' => $res + ); + echo json_encode($result); + return; +} // Form actions. if (get_parameter('update_config', 0)) { @@ -118,25 +126,26 @@ function notifications_get_source_id(id) { return matched[1]; } +// Get index of two ways element dialog. +function notifications_two_ways_element_get_dialog (id, source_id) { + return 'global_config_notifications_dialog_add-' + id + '-' + source_id; +} + +// Get index of two ways element form. +function notifications_two_ways_element_get_sufix (id, source_id) { + return 'multi-' + id + '-' + source_id; +} + // Disable or enable the select seeing the checked value of notify all users function notifications_disable_source(event) { var id = notifications_get_source_id(event.target.id); var is_checked = document.getElementById(event.target.id).checked; var selectors = ['groups', 'users']; selectors.map(function (select) { - document.getElementById('multi-' + select + '-' + id).disabled = is_checked; + document.getElementById(notifications_two_ways_element_get_sufix(select, id)).disabled = is_checked; }); } -// Get index of two ways element dialog. -function notifications_two_ways_element_get_dialog (id, source_id) { - return 'global_config_notifications_dialog_add-' + id + '-' + source_id; -} -// Get index of two ways element form. -function notifications_two_ways_element_get_sufix (id, source_id) { - return 'multi-' + id + '-' + source_id; -} - // Open a dialog with selector of source elements. function add_source_dialog(users, source_id) { // Display the dialog @@ -187,7 +196,7 @@ function notifications_modify_two_ways_element (id, source_id, operation) { end_id + index_sufix ); for (var i = select.options.length - 1; i >= 0; i--) { - if(select.options[i].selected ==true){ + if(select.options[i].selected){ select_end.appendChild(select.options[i]); } } @@ -211,7 +220,9 @@ function notifications_add_source_element_to_database(id, source_id) { function (data, status) { if (data.result) { // Append to other element - var out_select = document.getElementById('multi-' + id + '-' + source_id); + var out_select = document.getElementById( + notifications_two_ways_element_get_sufix(id, source_id) + ); for (var i = select.options.length - 1; i >= 0; i--) { out_select.appendChild(select.options[i]); } @@ -224,4 +235,37 @@ function notifications_add_source_element_to_database(id, source_id) { "json" ); } + +// Add elements to database and remove it form main select +function remove_source_elements(id, source_id) { + var index = notifications_two_ways_element_get_sufix(id, source_id); + var select = document.getElementById(index); + var selected = []; + var selected_index = []; + for (var i = select.options.length - 1; i >= 0; i--) { + if(select.options[i].selected){ + selected.push(select.options[i].value); + selected_index.push(i); + } + } + jQuery.post ("ajax.php", + {"page" : "godmode/setup/setup_notifications", + "remove_source_on_database" : 1, + "users" : id, + "source_id" : source_id, + "elements": selected + }, + function (data, status) { + if (data.result) { + // Append to other element + for (var i = selected_index.length - 1; i >= 0; i--) { + select.remove(selected_index[i]); + } + } else { + console.log("Cannot delete elements."); + } + }, + "json" + ); +} diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 44bb0fb12e..9467c0ff92 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -250,6 +250,28 @@ function notifications_remove_group_from_source ($source_id, $groups) { ) !== false; } +/** + * Delete a set of users from notification source + * + * @param int Source id + * @param array Id of users to be deleted + * + * @return bool True if success. False otherwise. + */ +function notifications_remove_users_from_source ($source_id, $users) { + // Source id is mandatory + if (!isset($source_id)) return false; + + // Delete from database + return db_process_sql_delete ( + 'tnotification_source_user', + array( + 'id_user' => $users, + 'id_source' => $source_id + ) + ) !== false; +} + /** * Insert a set of groups to notification source * @@ -444,7 +466,7 @@ function notifications_print_source_select_box($info_selec, $id, $source_id, $di $html_select .= "
"; $html_select .= "
"; $html_select .= html_print_image('images/input_add.png', true, array('title' => $add_title, 'onclick' => "add_source_dialog('$id', '$source_id')")); - $html_select .= html_print_image('images/input_delete.png', true, array('title' => $delete_title)); + $html_select .= html_print_image('images/input_delete.png', true, array('title' => $delete_title, 'onclick' => "remove_source_elements('$id', '$source_id')")); $html_select .= "
"; $html_select .= "
"; return $html_select; From 6f87b436d0c48a33fa5dd041a9fa005c350bff32 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Tue, 5 Feb 2019 18:47:41 +0100 Subject: [PATCH 046/249] minor fix Former-commit-id: 3fabf2561773365932c5d33e8bf9e42b7ed4e7f0 --- pandora_console/include/functions_servers.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pandora_console/include/functions_servers.php b/pandora_console/include/functions_servers.php index bc5fd590f3..249704fe13 100644 --- a/pandora_console/include/functions_servers.php +++ b/pandora_console/include/functions_servers.php @@ -984,6 +984,9 @@ function servers_get_server_string_name(int $server) case SERVER_TYPE_SYSLOG: return __('Syslog server'); + case SERVER_TYPE_WUX: + return __('WUX server'); + default: return __('N/A'); } From ac6b74dcdf857d01a6107cf7b9176cc90f20f04d Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 6 Feb 2019 11:36:28 +0100 Subject: [PATCH 047/249] Added new window to display user notifications config Former-commit-id: 57ba8fcd01365cedc92535d7cf71f70432a55a94 --- pandora_console/operation/menu.php | 5 + pandora_console/operation/users/user_edit.php | 51 +--------- .../operation/users/user_edit_header.php | 97 +++++++++++++++++++ .../users/user_edit_notifications.php | 24 +++++ 4 files changed, 129 insertions(+), 48 deletions(-) create mode 100644 pandora_console/operation/users/user_edit_header.php create mode 100644 pandora_console/operation/users/user_edit_notifications.php diff --git a/pandora_console/operation/menu.php b/pandora_console/operation/menu.php index d7a546a96a..42a70cf5e2 100644 --- a/pandora_console/operation/menu.php +++ b/pandora_console/operation/menu.php @@ -374,6 +374,11 @@ $sub["operation/users/user_edit"]["text"] = __('Edit my user'); $sub["operation/users/user_edit"]["id"] = 'Edit my user'; $sub["operation/users/user_edit"]["refr"] = 0; +// Users +$sub["operation/users/user_edit_notifications"]["text"] = __('Configure user notifications'); +$sub["operation/users/user_edit_notifications"]["id"] = 'Configure user notifications'; +$sub["operation/users/user_edit_notifications"]["refr"] = 0; + // ANY user can chat with other user and dogs. // Users $sub["operation/users/webchat"]["text"] = __('WebChat'); diff --git a/pandora_console/operation/users/user_edit.php b/pandora_console/operation/users/user_edit.php index 1c2eb0ef2e..7613caa92e 100644 --- a/pandora_console/operation/users/user_edit.php +++ b/pandora_console/operation/users/user_edit.php @@ -13,56 +13,11 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); - -enterprise_hook('open_meta_frame'); - -include_once($config['homedir'] . "/include/functions_profile.php"); -include_once($config['homedir'] . '/include/functions_users.php'); -include_once ($config['homedir'] . '/include/functions_groups.php'); -include_once ($config['homedir'] . '/include/functions_visual_map.php'); - -$meta = false; -if (enterprise_installed() && defined("METACONSOLE")) { - $meta = true; -} - -$id = get_parameter_get ("id", $config["id_user"]); // ID given as parameter -$status = get_parameter ("status", -1); // Flag to print action status message - -$user_info = get_user_info ($id); -$id = $user_info["id_user"]; //This is done in case there are problems with uppercase/lowercase (MySQL auth has that problem) - -if ((!check_acl ($config["id_user"], users_get_groups ($id), "UM")) - AND ($id != $config["id_user"])) { - - db_pandora_audit("ACL Violation","Trying to view a user without privileges"); - require ("general/noaccess.php"); - exit; -} - -//If current user is editing himself or if the user has UM (User Management) rights on any groups the user is part of AND the authorization scheme allows for users/admins to update info -if (($config["id_user"] == $id || check_acl ($config["id_user"], users_get_groups ($id), "UM")) && $config["user_can_update_info"]) { - $view_mode = false; -} -else { - $view_mode = true; -} - -// Header -if ($meta) { - user_meta_print_header(); - $url = 'index.php?sec=advanced&sec2=advanced/users_setup&tab=user_edit'; -} -else { - ui_print_page_header (__('User detail editor'), "images/op_workspace.png", false, "", false, ""); - $url = 'index.php?sec=workspace&sec2=operation/users/user_edit'; -} - +// Load the header +require($config['homedir'] . "/operation/users/user_edit_header.php"); // Update user info if (isset ($_GET["modified"]) && !$view_mode) { @@ -525,7 +480,7 @@ $table->rowclass[] = ''; $table->rowstyle[] = ''; $table->data[] = $data; -echo '
'; +echo ''; html_print_table($table); diff --git a/pandora_console/operation/users/user_edit_header.php b/pandora_console/operation/users/user_edit_header.php new file mode 100644 index 0000000000..99e0567e57 --- /dev/null +++ b/pandora_console/operation/users/user_edit_header.php @@ -0,0 +1,97 @@ + array( + 'active' => $_GET['sec2'] === 'operation/users/user_edit', + 'text' => + "". + html_print_image ( + "images/user_green.png", + true, + array ("title" => __('User management')) + ).'' + ), + 'notifications' => array( + 'active' => $_GET['sec2'] === 'operation/users/user_edit_notifications', + 'text' => + "". + html_print_image ( + "images/alerts_template.png", + true, + array ("title" => __('User notifications')) + ).'' + ) + ); + + ui_print_page_header ( + __('User detail editor'), + "images/op_workspace.png", + false, + "", + false, + $buttons + ); +} + +?> \ No newline at end of file diff --git a/pandora_console/operation/users/user_edit_notifications.php b/pandora_console/operation/users/user_edit_notifications.php new file mode 100644 index 0000000000..edec0e2a6c --- /dev/null +++ b/pandora_console/operation/users/user_edit_notifications.php @@ -0,0 +1,24 @@ + \ No newline at end of file From 6ddcfcbb19a07037d4503af914bd4a50ee98b0c5 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 6 Feb 2019 12:51:02 +0100 Subject: [PATCH 048/249] Fixed code style lintern Former-commit-id: d7757a56f8368761776f80f826600d601b56b6d9 --- .../godmode/setup/setup_notifications.php | 360 +++++++++--------- .../include/functions_notifications.php | 315 +++++++++------ .../operation/users/user_edit_header.php | 124 +++--- 3 files changed, 425 insertions(+), 374 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index bf842951aa..d315f14711 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -1,10 +1,9 @@ - $res - ); - echo json_encode($result); - return; + $res = $is_users ? notifications_add_users_to_source($id, $elements) : notifications_add_group_to_source($id, $elements); + $result = ['result' => $res]; + echo json_encode($result); + return; } + if (get_parameter('remove_source_on_database', 0)) { - $res = $is_users - ? notifications_remove_users_from_source($id, $elements) - : notifications_remove_group_from_source($id, $elements); - $result = array( - 'result' => $res - ); - echo json_encode($result); - return; + $res = $is_users ? notifications_remove_users_from_source($id, $elements) : notifications_remove_group_from_source($id, $elements); + $result = ['result' => $res]; + echo json_encode($result); + return; } // Form actions. if (get_parameter('update_config', 0)) { - $res_global = array_reduce(notifications_get_all_sources(), function($carry, $source){ - $id = notifications_desc_to_id($source['description']); - if (empty($id)) return false; - $enable_value = switch_to_int(get_parameter("enable-$id")); - $mail_value = (int)get_parameter("mail-{$id}", 0); - $user_value = (int)get_parameter("user-{$id}", 0); - $postpone_value = (int)get_parameter("postpone-{$id}", 0); - $all_users = (int)get_parameter("all-{$id}", 0); - $res = db_process_sql_update( - 'tnotification_source', - array( - 'enabled' => $enable_value, - 'user_editable' => $user_value, - 'also_mail' => $mail_value, - 'max_postpone_time' => $postpone_value - ), - array('id' => $source['id']) - ); - $all_users_res = $all_users - ? notifications_add_group_to_source($source['id'], array(0)) - : notifications_remove_group_from_source($source['id'], array(0)); - return $all_users_res && $res && $carry; - }, true); + $res_global = array_reduce( + notifications_get_all_sources(), + function ($carry, $source) { + $id = notifications_desc_to_id($source['description']); + if (empty($id)) { + return false; + } + + $enable_value = switch_to_int(get_parameter("enable-$id")); + $mail_value = (int) get_parameter("mail-{$id}", 0); + $user_value = (int) get_parameter("user-{$id}", 0); + $postpone_value = (int) get_parameter("postpone-{$id}", 0); + $all_users = (int) get_parameter("all-{$id}", 0); + $res = db_process_sql_update( + 'tnotification_source', + [ + 'enabled' => $enable_value, + 'user_editable' => $user_value, + 'also_mail' => $mail_value, + 'max_postpone_time' => $postpone_value, + ], + ['id' => $source['id']] + ); + $all_users_res = $all_users ? notifications_add_group_to_source($source['id'], [0]) : notifications_remove_group_from_source($source['id'], [0]); + return $all_users_res && $res && $carry; + }, + true + ); } // Notification table. It is just a wrapper. $table_content = new StdClass(); -$table_content->data = array(); +$table_content->data = []; $table_content->width = '100%'; $table_content->id = 'notifications-wrapper'; $table_content->class = 'databox filters'; $table_content->size['name'] = '30%'; -$table_remote->style['name'] = 'font-weight: bold'; // Print each source configuration -$table_content->data = array_map(function ($source) { - return notifications_print_global_source_configuration($source); -}, notifications_get_all_sources()); +$table_content->data = array_map( + function ($source) { + return notifications_print_global_source_configuration($source); + }, + notifications_get_all_sources() +); $table_content->data[] = html_print_submit_button( - __('Update'), 'update_button', false, 'class="sub upd" style="display: flex; "', true + __('Update'), + 'update_button', + false, + 'class="sub upd" style="display: flex; "', + true ); echo ''; @@ -121,151 +121,151 @@ echo ''; // Get the source id function notifications_get_source_id(id) { - var matched = id.match(/.*-(.*)/); - if (matched == null) return ''; - return matched[1]; + var matched = id.match(/.*-(.*)/); + if (matched == null) return ''; + return matched[1]; } // Get index of two ways element dialog. function notifications_two_ways_element_get_dialog (id, source_id) { - return 'global_config_notifications_dialog_add-' + id + '-' + source_id; + return 'global_config_notifications_dialog_add-' + id + '-' + source_id; } // Get index of two ways element form. function notifications_two_ways_element_get_sufix (id, source_id) { - return 'multi-' + id + '-' + source_id; + return 'multi-' + id + '-' + source_id; } // Disable or enable the select seeing the checked value of notify all users function notifications_disable_source(event) { - var id = notifications_get_source_id(event.target.id); - var is_checked = document.getElementById(event.target.id).checked; - var selectors = ['groups', 'users']; - selectors.map(function (select) { - document.getElementById(notifications_two_ways_element_get_sufix(select, id)).disabled = is_checked; - }); + var id = notifications_get_source_id(event.target.id); + var is_checked = document.getElementById(event.target.id).checked; + var selectors = ['groups', 'users']; + selectors.map(function (select) { + document.getElementById(notifications_two_ways_element_get_sufix(select, id)).disabled = is_checked; + }); } // Open a dialog with selector of source elements. function add_source_dialog(users, source_id) { - // Display the dialog - var dialog_id = notifications_two_ways_element_get_dialog(users, source_id); - // Clean id element. - var previous_dialog = document.getElementById(dialog_id); - if (previous_dialog !== null) previous_dialog.remove(); - // Create or recreate the content. - var not_dialog = document.createElement('div'); - not_dialog.setAttribute('class', 'global_config_notifications_dialog_add_wrapper'); - not_dialog.setAttribute('id', dialog_id); - document.body.appendChild(not_dialog); - $("#" + dialog_id).dialog({ - resizable: false, - draggable: true, - modal: true, - dialogClass: "global_config_notifications_dialog_add_full", - overlay: { - opacity: 0.5, - background: "black" - }, - closeOnEscape: true, - modal: true - }); + // Display the dialog + var dialog_id = notifications_two_ways_element_get_dialog(users, source_id); + // Clean id element. + var previous_dialog = document.getElementById(dialog_id); + if (previous_dialog !== null) previous_dialog.remove(); + // Create or recreate the content. + var not_dialog = document.createElement('div'); + not_dialog.setAttribute('class', 'global_config_notifications_dialog_add_wrapper'); + not_dialog.setAttribute('id', dialog_id); + document.body.appendChild(not_dialog); + $("#" + dialog_id).dialog({ + resizable: false, + draggable: true, + modal: true, + dialogClass: "global_config_notifications_dialog_add_full", + overlay: { + opacity: 0.5, + background: "black" + }, + closeOnEscape: true, + modal: true + }); - jQuery.post ("ajax.php", - {"page" : "godmode/setup/setup_notifications", - "get_selection_two_ways_form" : 1, - "users" : users, - "source_id" : source_id - }, - function (data, status) { - not_dialog.innerHTML = data - }, - "html" - ); + jQuery.post ("ajax.php", + {"page" : "godmode/setup/setup_notifications", + "get_selection_two_ways_form" : 1, + "users" : users, + "source_id" : source_id + }, + function (data, status) { + not_dialog.innerHTML = data + }, + "html" + ); } // Move from selected and not selected source elements. function notifications_modify_two_ways_element (id, source_id, operation) { - var index_sufix = notifications_two_ways_element_get_sufix (id, source_id); - var start_id = operation === 'add' ? 'all-' : 'selected-'; - var end_id = operation !== 'add' ? 'all-' : 'selected-'; - var select = document.getElementById( - start_id + index_sufix - ); - var select_end = document.getElementById( - end_id + index_sufix - ); - for (var i = select.options.length - 1; i >= 0; i--) { - if(select.options[i].selected){ - select_end.appendChild(select.options[i]); - } - } + var index_sufix = notifications_two_ways_element_get_sufix (id, source_id); + var start_id = operation === 'add' ? 'all-' : 'selected-'; + var end_id = operation !== 'add' ? 'all-' : 'selected-'; + var select = document.getElementById( + start_id + index_sufix + ); + var select_end = document.getElementById( + end_id + index_sufix + ); + for (var i = select.options.length - 1; i >= 0; i--) { + if(select.options[i].selected){ + select_end.appendChild(select.options[i]); + } + } } // Add elements to database and close dialog function notifications_add_source_element_to_database(id, source_id) { - var index = 'selected-' + notifications_two_ways_element_get_sufix (id, source_id); - var select = document.getElementById(index); - var selected = []; - for (var i = select.options.length - 1; i >= 0; i--) { - selected.push(select.options[i].value); - } - jQuery.post ("ajax.php", - {"page" : "godmode/setup/setup_notifications", - "add_source_to_database" : 1, - "users" : id, - "source_id" : source_id, - "elements": selected - }, - function (data, status) { - if (data.result) { - // Append to other element - var out_select = document.getElementById( - notifications_two_ways_element_get_sufix(id, source_id) - ); - for (var i = select.options.length - 1; i >= 0; i--) { - out_select.appendChild(select.options[i]); - } - // Close the dialog - $("#" + notifications_two_ways_element_get_dialog(id, source_id)).dialog("close"); - } else { - console.log("Cannot update element."); - } - }, - "json" - ); + var index = 'selected-' + notifications_two_ways_element_get_sufix (id, source_id); + var select = document.getElementById(index); + var selected = []; + for (var i = select.options.length - 1; i >= 0; i--) { + selected.push(select.options[i].value); + } + jQuery.post ("ajax.php", + {"page" : "godmode/setup/setup_notifications", + "add_source_to_database" : 1, + "users" : id, + "source_id" : source_id, + "elements": selected + }, + function (data, status) { + if (data.result) { + // Append to other element + var out_select = document.getElementById( + notifications_two_ways_element_get_sufix(id, source_id) + ); + for (var i = select.options.length - 1; i >= 0; i--) { + out_select.appendChild(select.options[i]); + } + // Close the dialog + $("#" + notifications_two_ways_element_get_dialog(id, source_id)).dialog("close"); + } else { + console.log("Cannot update element."); + } + }, + "json" + ); } // Add elements to database and remove it form main select function remove_source_elements(id, source_id) { - var index = notifications_two_ways_element_get_sufix(id, source_id); - var select = document.getElementById(index); - var selected = []; - var selected_index = []; - for (var i = select.options.length - 1; i >= 0; i--) { - if(select.options[i].selected){ - selected.push(select.options[i].value); - selected_index.push(i); - } - } - jQuery.post ("ajax.php", - {"page" : "godmode/setup/setup_notifications", - "remove_source_on_database" : 1, - "users" : id, - "source_id" : source_id, - "elements": selected - }, - function (data, status) { - if (data.result) { - // Append to other element - for (var i = selected_index.length - 1; i >= 0; i--) { - select.remove(selected_index[i]); - } - } else { - console.log("Cannot delete elements."); - } - }, - "json" - ); + var index = notifications_two_ways_element_get_sufix(id, source_id); + var select = document.getElementById(index); + var selected = []; + var selected_index = []; + for (var i = select.options.length - 1; i >= 0; i--) { + if(select.options[i].selected){ + selected.push(select.options[i].value); + selected_index.push(i); + } + } + jQuery.post ("ajax.php", + {"page" : "godmode/setup/setup_notifications", + "remove_source_on_database" : 1, + "users" : id, + "source_id" : source_id, + "elements": selected + }, + function (data, status) { + if (data.result) { + // Append to other element + for (var i = selected_index.length - 1; i >= 0; i--) { + select.remove(selected_index[i]); + } + } else { + console.log("Cannot delete elements."); + } + }, + "json" + ); } diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 9467c0ff92..ac030349ef 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -29,6 +29,7 @@ define('NOTIFICATIONS_POSTPONE_FOREVER', -1); + /** * Retrieves source ID for given source. * @@ -49,6 +50,7 @@ function get_notification_source_id(string $source) ); } + /** * Converts description into a handable identifier * @@ -56,12 +58,14 @@ function get_notification_source_id(string $source) * * @return string First word in lowercase. Empty string if no word detected. */ -function notifications_desc_to_id(string $desc) { +function notifications_desc_to_id(string $desc) +{ preg_match('/^[a-zA-Z]*/', $desc, $matches); $match = $matches[0]; return isset($match) ? $match : ''; } + /** * Retrieve all targets for given message. * @@ -158,30 +162,36 @@ function check_notification_readable(int $id_message) return (bool) db_get_value_sql($sql); } + /** * Return all info from tnotification_source * * @return array with sources info */ -function notifications_get_all_sources() { - return mysql_db_get_all_rows_in_table('tnotification_source'); +function notifications_get_all_sources() +{ + return db_get_all_rows_in_table('tnotification_source'); } + /** * Return the user sources to be inserted into a select * - * @param int $source_id Source database identificator + * @param integer $source_id Source database identificator * * @return array with the user id in keys and user id in value too */ -function notifications_get_user_sources_for_select($source_id) { +function notifications_get_user_sources_for_select($source_id) +{ $users = db_get_all_rows_filter( 'tnotification_source_user', - array('id_source' => $source_id), + ['id_source' => $source_id], 'id_user' ); // If fails or no one is selected, return empty array - if ($users === false) return array(); + if ($users === false) { + return []; + } return index_array($users, 'id_user', 'id_user'); } @@ -190,186 +200,231 @@ function notifications_get_user_sources_for_select($source_id) { /** * Return the groups sources to be inserted into a select * - * @param int $source_id Source database identificator + * @param integer $source_id Source database identificator * * @return array with the group id in keys and group name in value */ -function notifications_get_group_sources_for_select($source_id) { - $groups = notifications_get_group_sources ( - array('id_source' => $source_id), - array('id_group') +function notifications_get_group_sources_for_select($source_id) +{ + $groups = notifications_get_group_sources( + ['id_source' => $source_id], + ['id_group'] ); return index_array($groups, 'id_group', 'name'); } + /** * Get the group sources * * @param array $filter Filter of sql query. */ -function notifications_get_group_sources ($filter = array(), $fields = array()) { +function notifications_get_group_sources($filter=[], $fields=[]) +{ // Get only the tnotifications_source_group fields in addition to group name. - if (empty($fields)) $fields[] = "tnsg.*"; - $fields = array_map(function($field) { - if (!preg_match("/^tnsg./", $field)) $field = "tnsg.{$field}"; - return $field; - }, $fields); + if (empty($fields)) { + $fields[] = 'tnsg.*'; + } + + $fields = array_map( + function ($field) { + if (!preg_match('/^tnsg./', $field)) { + $field = "tnsg.{$field}"; + } + + return $field; + }, + $fields + ); // Get groups. $groups = db_get_all_rows_filter( 'tnotification_source_group tnsg LEFT JOIN tgrupo tg ON tnsg.id_group = tg.id_grupo', $filter, - array_merge ($fields, array('IFNULL(tg.nombre, "All") AS name')) + array_merge($fields, ['IFNULL(tg.nombre, "All") AS name']) ); // If fails or no one is selected, return empty array - if ($groups === false) return array(); + if ($groups === false) { + return []; + } + return $groups; } + /** * Delete a set of groups from notification source * * @param int Source id * @param array Id of groups to be deleted * - * @return bool True if success. False otherwise. + * @return boolean True if success. False otherwise. */ -function notifications_remove_group_from_source ($source_id, $groups) { +function notifications_remove_group_from_source($source_id, $groups) +{ // Source id is mandatory - if (!isset($source_id)) return false; + if (!isset($source_id)) { + return false; + } // Delete from database - return db_process_sql_delete ( + return db_process_sql_delete( 'tnotification_source_group', - array( - 'id_group' => $groups, - 'id_source' => $source_id - ) + [ + 'id_group' => $groups, + 'id_source' => $source_id, + ] ) !== false; } + /** * Delete a set of users from notification source * * @param int Source id * @param array Id of users to be deleted * - * @return bool True if success. False otherwise. + * @return boolean True if success. False otherwise. */ -function notifications_remove_users_from_source ($source_id, $users) { +function notifications_remove_users_from_source($source_id, $users) +{ // Source id is mandatory - if (!isset($source_id)) return false; + if (!isset($source_id)) { + return false; + } // Delete from database - return db_process_sql_delete ( + return db_process_sql_delete( 'tnotification_source_user', - array( - 'id_user' => $users, - 'id_source' => $source_id - ) + [ + 'id_user' => $users, + 'id_source' => $source_id, + ] ) !== false; } + /** * Insert a set of groups to notification source * * @param int Source id * @param array Id of groups to be deleted * - * @return bool True if success. False otherwise. + * @return boolean True if success. False otherwise. */ -function notifications_add_group_to_source ($source_id, $groups) { +function notifications_add_group_to_source($source_id, $groups) +{ // Source id is mandatory - if (!isset($source_id)) return false; + if (!isset($source_id)) { + return false; + } // Insert into database all groups passed $res = true; foreach ($groups as $group) { - if (empty($group)) continue; + if (empty($group)) { + continue; + } + $res = $res && db_process_sql_insert( 'tnotification_source_group', - array( - 'id_group' => $group, - 'id_source' => $source_id) - ) !== false; + [ + 'id_group' => $group, + 'id_source' => $source_id, + ] + ) !== false; } + return $res; } + /** * Insert a set of users to notification source * * @param int Source id * @param array Id of users to be deleted * - * @return bool True if success. False otherwise. + * @return boolean True if success. False otherwise. */ - function notifications_add_users_to_source ($source_id, $users) { +function notifications_add_users_to_source($source_id, $users) +{ // Source id is mandatory - if (!isset($source_id)) return false; + if (!isset($source_id)) { + return false; + } // Insert into database all groups passed $res = true; foreach ($users as $user) { - if (empty($user)) continue; + if (empty($user)) { + continue; + } + $res = $res && db_process_sql_insert( 'tnotification_source_user', - array( - 'id_user' => $user, - 'id_source' => $source_id) - ) !== false; + [ + 'id_user' => $user, + 'id_source' => $source_id, + ] + ) !== false; } + return $res; } + /** * Get the groups that not own to a source and, for that reason, they can be * added to the source. * - * @param int $source_id Source id. + * @param integer $source_id Source id. * @return array Indexed by id group all selectable groups. */ -function notifications_get_group_source_not_configured ($source_id) { +function notifications_get_group_source_not_configured($source_id) +{ $groups_selected = notifications_get_group_sources_for_select($source_id); - $all_groups = users_get_groups_for_select(false, "AR", false, true, $groups_selected); + $all_groups = users_get_groups_for_select(false, 'AR', false, true, $groups_selected); return array_diff($all_groups, $groups_selected); } + /** * Get the users that not own to a source and, for that reason, they can be * added to the source. * - * @param int $source_id + * @param integer $source_id * @return array Indexed by id user, all selectable users. */ -function notifications_get_user_source_not_configured ($source_id) { +function notifications_get_user_source_not_configured($source_id) +{ $users_selected = array_keys(notifications_get_user_sources_for_select($source_id)); $users = get_users( 'id_user', - array('!id_user' => $users_selected), - array('id_user') + ['!id_user' => $users_selected], + ['id_user'] ); return index_array($users, 'id_user', 'id_user'); } + /** * Print the notification ball to see unread messages * * @return string with HTML code of notification ball */ -function notifications_print_ball() { +function notifications_print_ball() +{ $num_notifications = messages_get_count(); - $class_status = $num_notifications == 0 - ? 'notification-ball-no-messages' - : 'notification-ball-new-messages'; - return - "
+ $class_status = $num_notifications == 0 ? 'notification-ball-no-messages' : 'notification-ball-new-messages'; + return "
$num_notifications
"; } + /** * Print notification configuration global * @@ -377,58 +432,61 @@ function notifications_print_ball() { * * @return string with HTML of source configuration */ -function notifications_print_global_source_configuration($source) { - +function notifications_print_global_source_configuration($source) +{ // Get some values to generate the title $id = notifications_desc_to_id($source['description']); - $switch_values = array ( - 'name' => "enable-" . $id, - 'value' => $source['enabled'] - ); + $switch_values = [ + 'name' => 'enable-'.$id, + 'value' => $source['enabled'], + ]; // Search if group all is set and handle that situation $source_groups = notifications_get_group_sources_for_select($source['id']); - $is_group_all = isset($source_groups["0"]); - if($is_group_all) unset($source_groups["0"]); + $is_group_all = isset($source_groups['0']); + if ($is_group_all) { + unset($source_groups['0']); + } // Generate the title $html_title = "
"; - $html_title .= html_print_switch($switch_values); - $html_title .= "

{$source['description']}

"; - $html_title .= "
"; + $html_title .= html_print_switch($switch_values); + $html_title .= "

{$source['description']}

"; + $html_title .= '
'; // Generate the html for title $html_selectors = "
"; - $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $id, $is_group_all); - $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $id, $is_group_all); - $html_selectors .= "
"; + $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $id, $is_group_all); + $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $id, $is_group_all); + $html_selectors .= ''; // Generate the checkboxes and time select $html_checkboxes = "
"; - $html_checkboxes .= " "; - $html_checkboxes .= html_print_checkbox("all-$id", 1, $is_group_all, true, false, 'notifications_disable_source(event)'); - $html_checkboxes .= __('Notify all users'); - $html_checkboxes .= "
"; - $html_checkboxes .= html_print_checkbox("mail-$id", 1, $source['also_mail'], true); - $html_checkboxes .= __('Also email users with notification content'); - $html_checkboxes .= "
"; - $html_checkboxes .= html_print_checkbox("user-$id", 1, $source['user_editable'], true); - $html_checkboxes .= __('Users cannot modify notification preferences'); - $html_checkboxes .= " "; - $html_checkboxes .= "
"; + $html_checkboxes .= ' '; + $html_checkboxes .= html_print_checkbox("all-$id", 1, $is_group_all, true, false, 'notifications_disable_source(event)'); + $html_checkboxes .= __('Notify all users'); + $html_checkboxes .= '
'; + $html_checkboxes .= html_print_checkbox("mail-$id", 1, $source['also_mail'], true); + $html_checkboxes .= __('Also email users with notification content'); + $html_checkboxes .= '
'; + $html_checkboxes .= html_print_checkbox("user-$id", 1, $source['user_editable'], true); + $html_checkboxes .= __('Users cannot modify notification preferences'); + $html_checkboxes .= ' '; + $html_checkboxes .= ''; // Generate the select with the time $html_select_pospone = __('Users can postpone notifications up to'); - $html_select_pospone .= html_print_select ( - array( - SECONDS_5MINUTES => __('5 minutes'), - SECONDS_15MINUTES => __('15 minutes'), - SECONDS_12HOURS => __('12 hours'), - SECONDS_1DAY => __('1 day'), - SECONDS_1WEEK => __('1 week'), - SECONDS_15DAYS => __('15 days'), - SECONDS_1MONTH => __('1 month'), - NOTIFICATIONS_POSTPONE_FOREVER => __('forever')), + $html_select_pospone .= html_print_select( + [ + SECONDS_5MINUTES => __('5 minutes'), + SECONDS_15MINUTES => __('15 minutes'), + SECONDS_12HOURS => __('12 hours'), + SECONDS_1DAY => __('1 day'), + SECONDS_1WEEK => __('1 week'), + SECONDS_15DAYS => __('15 days'), + SECONDS_1MONTH => __('1 month'), + NOTIFICATIONS_POSTPONE_FOREVER => __('forever'), + ], "postpone-{$id}", $source['max_postpone_time'], '', @@ -438,58 +496,61 @@ function notifications_print_global_source_configuration($source) { ); // Return all html - return $html_title . $html_selectors . $html_checkboxes . $html_select_pospone; + return $html_title.$html_selectors.$html_checkboxes.$html_select_pospone; } + /** * Print select boxes of notified users or groups * - * @param array $info_selec All info required for build the selector - * @param string $id users|groups - * @param string $source_id Id of source - * @param bool $disabled Disable the selectors + * @param array $info_selec All info required for build the selector + * @param string $id users|groups + * @param string $source_id Id of source + * @param boolean $disabled Disable the selectors * * @return string HTML with the generated selector */ -function notifications_print_source_select_box($info_selec, $id, $source_id, $disabled) { - - $title = $id == "users" ? __('Notified users') : __('Notified groups'); - $add_title = $id == "users" ? __('Add users') : __('Add groups'); - $delete_title = $id == "users" ? __('Delete users') : __('Delete groups'); +function notifications_print_source_select_box($info_selec, $id, $source_id, $disabled) +{ + $title = $id == 'users' ? __('Notified users') : __('Notified groups'); + $add_title = $id == 'users' ? __('Add users') : __('Add groups'); + $delete_title = $id == 'users' ? __('Delete users') : __('Delete groups'); // Generate the HTML $html_select = "
"; - $html_select .= "
"; + $html_select .= '
'; $html_select .= "

$title

"; // Put a true if empty sources to avoid to sow the 'None' value - $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}-{$source_id}[]", 0, false, '', '', true, true, true,'', $disabled); - $html_select .= "
"; + $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "multi-{$id}-{$source_id}[]", 0, false, '', '', true, true, true, '', $disabled); + $html_select .= '
'; $html_select .= "
"; - $html_select .= html_print_image('images/input_add.png', true, array('title' => $add_title, 'onclick' => "add_source_dialog('$id', '$source_id')")); - $html_select .= html_print_image('images/input_delete.png', true, array('title' => $delete_title, 'onclick' => "remove_source_elements('$id', '$source_id')")); - $html_select .= "
"; - $html_select .= "
"; + $html_select .= html_print_image('images/input_add.png', true, ['title' => $add_title, 'onclick' => "add_source_dialog('$id', '$source_id')"]); + $html_select .= html_print_image('images/input_delete.png', true, ['title' => $delete_title, 'onclick' => "remove_source_elements('$id', '$source_id')"]); + $html_select .= ' '; + $html_select .= ''; return $html_select; } + /** * Print the select with right and left arrows to select new sources * (groups or users). * - * @param array $info_selec Array with source info. - * @param string $users users|groups. - * @param source $source_id Source id. + * @param array $info_selec Array with source info. + * @param string $users users|groups. + * @param source $source_id Source id. * @return string HTML with the select code. */ -function notifications_print_two_ways_select($info_selec, $users, $source_id) { +function notifications_print_two_ways_select($info_selec, $users, $source_id) +{ $html_select = "
"; - $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "all-multi-{$users}-{$source_id}[]", 0, false, '', '', true, true, true,''); - $html_select .= "
"; - $html_select .= html_print_image('images/darrowright.png', true, array('title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'add')")); - $html_select .= html_print_image('images/darrowleft.png', true, array('title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'remove')")); - $html_select .= "
"; + $html_select .= html_print_select(empty($info_selec) ? true : $info_selec, "all-multi-{$users}-{$source_id}[]", 0, false, '', '', true, true, true, ''); + $html_select .= "
"; + $html_select .= html_print_image('images/darrowright.png', true, ['title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'add')"]); + $html_select .= html_print_image('images/darrowleft.png', true, ['title' => $add_title, 'onclick' => "notifications_modify_two_ways_element('$users', '$source_id', 'remove')"]); + $html_select .= '
'; $html_select .= html_print_select(true, "selected-multi-{$users}-{$source_id}[]", 0, false, '', '', true, true, true, ''); - $html_select .= "
"; + $html_select .= ''; $html_select .= html_print_button(__('Add'), 'Add', false, "notifications_add_source_element_to_database('$users', '$source_id')", "class='sub add'", true); return $html_select; diff --git a/pandora_console/operation/users/user_edit_header.php b/pandora_console/operation/users/user_edit_header.php index 99e0567e57..4b329eee77 100644 --- a/pandora_console/operation/users/user_edit_header.php +++ b/pandora_console/operation/users/user_edit_header.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,86 +11,77 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; -check_login (); +check_login(); enterprise_hook('open_meta_frame'); -include_once($config['homedir'] . "/include/functions_profile.php"); -include_once($config['homedir'] . '/include/functions_users.php'); -include_once ($config['homedir'] . '/include/functions_groups.php'); -include_once ($config['homedir'] . '/include/functions_visual_map.php'); +require_once $config['homedir'].'/include/functions_profile.php'; +require_once $config['homedir'].'/include/functions_users.php'; +require_once $config['homedir'].'/include/functions_groups.php'; +require_once $config['homedir'].'/include/functions_visual_map.php'; $meta = false; -if (enterprise_installed() && defined("METACONSOLE")) { - $meta = true; +if (enterprise_installed() && defined('METACONSOLE')) { + $meta = true; } -$id = get_parameter_get ("id", $config["id_user"]); // ID given as parameter -$status = get_parameter ("status", -1); // Flag to print action status message - -$user_info = get_user_info ($id); -$id = $user_info["id_user"]; //This is done in case there are problems with uppercase/lowercase (MySQL auth has that problem) - -if ((!check_acl ($config["id_user"], users_get_groups ($id), "UM")) - AND ($id != $config["id_user"])) { - - db_pandora_audit("ACL Violation","Trying to view a user without privileges"); - require ("general/noaccess.php"); - exit; +$id = get_parameter_get('id', $config['id_user']); +// ID given as parameter +$status = get_parameter('status', -1); +// Flag to print action status message +$user_info = get_user_info($id); +$id = $user_info['id_user']; +// This is done in case there are problems with uppercase/lowercase (MySQL auth has that problem) +if ((!check_acl($config['id_user'], users_get_groups($id), 'UM')) + and ($id != $config['id_user']) +) { + db_pandora_audit('ACL Violation', 'Trying to view a user without privileges'); + include 'general/noaccess.php'; + exit; } -//If current user is editing himself or if the user has UM (User Management) rights on any groups the user is part of AND the authorization scheme allows for users/admins to update info -if (($config["id_user"] == $id || check_acl ($config["id_user"], users_get_groups ($id), "UM")) && $config["user_can_update_info"]) { - $view_mode = false; -} -else { - $view_mode = true; +// If current user is editing himself or if the user has UM (User Management) rights on any groups the user is part of AND the authorization scheme allows for users/admins to update info +if (($config['id_user'] == $id || check_acl($config['id_user'], users_get_groups($id), 'UM')) && $config['user_can_update_info']) { + $view_mode = false; +} else { + $view_mode = true; } -$urls = array(); +$urls = []; if (is_metaconsole()) { - user_meta_print_header(); - $urls['main'] = 'index.php?sec=advanced&sec2=advanced/users_setup&tab=user_edit'; -} -else { - $urls['main'] = "index.php?sec=workspace&sec2=operation/users/user_edit"; - $urls['notifications'] = "index.php?sec=workspace&sec2=operation/users/user_edit_notifications"; - $buttons = array( - 'main' => array( - 'active' => $_GET['sec2'] === 'operation/users/user_edit', - 'text' => - "". - html_print_image ( - "images/user_green.png", - true, - array ("title" => __('User management')) - ).'' - ), - 'notifications' => array( - 'active' => $_GET['sec2'] === 'operation/users/user_edit_notifications', - 'text' => - "". - html_print_image ( - "images/alerts_template.png", - true, - array ("title" => __('User notifications')) - ).'' - ) - ); + user_meta_print_header(); + $urls['main'] = 'index.php?sec=advanced&sec2=advanced/users_setup&tab=user_edit'; +} else { + $urls['main'] = 'index.php?sec=workspace&sec2=operation/users/user_edit'; + $urls['notifications'] = 'index.php?sec=workspace&sec2=operation/users/user_edit_notifications'; + $buttons = [ + 'main' => [ + 'active' => $_GET['sec2'] === 'operation/users/user_edit', + 'text' => "".html_print_image( + 'images/user_green.png', + true, + ['title' => __('User management')] + ).'', + ], + 'notifications' => [ + 'active' => $_GET['sec2'] === 'operation/users/user_edit_notifications', + 'text' => "".html_print_image( + 'images/alerts_template.png', + true, + ['title' => __('User notifications')] + ).'', + ], + ]; - ui_print_page_header ( - __('User detail editor'), - "images/op_workspace.png", - false, - "", - false, - $buttons - ); + ui_print_page_header( + __('User detail editor'), + 'images/op_workspace.png', + false, + '', + false, + $buttons + ); } - -?> \ No newline at end of file From 19c5a1c84466bb4020e35d726406a47037a804f3 Mon Sep 17 00:00:00 2001 From: daniel Date: Wed, 6 Feb 2019 15:58:36 +0100 Subject: [PATCH 049/249] fixed error pdf Former-commit-id: 2a81a654df0c216951c61f36ff31a05ce5f7e29a --- .../include/functions_reporting_html.php | 34 +++++++++++-------- pandora_console/include/styles/pandora.css | 27 +++++++++++++++ 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index d79afa08e8..9c9e493ba5 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -454,7 +454,7 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) if (isset($item['data'])) { $table1 = new stdClass(); $table1->width = '99%'; - $table1->class = 'content_table databox'; + $table1->align = []; $table1->align[0] = 'left'; $table1->align[1] = 'left'; @@ -479,10 +479,14 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) $table1->headstyle[4] = 'text-align: right'; $table1->headstyle[5] = 'text-align: right'; + $table1->style = []; + $table1->style[0] = 'page-break-before: always;'; + + $table1->rowstyle = []; + // Second_table for time globals. $table2 = new stdClass(); $table2->width = '99%'; - $table2->class = 'content_table'; $table2->align = []; $table2->align[0] = 'left'; @@ -514,7 +518,6 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) // Third_table for time globals. $table3 = new stdClass(); $table3->width = '99%'; - $table3->class = 'content_table'; $table3->align = []; $table3->align[0] = 'left'; @@ -645,6 +648,7 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) $row3[] = ''.$sla['checks_ok'].''; $row3[] = ''.$sla['checks_unknown'].''; + $table1->rowstyle[] = 'page-break-before: always;'; $table1->data[] = $row; $table2->data[] = $row2; $table3->data[] = $row3; @@ -675,19 +679,19 @@ function reporting_html_SLA($table, $item, $mini, $pdf=0) ); $return_pdf .= ''; - $return_pdf .= ''; - $return_pdf .= html_print_table( - $table2, - true - ); - $return_pdf .= ''; + $return_pdf .= ''; + $return_pdf .= html_print_table( + $table2, + true + ); + $return_pdf .= ''; - $return_pdf .= ''; - $return_pdf .= html_print_table( - $table3, - true - ); - $return_pdf .= ''; + $return_pdf .= ''; + $return_pdf .= html_print_table( + $table3, + true + ); + $return_pdf .= ''; } } else { $table->colspan['error']['cell'] = 3; diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index cd5a3d8eaf..9aeb40545b 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -5164,3 +5164,30 @@ input[type="submit"].ui-button-dialog { width: 90px !important; } /* --- END - JQUERY-UI --- */ + +/* + PDF STYLES +*/ + +table.header_table { + width: 100%; +} + +table.header_table thead tr th, +table.header_table tbody tr td { + padding: 10px; +} + +thead.header_tr tr { + background: #e6e6e6; +} + +thead.header_tr tr th { + font-weight: normal; + text-align: right; +} + +thead.header_tr tr th.th_first { + font-weight: bold; + text-align: left; +} From 37d02ddf59fdf04119d4176476030f1a539cf00f Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 6 Feb 2019 18:18:48 +0100 Subject: [PATCH 050/249] Added disabled status to switches Former-commit-id: 7fee49f58e4be84bfb8bad08303b203d71dafe16 --- pandora_console/include/functions_html.php | 3 ++- pandora_console/include/styles/pandora.css | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 8510b5e259..22c392e726 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -2593,9 +2593,10 @@ function html_print_switch ($attributes = array()) { $name_html = isset($attributes['name']) ? "name = {$attributes['name']}" : ''; $checked_html = (bool)$attributes['value'] ? 'checked' : ''; + $disabled_html = (bool)$attributes['disabled'] ? 'disabled' : ''; return ""; } diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 1d4e4af4c0..cc6545fc87 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -5290,4 +5290,8 @@ input:checked + .p-slider:before { transform: translateX(13px); } +input:disabled + .p-slider { + opacity: 0.4; +} + /* --- END SWITCH --- */ From 986dfcb74d04677281cb3a5712ff4f5e3062ff7a Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 6 Feb 2019 18:20:26 +0100 Subject: [PATCH 051/249] Added basic and dummy user edit notifications Former-commit-id: d0395c5b2cbc870812e54e15db523eeaac94557f --- .../include/functions_notifications.php | 92 ++++++++++++++++++- .../users/user_edit_notifications.php | 30 +++++- 2 files changed, 116 insertions(+), 6 deletions(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index ac030349ef..0f26ed977c 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -182,18 +182,37 @@ function notifications_get_all_sources() * @return array with the user id in keys and user id in value too */ function notifications_get_user_sources_for_select($source_id) +{ + $users = notifications_get_user_sources( + ['id_source' => $source_id], + ['id_user'] + ); + + return index_array($users, 'id_user', 'id_user'); +} + + +/** + * Get the user sources + * + * @param array $filter Filter of sql query. + * @param array $fields Fields to get of query. + * + * @return array Array with user sources data. + */ +function notifications_get_user_sources($filter=[], $fields=[]) { $users = db_get_all_rows_filter( 'tnotification_source_user', - ['id_source' => $source_id], - 'id_user' + $filter, + $fields ); - // If fails or no one is selected, return empty array + // If fails or no one is selected, return empty array. if ($users === false) { return []; } - return index_array($users, 'id_user', 'id_user'); + return $users; } @@ -358,6 +377,12 @@ function notifications_add_users_to_source($source_id, $users) // Insert into database all groups passed $res = true; + $also_mail = db_get_value( + 'also_mail', + 'tnotification_source', + 'id', + $source_id + ); foreach ($users as $user) { if (empty($user)) { continue; @@ -368,6 +393,8 @@ function notifications_add_users_to_source($source_id, $users) [ 'id_user' => $user, 'id_source' => $source_id, + 'enabled' => 1, + 'also_mail' => (int) $also_mail, ] ) !== false; } @@ -410,6 +437,48 @@ function notifications_get_user_source_not_configured($source_id) } +function notifications_build_user_enable_return($status, $enabled) +{ + return [ + 'status' => ((bool) $status === true) ? 1 : 0, + 'enabled' => ((bool) $enabled === true) ? 1 : 0, + ]; +} + + +function notifications_get_user_label_status($source, $user, $label) +{ + // If not enabled, it cannot be modificable. + if (!$source['enabled'] || !$source[$label]) { + return notifications_build_user_enable_return(false, false); + } + + // See at first for direct reference. + $user_source = notifications_get_user_sources( + [ + 'id_source' => $source['id'], + 'id_user' => $user, + ] + ); + if (!empty($user_source)) { + return notifications_build_user_enable_return( + isset($user_source[0][$label]) ? $user_source[0][$label] : false, + $source['user_editable'] + ); + } + + $common_groups = array_intersect( + array_keys(users_get_groups($user)), + array_keys( + notifications_get_group_sources_for_select($source['id']) + ) + ); + // No group found, return no permissions. + $value = empty($common_groups) ? false : $source[$label]; + return notifications_build_user_enable_return($value, false); +} + + /** * Print the notification ball to see unread messages * @@ -470,7 +539,7 @@ function notifications_print_global_source_configuration($source) $html_checkboxes .= __('Also email users with notification content'); $html_checkboxes .= '
'; $html_checkboxes .= html_print_checkbox("user-$id", 1, $source['user_editable'], true); - $html_checkboxes .= __('Users cannot modify notification preferences'); + $html_checkboxes .= __('Users can modify notification preferences'); $html_checkboxes .= ' '; $html_checkboxes .= ''; @@ -555,3 +624,16 @@ function notifications_print_two_ways_select($info_selec, $users, $source_id) return $html_select; } + + +function notifications_print_user_switch($source, $user, $label) +{ + $status = notifications_get_user_label_status($source, $user, $label); + return html_print_switch( + [ + 'name' => $label, + 'value' => $status['status'], + 'disabled' => !$status['enabled'], + ] + ); +} diff --git a/pandora_console/operation/users/user_edit_notifications.php b/pandora_console/operation/users/user_edit_notifications.php index edec0e2a6c..d7a4f71194 100644 --- a/pandora_console/operation/users/user_edit_notifications.php +++ b/pandora_console/operation/users/user_edit_notifications.php @@ -16,9 +16,37 @@ // Load global vars global $config; +// Includes. +include_once ($config['homedir'] . '/include/functions_notifications.php'); + // Load the header require($config['homedir'] . "/operation/users/user_edit_header.php"); -// TODO +// User notification table. It is just a wrapper. +$table_content = new StdClass(); +$table_content->data = array(); +$table_content->width = '100%'; +$table_content->id = 'user-notifications-wrapper'; +$table_content->class = 'databox filters'; +$table_content->size[0] = '33%'; +$table_content->size[1] = '33%'; +$table_content->size[2] = '33%'; + +// Print the header. +$table_content->data[] = array ( + '', + __('Enable'), + __('Also receive an email') +); + +$sources = notifications_get_all_sources(); +foreach ($sources as $source) { + $table_content->data[] = array( + $source['description'], + notifications_print_user_switch($source, $id, 'enabled'), + notifications_print_user_switch($source, $id, 'also_mail'), + ); +} +html_print_table($table_content); ?> \ No newline at end of file From 9ea3980b2666554dabf350710e4ca62aeb8b48f1 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 6 Feb 2019 20:22:22 +0100 Subject: [PATCH 052/249] wip supervisor Former-commit-id: 991922a7dd18ace8fd831d02ada2cf20e81d27c2 --- .../include/functions_notifications.php | 64 ++++++++++++++++++- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index ac030349ef..c8f46d90ae 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -1,5 +1,4 @@ Date: Thu, 7 Feb 2019 12:20:34 +0100 Subject: [PATCH 053/249] Added more attributes to swith HTML element Former-commit-id: aa567ef6f16e1e89489b16f808b00e772866ef86 --- pandora_console/include/functions_html.php | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 22c392e726..0db0b371cb 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -2587,16 +2587,27 @@ function html_print_csrf_error () { * @param array $atributes. Valid params: * name: Usefull to handle in forms * value: If is checked or not + * disabled: Disabled. Cannot be pressed. + * id: Optional id for the switch. + * class: Additional classes (string). * @return string with HTML of button */ function html_print_switch ($attributes = array()) { + $html_expand = ''; - $name_html = isset($attributes['name']) ? "name = {$attributes['name']}" : ''; - $checked_html = (bool)$attributes['value'] ? 'checked' : ''; - $disabled_html = (bool)$attributes['disabled'] ? 'disabled' : ''; + // Check the load values on status. + $html_expand .= (bool)$attributes['value'] ? ' checked' : ''; + $html_expand .= (bool)$attributes['disabled'] ? ' disabled' : ''; + + // Only load the valid attributes. + $valid_attrs = ['id', 'class', 'name']; + foreach ($valid_attrs as $va) { + if (!isset($attributes[$va])) continue; + $html_expand .= ' '.$va.'="'.$attributes[$va].'"'; + } return ""; } From d5fb9f1051818a6a3edc389b2593f852882d60f7 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 7 Feb 2019 12:22:50 +0100 Subject: [PATCH 054/249] Added AJAX to user notification config window Former-commit-id: 9ca09ae777d699588a76dfb619156d800a95895b --- .../include/functions_notifications.php | 27 +++++- .../users/user_edit_notifications.php | 92 ++++++++++++++++--- 2 files changed, 106 insertions(+), 13 deletions(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 0f26ed977c..9037e9790f 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -168,9 +168,9 @@ function check_notification_readable(int $id_message) * * @return array with sources info */ -function notifications_get_all_sources() +function notifications_get_all_sources($filter=[]) { - return db_get_all_rows_in_table('tnotification_source'); + return db_get_all_rows_filter('tnotification_source', $filter); } @@ -478,6 +478,27 @@ function notifications_get_user_label_status($source, $user, $label) return notifications_build_user_enable_return($value, false); } +function notifications_set_user_label_status($source, $user, $label, $value) { + $source_info = notifications_get_all_sources(['id' => $source]); + if (!isset($source_info[0]) + || !$source_info[0]['enabled'] + || !$source_info[0][$label] + || !$source_info[0]['user_editable'] + ) { + return false; + } + + return (bool) db_process_sql_update( + 'tnotification_source_user', + [$label => $value], + [ + 'id_user' => $user, + 'id_source' => $source, + ] + ); + +} + /** * Print the notification ball to see unread messages @@ -634,6 +655,8 @@ function notifications_print_user_switch($source, $user, $label) 'name' => $label, 'value' => $status['status'], 'disabled' => !$status['enabled'], + 'class' => 'notifications-user-label_individual', + 'id' => 'notifications-user-'.$source['id'].'-label-'.$label, ] ); } diff --git a/pandora_console/operation/users/user_edit_notifications.php b/pandora_console/operation/users/user_edit_notifications.php index d7a4f71194..6ffbf87976 100644 --- a/pandora_console/operation/users/user_edit_notifications.php +++ b/pandora_console/operation/users/user_edit_notifications.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,19 +11,39 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; // Includes. -include_once ($config['homedir'] . '/include/functions_notifications.php'); +require_once $config['homedir'].'/include/functions_notifications.php'; // Load the header -require($config['homedir'] . "/operation/users/user_edit_header.php"); +require $config['homedir'].'/operation/users/user_edit_header.php'; + +if (get_parameter('change_label', 0)) { + $label = get_parameter('label', ''); + $source = get_parameter('source', 0); + $user = get_parameter('user', ''); + $value = get_parameter('value', 0) ? 1 : 0; + + // Update the label value. + ob_clean(); + echo json_encode( + [ + 'result' => notifications_set_user_label_status( + $source, + $user, + $label, + $value + ), + ] + ); + return; +} // User notification table. It is just a wrapper. $table_content = new StdClass(); -$table_content->data = array(); +$table_content->data = []; $table_content->width = '100%'; $table_content->id = 'user-notifications-wrapper'; $table_content->class = 'databox filters'; @@ -33,20 +52,71 @@ $table_content->size[1] = '33%'; $table_content->size[2] = '33%'; // Print the header. -$table_content->data[] = array ( +$table_content->data[] = [ '', __('Enable'), - __('Also receive an email') -); + __('Also receive an email'), +]; $sources = notifications_get_all_sources(); foreach ($sources as $source) { - $table_content->data[] = array( + $table_content->data[] = [ $source['description'], notifications_print_user_switch($source, $id, 'enabled'), notifications_print_user_switch($source, $id, 'also_mail'), - ); + ]; } + html_print_table($table_content); -?> \ No newline at end of file +// Print id user to handle it on js. +html_print_input_hidden('id_user', $id); + +?> + From cf5716e569d2f9c9637eb03ec5dde43c4ad63b48 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 7 Feb 2019 12:56:48 +0100 Subject: [PATCH 055/249] supervisor added subtype to tmensajes Former-commit-id: 650e7317a4fea4e44be850af1156024297396a16 --- .../extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 15 ++++++++------- pandora_console/pandoradb.sql | 1 + pandora_console/pandoradb_data.sql | 15 +++++++-------- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 482fcb8f4e..ce015f9149 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1886,13 +1886,13 @@ CREATE TABLE `tnotification_source` ( -- -- Dumping data for table `tnotification_source` -- -INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, `user_editable`, `also_mail`) VALUES - ("System status", "icono_info_mr.png", 86400, 1, 0), - ("Message", "icono_info_mr.png", 86400, 1, 0), - ("Pending task", "icono_info_mr.png", 86400, 1, 0), - ("Advertisement", "icono_info_mr.png", 86400, 1, 0), - ("Official communication", "icono_info_mr.png", 86400, 1, 0), - ("Sugerence", "icono_info_mr.png", 86400, 1, 0); +INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, `enabled`, `user_editable`, `also_mail`) VALUES + ("System status", "icono_info_mr.png", 86400, 1, 1, 0), + ("Message", "icono_info_mr.png", 86400, 1, 1, 0), + ("Pending task", "icono_info_mr.png", 86400, 1, 1, 0), + ("Advertisement", "icono_info_mr.png", 86400, 1, 1, 0), + ("Official communication", "icono_info_mr.png", 86400, 1, 1, 0), + ("Sugerence", "icono_info_mr.png", 86400, 1, 1, 0); -- ----------------------------------------------------- -- Table `tmensajes` @@ -1901,6 +1901,7 @@ ALTER TABLE `tmensajes` ADD COLUMN `url` TEXT; ALTER TABLE `tmensajes` ADD COLUMN `response_mode` VARCHAR(200) DEFAULT NULL; ALTER TABLE `tmensajes` ADD COLUMN `citicity` INT(10) UNSIGNED DEFAULT '0'; ALTER TABLE `tmensajes` ADD COLUMN `id_source` BIGINT(20) UNSIGNED NOT NULL; +ALTER TABLE `tmensajes` ADD COLUMN `subtype` VARCHAR(255) DEFAULT ''; ALTER TABLE `tmensajes` ADD CONSTRAINT `tsource_fk` FOREIGN KEY (`id_source`) REFERENCES `tnotification_source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index daae31bf5d..5af9d38c55 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -1191,6 +1191,7 @@ CREATE TABLE IF NOT EXISTS `tmensajes` ( `response_mode` VARCHAR(200) DEFAULT NULL, `citicity` INT(10) UNSIGNED DEFAULT '0', `id_source` BIGINT(20) UNSIGNED NOT NULL, + `subtype` VARCHAR(255) DEFAULT '', PRIMARY KEY (`id_mensaje`), UNIQUE KEY `id_mensaje` (`id_mensaje`), KEY `tsource_fk` (`id_source`), diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index e803c83d82..f73ab0af68 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1271,11 +1271,10 @@ INSERT INTO tlog_graph_models VALUES (1, 'Apache log model', -- -- Dumping data for table `tnotification_source` -- -INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, `user_editable`, `also_mail`) VALUES - ("System status", "icono_info_mr.png", 86400, 1, 0), - ("Message", "icono_info_mr.png", 86400, 1, 0), - ("Pending task", "icono_info_mr.png", 86400, 1, 0), - ("Advertisement", "icono_info_mr.png", 86400, 1, 0), - ("Official communication", "icono_info_mr.png", 86400, 1, 0), - ("Sugerence", "icono_info_mr.png", 86400, 1, 0); - +INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, `enabled`, `user_editable`, `also_mail`) VALUES + ("System status", "icono_info_mr.png", 86400, 1, 1, 0), + ("Message", "icono_info_mr.png", 86400, 1, 1, 0), + ("Pending task", "icono_info_mr.png", 86400, 1, 1, 0), + ("Advertisement", "icono_info_mr.png", 86400, 1, 1, 0), + ("Official communication", "icono_info_mr.png", 86400, 1, 1, 0), + ("Sugerence", "icono_info_mr.png", 86400, 1, 1, 0); From fb814680db32f7bdd9257583fca070d677c3704d Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 7 Feb 2019 12:57:51 +0100 Subject: [PATCH 056/249] Added some well formatted docs Former-commit-id: 30aa9de2e1b3835f96adf2fbec24bfd5ab17e7c2 --- .../include/functions_notifications.php | 100 +++++++++++++----- 1 file changed, 75 insertions(+), 25 deletions(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 9037e9790f..5c232709de 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -166,6 +166,8 @@ function check_notification_readable(int $id_message) /** * Return all info from tnotification_source * + * @param array $filter Filter to table tnotification_source. + * * @return array with sources info */ function notifications_get_all_sources($filter=[]) @@ -177,7 +179,7 @@ function notifications_get_all_sources($filter=[]) /** * Return the user sources to be inserted into a select * - * @param integer $source_id Source database identificator + * @param integer $source_id Source database identificator. * * @return array with the user id in keys and user id in value too */ @@ -219,7 +221,7 @@ function notifications_get_user_sources($filter=[], $fields=[]) /** * Return the groups sources to be inserted into a select * - * @param integer $source_id Source database identificator + * @param integer $source_id Source database identificator. * * @return array with the group id in keys and group name in value */ @@ -237,6 +239,9 @@ function notifications_get_group_sources_for_select($source_id) * Get the group sources * * @param array $filter Filter of sql query. + * @param array $fields Fields retrieved. + * + * @return array With the group info */ function notifications_get_group_sources($filter=[], $fields=[]) { @@ -276,8 +281,8 @@ function notifications_get_group_sources($filter=[], $fields=[]) /** * Delete a set of groups from notification source * - * @param int Source id - * @param array Id of groups to be deleted + * @param integer $source_id Source id. + * @param array $groups Id of groups to be deleted. * * @return boolean True if success. False otherwise. */ @@ -302,8 +307,8 @@ function notifications_remove_group_from_source($source_id, $groups) /** * Delete a set of users from notification source * - * @param int Source id - * @param array Id of users to be deleted + * @param integer $source_id Source id. + * @param array $users Id of users to be deleted. * * @return boolean True if success. False otherwise. */ @@ -328,8 +333,8 @@ function notifications_remove_users_from_source($source_id, $users) /** * Insert a set of groups to notification source * - * @param int Source id - * @param array Id of groups to be deleted + * @param integer $source_id Source id. + * @param array $groups Id of groups to be deleted. * * @return boolean True if success. False otherwise. */ @@ -363,8 +368,8 @@ function notifications_add_group_to_source($source_id, $groups) /** * Insert a set of users to notification source * - * @param int Source id - * @param array Id of users to be deleted + * @param integer $source_id Source id. + * @param array $users Id of users to be deleted. * * @return boolean True if success. False otherwise. */ @@ -407,7 +412,8 @@ function notifications_add_users_to_source($source_id, $users) * Get the groups that not own to a source and, for that reason, they can be * added to the source. * - * @param integer $source_id Source id. + * @param integer $source_id Source id. + * * @return array Indexed by id group all selectable groups. */ function notifications_get_group_source_not_configured($source_id) @@ -422,7 +428,8 @@ function notifications_get_group_source_not_configured($source_id) * Get the users that not own to a source and, for that reason, they can be * added to the source. * - * @param integer $source_id + * @param integer $source_id Source id. + * * @return array Indexed by id user, all selectable users. */ function notifications_get_user_source_not_configured($source_id) @@ -437,6 +444,14 @@ function notifications_get_user_source_not_configured($source_id) } +/** + * Build a data struct to handle the value of a label + * + * @param mixed $status Status value. + * @param mixed $enabled Enabled value. + * + * @return array with status (1|0) and enabled (1|0) + */ function notifications_build_user_enable_return($status, $enabled) { return [ @@ -446,6 +461,15 @@ function notifications_build_user_enable_return($status, $enabled) } +/** + * Get user label (enabled, also_mail...) status. + * + * @param integer $source Id of notification source. + * @param string $user User id. + * @param string $label Label id (enabled, also_email...). + * + * @return array Return of notifications_build_user_enable_return. + */ function notifications_get_user_label_status($source, $user, $label) { // If not enabled, it cannot be modificable. @@ -478,7 +502,19 @@ function notifications_get_user_label_status($source, $user, $label) return notifications_build_user_enable_return($value, false); } -function notifications_set_user_label_status($source, $user, $label, $value) { + +/** + * Set the status to a single label on config of users notifications. + * + * @param integer $source Id of notification source. + * @param string $user User id. + * @param string $label Label id (enabled, also_email...). + * @param mixed $value Numeric value: 1 or 0. + * + * @return boolean True if success. + */ +function notifications_set_user_label_status($source, $user, $label, $value) +{ $source_info = notifications_get_all_sources(['id' => $source]); if (!isset($source_info[0]) || !$source_info[0]['enabled'] @@ -501,9 +537,9 @@ function notifications_set_user_label_status($source, $user, $label, $value) { /** - * Print the notification ball to see unread messages + * Print the notification ball to see unread messages. * - * @return string with HTML code of notification ball + * @return string with HTML code of notification ball. */ function notifications_print_ball() { @@ -518,7 +554,7 @@ function notifications_print_ball() /** * Print notification configuration global * - * @param array notification source data + * @param array $source Notification source data. * * @return string with HTML of source configuration */ @@ -593,15 +629,19 @@ function notifications_print_global_source_configuration($source) /** * Print select boxes of notified users or groups * - * @param array $info_selec All info required for build the selector - * @param string $id users|groups - * @param string $source_id Id of source - * @param boolean $disabled Disable the selectors + * @param array $info_selec All info required for build the selector. + * @param string $id One of users|groups. + * @param string $source_id Id of source. + * @param boolean $disabled Disable the selectors. * * @return string HTML with the generated selector */ -function notifications_print_source_select_box($info_selec, $id, $source_id, $disabled) -{ +function notifications_print_source_select_box( + $info_selec, + $id, + $source_id, + $disabled +) { $title = $id == 'users' ? __('Notified users') : __('Notified groups'); $add_title = $id == 'users' ? __('Add users') : __('Add groups'); $delete_title = $id == 'users' ? __('Delete users') : __('Delete groups'); @@ -626,9 +666,10 @@ function notifications_print_source_select_box($info_selec, $id, $source_id, $di * Print the select with right and left arrows to select new sources * (groups or users). * - * @param array $info_selec Array with source info. - * @param string $users users|groups. - * @param source $source_id Source id. + * @param array $info_selec Array with source info. + * @param string $users One of users|groups. + * @param source $source_id Source id. + * * @return string HTML with the select code. */ function notifications_print_two_ways_select($info_selec, $users, $source_id) @@ -647,6 +688,15 @@ function notifications_print_two_ways_select($info_selec, $users, $source_id) } +/** + * Print a label status represented by a switch + * + * @param integer $source Source id. + * @param string $user User id. + * @param string $label Label (enabled, also_mail...). + * + * @return string With HTML code + */ function notifications_print_user_switch($source, $user, $label) { $status = notifications_get_user_label_status($source, $user, $label); From dc9decde422ad82a123e8b82b70530f4ab2b8d86 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 7 Feb 2019 16:24:49 +0100 Subject: [PATCH 057/249] ConsoleSupervisor Former-commit-id: 3c40e628883f032a449862d0161659586819e6df --- .../include/class/ConsoleSupervisor.php | 2013 +++++++ pandora_console/include/functions_config.php | 5013 +++++++++-------- 2 files changed, 4725 insertions(+), 2301 deletions(-) create mode 100644 pandora_console/include/class/ConsoleSupervisor.php diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php new file mode 100644 index 0000000000..3eaedcfcfb --- /dev/null +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -0,0 +1,2013 @@ +verbose = $verbose; + + if ($source === false) { + $this->enabled = false; + $this->sourceId = null; + + $this->targetGroups = null; + $this->targetUsers = null; + } else { + $this->enabled = (bool) $source['enabled']; + $this->sourceId = $source['id']; + + // Assign targets. + $targets = get_notification_source_targets($this->sourceId); + $this->targetGroups = $targets['groups']; + $this->targetUsers = $targets['users']; + $this->targetUpdated = true; + } + + return $this; + } + + + /** + * Warn a message. + * + * @param string $msg Message. + * + * @return void + */ + public function warn(string $msg) + { + if ($this->verbose === true) { + echo date('M j G:i:s').' ConsoleSupervisor: '.$msg."\n"; + } + } + + + /** + * Manage scheduled tasks. + * + * @return void + */ + public function run() + { + global $config; + + if ($this->enabled === false) { + // Feature not enabled. + return; + } + + if ($this->sourceId === null) { + // Source not detected. + return; + } + + if ($this->verbose === true) { + if (enterprise_hook('cron_supervisor_lock') === false) { + // Cannot continue. Locked. + exit; + } + } + + // Enterprise support. + if (file_exists($config['homedir'].'/'.ENTERPRISE_DIR.'/load_enterprise.php')) { + include_once $config['homedir'].'/'.ENTERPRISE_DIR.'/load_enterprise.php'; + } + + $time = get_system_time(); + $scheduled_tasks = db_get_all_rows_in_table('tuser_task_scheduled'); + if (!$scheduled_tasks) { + $scheduled_tasks = []; + } + + // Automatic checks launched by supervisor. + $this->warn('running.'); + + /* + * Check license. + * NOTIF.LICENSE.EXPIRATION + */ + + $this->checkLicense(); + + /* + * Check number of files in attachment: + * NOTIF.FILES.ATTACHMENT + */ + + $this->checkAttachment(); + + /* + * Files in data_in: + * NOTIF.FILES.DATAIN (>1000) + * NOTIF.FILES.DATAIN.BADXML (>150) + */ + + $this->checkDataIn(); + + /* + * Check module queues not growing: + * NOTIF.SERVER.QUEUE.ID_SERVER + */ + + $this->checkServers(); + + /* + * Check component statuses (servers down - frozen). + * NOTIF.SERVER.STATUS.ID_SERVER + */ + + $this->checkPandoraServers(); + + /* + * Check at least 1 server running in master mode. + * NOTIF.SERVER.MASTER + */ + + $this->checkPandoraServerMasterAvailable(); + + /* + * PHP configuration warnings: + * NOTIF.PHP.SAFE_MODE + * NOTIF.PHP.INPUT_TIME + * NOTIF.PHP.EXECUTION_TIME + * NOTIF.PHP.UPLOAD_MAX_FILESIZE + * NOTIF.PHP.MEMORY_LIMIT + * NOTIF.PHP.DISABLE_FUNCTIONS + * NOTIF.PHP.PHANTOMJS + * NOTIF.PHP.VERSION + */ + + $this->checkPHPSettings(); + + /* + * Check connection with historical DB (if enabled). + * NOTIF.HISTORYDB + */ + + $this->checkPandoraHistoryDB(); + + /* + * Check pandoradb running in main DB. + * Check pandoradb running in historical DB. + * NOTIF.PANDORADB + * NOTIF.PANDORADB.HISTORICAL + */ + + $this->checkPandoraDBMaintenance(); + + /* + * Check historical DB MR version. + * NOTIF.HISTORYDB.MR + */ + + $this->checkPandoraHistoryDBMR(); + + /* + * Check external components. + * NOTIF.EXT.ELASTICSEARCH + * NOTIF.EXT.LOGSTASH + * + */ + + $this->checkExternalComponents(); + + /* + * Check Metaconsole synchronization issues. + * NOTIF.METACONSOLE.DB_CONNECTION + */ + + $this->checkMetaconsole(); + + /* + * Check incoming scheduled downtimes (< 15d). + * NOTIF.DOWNTIME + */ + + $this->checkDowntimes(); + + /* + * Check if instance is registered. + * NOTIF.UPDATEMANAGER.REGISTRATION + */ + + $this->checkUpdateManagerRegistration(); + + /* + * Check if event storm protection is activated. + * NOTIF.MISC.EVENTSTORMPROTECTION + */ + + $this->checkEventStormProtection(); + + /* + * Check if develop_bypass is enabled. + * NOTIF.MISC.DEVELOPBYPASS + */ + + $this->checkDevelopBypass(); + + /* + * Check if fontpath exists. + * NOTIF.MISC.FONTPATH + */ + + $this->checkFont(); + + /* + * Check if default user and password exists. + * NOTIF.SECURITY.DEFAULT_PASSWORD + */ + + $this->checkDefaultPassword(); + + /* + * Check if there's an active subscription. + * NOTIF.NEWSLETTER.SUBSCRIPTION + */ + + $this->checkNewsletterSubscription(); + + /* + * Check if there're new updates. + * NOTIF.UPDATEMANAGER.OPENSETUP + * NOTIF.UPDATEMANAGER.UPDATE + */ + + $this->checkUpdates(); + + if ($this->verbose === true) { + // Release the lock. + enterprise_hook('cron_supervisor_release_lock'); + } + + } + + + /** + * Update targets for given notification using object targets. + * + * @param integer $notification_id Current notification. + * + * @return void + */ + public function updateTargets(int $notification_id) + { + if (is_array($this->targetUsers) === true + && count($this->targetUsers) > 0 + ) { + // Process user targets. + $insertion_string = ''; + $users_sql = 'INSERT INTO tnotification_user(id_mensaje,id_user)'; + foreach ($this->targetUsers as $user) { + $insertion_string .= sprintf( + '(%d,"%s")', + $notification_id, + $user['id_user'] + ); + $insertion_string .= ','; + + // Send mail. + if (isset($user['also_mail']) && $user['also_mail'] == 1) { + $this->warn('Mailing user: '.$user['id_user']."\n"); + // TODO: Add sendmail sequence. + } + } + + $insertion_string = substr($insertion_string, 0, -1); + + db_process_sql($users_sql.' VALUES '.$insertion_string); + } + + if (is_array($this->targetGroups) === true + && count($this->targetGroups) > 0 + ) { + // Process group targets. + $insertion_string = ''; + $groups_sql = 'INSERT INTO tnotification_group(id_mensaje,id_group)'; + foreach ($this->targetGroups as $group) { + $insertion_string .= sprintf( + '(%d,"%s")', + $notification_id, + $group['id_group'] + ); + $insertion_string .= ','; + + // Send mail. + if (isset($group['also_mail']) && $group['also_mail'] == 1) { + $this->warn('Mailing group: '.$group['id_group']."\n"); + // TODO: Add sendmail sequence. + } + } + + $insertion_string = substr($insertion_string, 0, -1); + + db_process_sql($groups_sql.' VALUES '.$insertion_string); + } + + } + + + /** + * Generates notifications for target users and groups. + * + * @param array $data Message to be delivered: + * - boolean status (false: notify, true: do not notify) + * - string title + * - string message + * - string url. + * @param integer $source_id Target source_id, by default $this->sourceId. + * @param integer $max_age Maximum age for generated notification. + * + * @return void + */ + public function notify( + array $data, + int $source_id=0, + int $max_age=86400 + ) { + // Uses 'check failed' logic. + if (is_array($data) === false) { + // Skip. + return; + } + + if ($this->targetUpdated === false) { + $targets = get_notification_source_targets($this->sourceId); + $this->targetGroups = $targets['groups']; + $this->targetUsers = $targets['users']; + $this->targetUpdated = false; + } + + if ($source_id === 0) { + $source_id = $this->sourceId; + // Assign targets. + $targets = get_notification_source_targets($source_id); + $this->targetGroups = $targets['groups']; + $this->targetUsers = $targets['users']; + $this->targetUpdated = false; + } + + switch ($data['type']) { + case 'NOTIF.LICENSE.EXPIRATION': + case 'NOTIF.FILES.ATTACHMENT': + case 'NOTIF.FILES.DATAIN': + case 'NOTIF.FILES.DATAIN.BADXML': + case 'NOTIF.PHP.SAFE_MODE': + case 'NOTIF.PHP.INPUT_TIME': + case 'NOTIF.PHP.EXECUTION_TIME': + case 'NOTIF.PHP.UPLOAD_MAX_FILESIZE': + case 'NOTIF.PHP.MEMORY_LIMIT': + case 'NOTIF.PHP.DISABLE_FUNCTIONS': + case 'NOTIF.PHP.PHANTOMJS': + case 'NOTIF.PHP.VERSION': + case 'NOTIF.HISTORYDB': + case 'NOTIF.PANDORADB': + case 'NOTIF.PANDORADB.HISTORICAL': + case 'NOTIF.HISTORYDB.MR': + case 'NOTIF.EXT.ELASTICSEARCH': + case 'NOTIF.EXT.LOGSTASH': + case 'NOTIF.METACONSOLE.DB_CONNECTION': + case 'NOTIF.DOWNTIME': + case 'NOTIF.UPDATEMANAGER.REGISTRATION': + case 'NOTIF.MISC.EVENTSTORMPROTECTION': + case 'NOTIF.MISC.DEVELOPBYPASS': + case 'NOTIF.MISC.FONTPATH': + case 'NOTIF.SECURITY.DEFAULT_PASSWORD': + case 'NOTIF.NEWSLETTER.SUBSCRIPTION': + case 'NOTIF.UPDATEMANAGER.OPENSETUP': + case 'NOTIF.UPDATEMANAGER.UPDATE': + + default: + // NOTIF.SERVER.STATUS. + // NOTIF.SERVER.STATUS.ID_SERVER. + // NOTIF.SERVER.QUEUE.ID_SERVER. + // NOTIF.SERVER.MASTER. + // NOTIF.SERVER.STATUS.ID_SERVER. + if (preg_match('/^NOTIF.SERVER/', $data['type']) === true) { + // Component notifications require be inmediate. + $max_age = 0; + } + + // Else ignored. + break; + } + + // Get previous notification. + $prev = db_get_row( + 'tmensajes', + 'subtype', + $data['type'] + ); + + if ($prev !== false + && (time() - $prev['timestamp']) > $max_age + ) { + // Clean previous notification. + $this->cleanNotifications($data['type']); + } else if ($prev !== false) { + // Avoid creation. Previous notification is still valid. + // Update message with latest information. + $r = db_process_sql_update( + 'tmensajes', + [ + 'mensaje' => io_safe_input($data['message']), + 'subject' => io_safe_input($data['title']), + ], + ['id_mensaje' => $prev['id_mensaje']] + ); + + $this->updateTargets($prev['id_mensaje']); + return; + } + + if (isset($data['type']) === false) { + $data['type'] = ''; + } + + // Create notification. + $notification = []; + $notification['timestamp'] = time(); + $notification['id_source'] = $source_id; + $notification['mensaje'] = io_safe_input($data['message']); + $notification['subject'] = io_safe_input($data['title']); + $notification['subtype'] = $data['type']; + $notification['url'] = io_safe_input($data['url']); + + $id = db_process_sql_insert('tmensajes', $notification); + + if ($id === false) { + // Failed to generate notification. + $this->warn('Failed to generate notification'); + return; + } + + $this->updateTargets($id); + + } + + + /** + * Deletes useless notifications. + * + * @param string $subtype Subtype to be deleted. + * + * @return mixed False in case of error or invalid values passed. + * Affected rows otherwise + */ + public function cleanNotifications(string $subtype) + { + $not_count = db_get_value_sql( + sprintf( + 'SELECT count(*) as n + FROM tmensajes + WHERE subtype like "%s"', + $subtype + ) + ); + + if ($not_count > 0) { + return db_process_sql_delete( + 'tmensajes', + sprintf('subtype like "%s"', $subtype) + ); + } + + return true; + } + + + /** + * Check license status and validity. + * + * @return boolean Return true if license is valid, false if not. + */ + public function checkLicense() + { + global $config; + + $license = enterprise_hook('license_get_info'); + if ($license === ENTERPRISE_NOT_HOOK) { + return false; + } + + $days_to_expiry = ((strtotime($license['expiry_date']) - time()) / (60 * 60 * 24)); + + if (($days_to_expiry <= 15) && ($days_to_expiry > 0)) { + // Warn user if license is going to expire in 15 days or less. + $this->notify( + [ + 'type' => 'NOTIF.LICENSE_EXPIRATION', + 'title' => __('License is going to expire.'), + 'message' => __( + 'Your license is going to expire in %d days. Please contact sales.', + $days_to_expiry + ), + 'url' => ui_get_full_url( + 'index.php?sec=gsetup&sec2=godmode/setup/license' + ), + ] + ); + } else if ($days_to_expiry < 0) { + // Warn user, license has expired. + $this->notify( + [ + 'type' => 'NOTIF.LICENSE.EXPIRATION', + 'title' => __('License is expired.'), + 'message' => __('Your license has expired. Please contact sales.'), + 'url' => ui_get_full_url( + 'index.php?sec=gsetup&sec2=godmode/setup/license' + ), + ] + ); + return false; + } else { + $this->cleanNotifications('NOTIF.LICENSE.EXPIRATION'); + } + + return true; + + } + + + /** + * Count files in target path. + * + * @param string $path Path to be checked. + * @param string $regex Regular expression to find files. + * @param integer $max_files Maximum number of files to find. + * + * @return integer Number of files in target path. + */ + public function countFiles( + string $path='', + string $regex='', + int $max_files=500 + ) { + if (empty($path) === true) { + return -1; + } + + $nitems = 0; + + // Count files up to max_files. + $dir = opendir($path); + + if ($dir !== false) { + // Used instead of glob to avoid check directories with + // more than 1M files. + while (false !== ($file = readdir($dir)) && $nitems <= $max_files) { + if ($file != '.' && $file != '..') { + if (empty($regex) === false) { + if (preg_match($regex, $file) !== 1) { + $nitems++; + continue; + } + } + + $nitems++; + } + } + + closedir($dir); + } + + return $nitems; + } + + + /** + * Check excesive files in attachment directory. + * + * @return void + */ + public function checkAttachment() + { + global $config; + + if (is_writable($config['attachment_store']) !== true) { + $this->notify( + [ + 'type' => 'NOTIF.WRITABLE.ATTACHMENT', + 'title' => __('Attachment directory is not writable.'), + 'message' => __( + 'Directory %s is not writable. Please configure proper permissions.', + $config['attachment_store'] + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' + ), + ] + ); + return; + } else { + $this->cleanNotifications('NOTIF.WRITABLE.ATTACHMENT'); + } + + $filecount = $this->countFiles( + $config['attachment_store'], + '', + $config['num_files_attachment'] + ); + if ($filecount > $config['num_files_attachment']) { + $this->notify( + [ + 'type' => 'NOTIF.FILES.ATTACHMENT', + 'title' => __('There are too much files in attachment directory.'), + 'message' => __( + 'There are more than %d files in attachment, you should consider cleaning up your attachment directory manually.', + $config['num_files_attachment'] + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.FILES.ATTACHMENT'); + } + + } + + + /** + * Check excesive files in data_in directory. + * + * @return void + */ + public function checkDataIn() + { + global $config; + + if (enterprise_installed() + && isset($config['license_nms']) + && $config['license_nms'] != 1 + ) { + if (is_readable($config['remote_config']) !== true) { + $this->notify( + [ + 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG', + 'title' => __('Remote configuration directory is not readable.'), + 'message' => __( + 'Remote configuration directory %s is not readable. Please configure it.', + $config['remote_config'] + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' + ), + ] + ); + return; + } else { + $this->cleanNotifications( + 'NOTIF.PERMISSIONS.REMOTE_CONFIG' + ); + } + + if (is_writable($config['remote_config'].'/conf') !== true) { + $this->notify( + [ + 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG.CONF', + 'title' => __('Remote configuration directory is not writable.'), + 'message' => __( + 'Remote configuration directory %s is not writable. Please configure it.', + $config['remote_config'].'/conf' + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' + ), + ] + ); + } else { + $this->cleanNotifications( + 'NOTIF.PERMISSIONS.REMOTE_CONFIG.CONF' + ); + } + + if (is_writable($config['remote_config'].'/collections') !== true) { + $this->notify( + [ + 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG.COLLECTIONS', + 'title' => __('Remote collections directory is not writable.'), + 'message' => __( + 'Collections directory %s is not writable. Please configure it.', + $config['remote_config'].'/collections' + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' + ), + ] + ); + } else { + $this->cleanNotifications( + 'NOTIF.PERMISSIONS.REMOTE_CONFIG.COLLECTIONS' + ); + } + + if (is_writable($config['remote_config'].'/md5') !== true) { + $this->notify( + [ + 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG.MD5', + 'title' => __('Remote md5 directory is not writable.'), + 'message' => __( + 'MD5 directory %s is not writable. Please configure it.', + $config['remote_config'].'/md5' + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' + ), + ] + ); + } else { + $this->cleanNotifications( + 'NOTIF.PERMISSIONS.REMOTE_CONFIG.MD5' + ); + } + } else { + $this->cleanNotifications('NOTIF.PERMISSIONS.REMOTE_CONF%'); + } + + $MAX_FILES_DATA_IN = 1000; + $MAX_BADXML_FILES_DATA_IN = 150; + + $filecount = $this->countFiles( + $config['remote_config'], + '', + $MAX_FILES_DATA_IN + ); + // If cannot open directory, count is '-1', skip. + if ($filecount > $MAX_FILES_DATA_IN) { + $this->notify( + [ + 'type' => 'NOTIF.FILES.DATAIN', + 'title' => __('There are too much files in spool').'.', + 'message' => __( + 'There are more than %d files in %s, you should consider checking DataServer performance', + $MAX_FILES_DATA_IN, + $config['remote_config'] + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.FILES.DATAIN'); + } + + $filecount = $this->countFiles( + $config['remote_config'], + '/.*BADXML/', + $MAX_BADXML_FILES_DATA_IN + ); + // If cannot open directory, count is '-1', skip. + if ($filecount > $MAX_BADXML_FILES_DATA_IN) { + $this->notify( + [ + 'type' => 'NOTIF.FILES.DATAIN.BADXML', + 'title' => __('There are too much BADXML files in spool.'), + 'message' => __( + 'There are more than %d files in %s, you should consider checking software agents.', + $MAX_BADXML_FILES_DATA_IN, + $config['remote_config'] + ), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.FILES.DATAIN.BADXML'); + } + } + + + /** + * Check growing queues in servers. + * + * @return void + */ + public function checkServers() + { + global $config; + + $idx_file = $config['attachment_store'].'/.cron.supervisor.servers.idx'; + + $MAX_QUEUE = 1500; + $MAX_GROWN = 50; + + $queue_state = []; + $previous = []; + $new = []; + + if (file_exists($idx_file) === true) { + // Read previous values from file. + $previous = json_decode(file_get_contents($idx_file), true); + } + + // DataServer queue status. + $queue_state = db_get_all_rows_sql( + 'SELECT id_server,name,server_type,queued_modules,status + FROM tserver ORDER BY 1' + ); + + $time = time(); + foreach ($queue_state as $queue) { + $key = $queue['id_server']; + $type = $queue['server_type']; + $new_data[$key] = $queue['queued_modules']; + + // Compare queue increments in a not over 900 seconds. + if (empty($previous[$key]['modules']) + || ($time - $previous[$key]['utime']) > 900 + ) { + $previous[$key]['modules'] = 0; + } + + $modules_queued = ($queue['queued_modules'] - $previous[$key]['modules']); + + // 50 Modules queued since last check. Or more than 1500 queued. + if ($modules_queued > $MAX_GROWN + || $queue['queued_modules'] > $MAX_QUEUE + ) { + $msg = 'Queue has grown %d modules. Total %d'; + if ($modules_queued <= 0) { + $msg = 'Queue is decreasing in %d modules. But there are %d queued.'; + $modules_queued *= -1; + } + + $this->notify( + [ + 'type' => 'NOTIF.SERVER.QUEUE.'.$key, + 'title' => __( + '%s (%s) performance is being lacked.', + servers_get_server_string_name($type), + $queue['name'] + ), + 'message' => __( + $msg, + $modules_queued, + $queue['queued_modules'] + ), + 'url' => ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.SERVER.QUEUE.'.$key); + } + + $new[$key]['modules'] = $queue['queued_modules']; + $new[$key]['utime'] = $time; + } + + file_put_contents($idx_file, json_encode($new)); + } + + + /** + * Check Pandora component statuses. + * + * @return void + */ + public function checkPandoraServers() + { + $servers = db_get_all_rows_sql( + 'SELECT + id_server, + name, + server_type, + status, + unix_timestamp() - unix_timestamp(keepalive) as downtime + FROM tserver + WHERE + unix_timestamp() - unix_timestamp(keepalive) > server_keepalive + OR status = 0' + ); + + if ($servers === false) { + $nservers = db_get_value_sql( + 'SELECT count(*) as nservers + FROM tserver' + ); + if ($nservers == 0) { + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_en:Configuration'; + if ($config['language'] == 'es') { + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_es:Configuracion'; + } + + $this->notify( + [ + 'type' => 'NOTIF.SERVER.STATUS', + 'title' => __('No servers available.'), + 'message' => __('There are no servers registered in this console, please check installation guide.'), + 'url' => $url, + ] + ); + } + + // At this point there's no servers with issues. + $this->cleanNotifications('NOTIF.SERVER.STATUS%'); + return; + } + + foreach ($servers as $server) { + if ($server['status'] == 1) { + // Fatal error. Component has die. + $msg = __( + '%s (%s) crashed.', + servers_get_server_string_name($server['server_type']), + $server['name'] + ); + + $description = __( + '%s (%s) has died, please check log files', + servers_get_server_string_name($server['server_type']), + $server['name'] + ); + } else { + // Non-fatal error. Controlated exit. Component is not running. + $msg = __( + '%s (%s) is stopped.', + servers_get_server_string_name($server['server_type']), + $server['name'] + ); + $description = __( + '%s (%s) is stopped, please check configuration file or remove this server from server list.', + servers_get_server_string_name($server['server_type']), + $server['name'] + ); + } + + $this->notify( + [ + 'type' => 'NOTIF.SERVER.STATUS.'.$server['id_server'], + 'title' => $msg, + 'message' => $description, + 'url' => ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60' + ), + ] + ); + } + } + + + /** + * Checks if there's at last one server running in master mode. + * + * @return void + */ + public function checkPandoraServerMasterAvailable() + { + $n_masters = db_get_value_sql( + 'SELECT + count(*) as n + FROM tserver + WHERE + unix_timestamp() - unix_timestamp(keepalive) <= server_keepalive + AND master > 0 + AND status = 1' + ); + + if ($n_masters === false) { + // Failed to retrieve server list. + return; + } + + if ($n_masters <= 0) { + // No server running in master. + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_en:Configuration#master'; + if ($config['language'] == 'es') { + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_es:Configuracion#master'; + } + + $this->notify( + [ + 'type' => 'NOTIF.SERVER.MASTER', + 'title' => __('No master servers found.'), + 'message' => __('You should define at last one server to run as master, please check documentation.'), + 'url' => $url, + ] + ); + } else { + $this->cleanNotifications('NOTIF.SERVER.MASTER%'); + } + + } + + + /** + * Checks PHP settings to be correct. Generates system notifications if not. + * + * @return void + */ + public function checkPHPSettings() + { + global $config; + + $PHPupload_max_filesize = config_return_in_bytes( + ini_get('upload_max_filesize') + ); + + // PHP configuration. + $PHPmax_input_time = ini_get('max_input_time'); + $PHPmemory_limit = config_return_in_bytes(ini_get('memory_limit')); + $PHPmax_execution_time = ini_get('max_execution_time'); + $PHPsafe_mode = ini_get('safe_mode'); + $PHPdisable_functions = ini_get('disable_functions'); + $PHPupload_max_filesize_min = config_return_in_bytes('800M'); + $PHPmemory_limit_min = config_return_in_bytes('500M'); + + // PhantomJS status. + $result_ejecution = exec($config['phantomjs_bin'].'/phantomjs --version'); + + // PHP version checks. + $php_version = phpversion(); + $php_version_array = explode('.', $php_version); + + if ($PHPsafe_mode === '1') { + $this->notify( + [ + 'type' => 'NOTIF.PHP.SAFE_MODE', + 'title' => __('PHP safe mode is enabled. Some features may not properly work.'), + 'message' => __('To disable, change it on your PHP configuration file (php.ini) and put safe_mode = Off (Dont forget restart apache process after changes)'), + 'url' => ui_get_full_url('index.php'), + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.SAFE_MODE'); + } + + if ($PHPmax_input_time !== '-1') { + $this->notify( + [ + 'type' => 'NOTIF.PHP.INPUT_TIME', + 'title' => sprintf( + __("Not recommended '%s' value in PHP configuration"), + 'max_input_time' + ), + 'message' => sprintf( + __('Recommended value is %s'), + '-1 ('.__('Unlimited').')' + ).'

'.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), + 'url' => ui_get_full_url('index.php'), + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.INPUT_TIME'); + } + + if ($PHPmax_execution_time !== '0') { + $this->notify( + [ + 'type' => 'NOTIF.PHP.EXECUTION_TIME', + 'title' => sprintf( + __("Not recommended '%s' value in PHP configuration"), + 'max_execution_time' + ), + 'message' => sprintf( + __('Recommended value is: %s'), + '0 ('.__('Unlimited').')' + ).'

'.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), + 'url' => ui_get_full_url('index.php'), + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.EXECUTION_TIME'); + } + + if ($PHPupload_max_filesize < $PHPupload_max_filesize_min) { + $this->notify( + [ + 'type' => 'NOTIF.PHP.UPLOAD_MAX_FILESIZE', + 'title' => sprintf( + __("Not recommended '%s' value in PHP configuration"), + 'upload_max_filesize' + ), + 'message' => sprintf( + __('Recommended value is: %s'), + sprintf(__('%s or greater'), '800M') + ).'

'.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), + 'url' => ui_get_full_url('index.php'), + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.UPLOAD_MAX_FILESIZE'); + } + + if ($PHPmemory_limit < $PHPmemory_limit_min && $PHPmemory_limit !== '-1') { + $this->notify( + [ + 'type' => 'NOTIF.PHP.MEMORY_LIMIT', + 'title' => sprintf( + __("Not recommended '%s' value in PHP configuration"), + 'memory_limit' + ), + 'message' => sprintf( + __('Recommended value is: %s'), + sprintf(__('%s or greater'), '500M') + ).'

'.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator'), + 'url' => ui_get_full_url('index.php'), + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.MEMORY_LIMIT'); + } + + if (preg_match('/system/', $PHPdisable_functions) || preg_match('/exec/', $PHPdisable_functions)) { + $this->notify( + [ + 'type' => 'NOTIF.PHP.DISABLE_FUNCTIONS', + 'title' => __('Problems with disable functions in PHP.INI'), + 'message' => __('Variable disable_functions containts functions system() or exec(), in PHP configuration file (php.ini)').'

'.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), + 'url' => ui_get_full_url('index.php'), + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.DISABLE_FUNCTIONS'); + } + + if (!isset($result_ejecution) || $result_ejecution == '') { + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_en:Configuration#Phantomjs'; + if ($config['language'] == 'es') { + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_es:Configuracion#Phantomjs'; + } + + $this->notify( + [ + 'type' => 'NOTIF.PHP.PHANTOMJS', + 'title' => __('phantomjs is not installed'), + 'message' => __('To be able to create images of the graphs for PDFs, please install the phantom.js extension. For that, it is necessary to follow these steps:'), + 'url' => $url, + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.PHANTOMJS'); + } + + if ($php_version_array[0] < 7) { + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_en:_PHP_7'; + if ($config['language'] == 'es') { + $url = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_es:Instalaci%C3%B3n_y_actualizaci%C3%B3n_PHP_7'; + } + + $this->notify( + [ + 'type' => 'NOTIF.PHP.VERSION', + 'title' => __('PHP UPDATE REQUIRED'), + 'message' => __('For a correct operation of PandoraFMS, PHP must be updated to version 7.0 or higher.').'
'.__('Otherwise, functionalities will be lost.').'
'."
  1. ".__('Report download in PDF format').'
  2. '."
  3. ".__('Emails Sending').'
  4. '.__('Metaconsole Collections').'
  5. ...
', + 'url' => $url, + ] + ); + } else { + $this->cleanNotifications('NOTIF.PHP.VERSION'); + } + } + + + /** + * Checks if history DB is available. + * + * @return void + */ + public function checkPandoraHistoryDB() + { + global $config; + + if (isset($config['history_db_enabled']) + && $config['history_db_enabled'] == 1 + ) { + if (! isset($config['history_db_connection']) + || $config['history_db_connection'] === false + ) { + ob_start(); + $config['history_db_connection'] = db_connect( + $config['history_db_host'], + $config['history_db_name'], + $config['history_db_user'], + io_output_password($config['history_db_pass']), + $config['history_db_port'], + false + ); + ob_get_clean(); + } + + if ($config['history_db_connection'] === false) { + $this->notify( + [ + 'type' => 'NOTIF.HISTORYDB', + 'title' => __('Historical database not available'), + 'message' => __('Historical database is enabled. But not available using given configuration. Please check it.'), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=hist_db' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.HISTORYDB'); + } + } else { + $this->cleanNotifications('NOTIF.HISTORYDB'); + } + } + + + /** + * Check if pandora_db is running in all available DB instances. + * Generating notifications. + * + * @return void + */ + public function checkPandoraDBMaintenance() + { + global $config; + + // Main DB db_maintenance value. + $db_maintance = db_get_value( + 'value', + 'tconfig', + 'token', + 'db_maintance' + ); + + // If never was executed, it means we are in the first Pandora FMS execution. Set current timestamp. + if (empty($db_maintance)) { + config_update_value('db_maintance', date('U')); + } + + $last_maintance = (date('U') - $db_maintance); + + // Limit 48h. + if ($last_maintance > 172800) { + $this->notify( + [ + 'type' => 'NOTIF.PANDORADB', + 'title' => __('Database maintance problem'), + 'message' => __('Your database is not maintained correctly. It seems that more than 48hrs have passed without proper maintenance. Please review documents of %s on how to perform this maintenance process (DB Tool) and enable it as soon as possible.', get_product_name()), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.PANDORADB'); + } + + if (isset($config['history_db_enabled']) + && $config['history_db_enabled'] == 1 + ) { + // History DB db_maintenance value. + $db_maintenance = db_get_value( + 'value', + 'tconfig', + 'token', + 'db_maintenance', + true + ); + + // History db connection is supossed to be enabled since we use + // db_get_value, wich initializes target db connection. + if (empty($db_maintance)) { + $sql = sprintf( + 'UPDATE tconfig SET `value`=%d WHERE `token`="%s"', + date('U'), + 'db_maintenance' + ); + $affected_rows = db_process_sql( + $sql, + $rettype = 'affected_rows', + $dbconnection = $config['history_db_connection'] + ); + + if ($affected_rows == 0) { + // Failed to update. Maybe the row does not exist? + $sql = sprintf( + 'INSERT INTO tconfig(`token`,`value`) VALUES("%s",%d)', + 'db_maintenance', + date('U') + ); + + $affected_rows = db_process_sql( + $sql, + $rettype = 'affected_rows', + $dbconnection = $config['history_db_connection'] + ); + } + } + + $last_maintance = (date('U') - $db_maintance); + + // Limit 48h. + if ($last_maintance > 172800) { + $this->notify( + [ + 'type' => 'NOTIF.PANDORADB.HISTORY', + 'title' => __( + 'Historical database maintance problem.' + ), + 'message' => __('Your historical database is not being maintained correctly. It seems that more than 48hrs have passed without proper maintenance. Please review documents of %s on how to perform this maintenance process (DB Tool) and enable it as soon as possible.', get_product_name()), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' + ), + ] + ); + } else { + // Historical db working fine. + $this->cleanNotifications('NOTIF.PANDORADB.HISTORY'); + } + } else { + // Disabled historical db. + $this->cleanNotifications('NOTIF.PANDORADB.HISTORY'); + } + } + + + /** + * Check MR package applied in historical DB + * + * @return void + */ + public function checkPandoraHistoryDBMR() + { + global $config; + + if (isset($config['history_db_enabled']) + && $config['history_db_enabled'] == 1 + ) { + $mrh_version = db_get_value( + 'value', + 'tconfig', + 'token', + 'MR', + true + ); + if ($mrh_version != $config['MR']) { + $this->notify( + [ + 'type' => 'NOTIF.HISTORYDB.MR', + 'title' => __('Historical database MR missmatch'), + 'message' => __('Your historical database is not using the same schema of main DB. This could produce anomalyes while storing historical data.'), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=hist_db' + ), + ] + ); + } else { + // MR version OK. + $this->cleanNotifications('NOTIF.HISTORYDB.MR'); + } + } else { + // Disabled historical db. + $this->cleanNotifications('NOTIF.HISTORYDB.MR'); + } + } + + + /** + * Check if elasticsearch is available. + * + * @return void + */ + public function checkExternalComponents() + { + global $config; + + // Cannot check logstash, configuration is only available from server. + // Cannot check selenium, configuration is only available from server. + if (isset($config['log_collector']) + && $config['log_collector'] == 1 + ) { + $elasticsearch = @fsockopen( + $config['elasticsearch_ip'], + $config['elasticsearch_port'], + $errno, + $errstr, + 5 + ); + + if ($elasticsearch === false) { + $this->notify( + [ + 'type' => 'NOTIF.EXT.ELASTICSEARCH', + 'title' => __('Log collector cannot connect to ElasticSearch'), + 'message' => __('ElasticSearch is not available using current configuration. Please check it.'), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=log' + ), + ] + ); + } else { + fclose($elasticsearch); + $this->cleanNotifications('NOTIF.EXT.ELASTICSEARCH'); + } + } else { + $this->cleanNotifications('NOTIF.EXT.ELASTICSEARCH'); + } + + } + + + /** + * Checks if metaconsole DB connection is ready. + * + * @return void + */ + public function checkMetaconsole() + { + global $config; + + $check_ok = true; + + if (license_free() + && is_metaconsole() === false + && isset($config['node_metaconsole']) + && $config['node_metaconsole'] == 1 + ) { + // Check if node is successfully registered in MC. + $server_name = db_get_value( + 'distinct(name)', + 'tserver', + 'server_type', + 1 + ); + + $mc_db_conn = enterprise_hook( + 'metaconsole_load_external_db', + [ + [ + 'dbhost' => $config['replication_dbhost'], + 'dbuser' => $config['replication_dbuser'], + 'dbpass' => io_output_password( + $config['replication_dbpass'] + ), + 'dbname' => $config['replication_dbname'], + ], + ] + ); + + if ($mc_db_conn === NOERR) { + $check_ok = true; + } else { + $check_ok = false; + } + + // Restore the default connection. + enterprise_hook('metaconsole_restore_db'); + } + + if ($check_ok === true) { + $this->cleanNotifications('NOTIF.METACONSOLE.DB_CONNECTION'); + } else { + $this->notify( + [ + 'type' => 'NOTIF.METACONSOLE.DB_CONNECTION', + 'title' => __('Metaconsole DB is not available.'), + 'message' => __('Cannot connect with Metaconsole DB using stored configuration. Please check it.'), + 'url' => ui_get_full_url( + 'index.php?sec=general&sec2=godmode/setup/setup§ion=enterprise' + ), + ] + ); + } + } + + + /** + * Check if there are any incoming scheduled downtime in less than 15d. + * + * @return void + */ + public function checkDowntimes() + { + // 15 Days. + $THRESHOLD_SECONDS = (15 * 3600 * 24); + + // Check first if any planned runtime is running. + $currently_running = (int) db_get_value_sql( + 'SELECT count(*) as "n" FROM tplanned_downtime + WHERE executed = 1' + ); + + if ($currently_running > 0) { + $this->notify( + [ + 'type' => 'NOTIF.DOWNTIME', + 'title' => __('Scheduled downtime running.'), + 'message' => __('A scheduled downtime is running. Some monitorization data won\'t be available while downtime is taking place.'), + 'url' => ui_get_full_url( + 'index.php?sec=gagente&sec2=godmode/agentes/planned_downtime.list' + ), + ] + ); + return; + } else { + // Retrieve downtimes. + $downtimes = db_get_all_rows_sql( + 'SELECT * FROM tplanned_downtime + WHERE + (type_execution="once" AND date_from > now()) + OR type_execution!="once" ORDER BY `id` DESC' + ); + + // Initialize searchers. + $next_downtime_begin = PHP_INT_MAX; + $now = time(); + + if ($downtimes === false) { + $this->cleanNotifications('NOTIF.DOWNTIME'); + return; + } + + $weekdays = [ + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', + ]; + + foreach ($downtimes as $dt) { + if ($dt['type_execution'] == 'once' + && ($dt['date_from'] - $now) < $THRESHOLD_SECONDS + ) { + if ($next_downtime_begin > $dt['date_from']) { + // Store datetime for next downtime. + $next_downtime_begin = $dt['date_from']; + $next_downtime_end = $dt['date_to']; + } + } else if ($dt['type_periodicity'] == 'monthly') { + $schd_time_begin = explode( + ':', + $dt['periodically_time_from'] + ); + $schd_time_end = explode( + ':', + $dt['periodically_time_to'] + ); + + $begin = mktime( + // Hour. + $schd_time_begin[0], + // Minute. + $schd_time_begin[1], + // Second. + $schd_time_begin[2], + // Month. + date('n', $now), + // Day. + $dt['periodically_day_from'], + // Year. + date('Y', $now) + ); + + $end = mktime( + // Hour. + $schd_time_end[0], + // Minute. + $schd_time_end[1], + // Second. + $schd_time_end[2], + // Month. + date('n', $now), + // Day. + $dt['periodically_day_to'], + // Year. + date('Y', $now) + ); + + if ($next_downtime_begin > $begin) { + $next_downtime_begin = $begin; + $next_downtime_end = $end; + } + } else if ($dt['type_periodicity'] == 'weekly') { + // Always applies. + $current_week_day = date('N', $now); + + $schd_time_begin = explode( + ':', + $dt['periodically_time_from'] + ); + $schd_time_end = explode( + ':', + $dt['periodically_time_to'] + ); + + $i = 0; + $max = 7; + while ($dt[$weekdays[(($current_week_day + $i) % 7)]] != 1 + && $max-- >= 0 + ) { + // Calculate day of the week matching downtime + // definition. + $i++; + } + + if ($max < 0) { + // No days set. + continue; + } + + // Calculate utimestamp. + $begin = mktime( + // Hour. + $schd_time_begin[0], + // Minute. + $schd_time_begin[1], + // Second. + $schd_time_begin[2], + // Month. + date('n', $now), + // Day. + (date('j', $now) + $i + 1), + // Year. + date('Y', $now) + ); + + $end = mktime( + // Hour. + $schd_time_end[0], + // Minute. + $schd_time_end[1], + // Second. + $schd_time_end[2], + // Month. + date('n', $now), + // Day. + (date('j', $now) + $i + 1), + // Year. + date('Y', $now) + ); + + if ($next_downtime_begin > $begin) { + $next_downtime_begin = $begin; + $next_downtime_end = $end; + } + } + } + + if ($next_downtime_begin != PHP_INT_MAX) { + $this->notify( + [ + 'type' => 'NOTIF.DOWNTIME', + 'title' => __('Downtime scheduled soon.'), + 'message' => __( + 'A scheduled downtime is going to be executed from %s to %s. Some monitorization data won\'t be available while downtime is taking place.', + date('M j, G:i:s ', $next_downtime_begin), + date('M j, G:i:s ', $next_downtime_end) + ), + 'url' => ui_get_full_url( + 'index.php?sec=gagente&sec2=godmode/agentes/planned_downtime.list' + ), + ] + ); + return; + } else { + $this->cleanNotifications('NOTIF.DOWNTIME'); + } + } + } + + + /** + * Check if current instance of Pandora FMS is registered in Update Manager. + * + * @return void + */ + public function checkUpdateManagerRegistration() + { + global $config; + $login = get_parameter('login', false); + + if (license_free() === true + && users_is_admin($config['id_user']) === true + ) { + $login = get_parameter('login', false); + // Registration advice. + if ((isset($config['instance_registered']) === true + || ($config['instance_registered'] != 1)) && ($login === false) + ) { + $this->notify( + [ + 'type' => 'NOTIF.UPDATEMANAGER.REGISTRATION', + 'title' => __('This instance is not registered in the Update manager'), + 'message' => __('Click here to start the registration process'), + 'url' => 'javascript: force_run_register();', + ] + ); + } else { + $this->cleanNotifications('NOTIF.UPDATEMANAGER.REGISTRATION'); + } + } else { + $this->cleanNotifications('NOTIF.UPDATEMANAGER.REGISTRATION'); + } + } + + + /** + * Check if instance is subscribed to newsletter. + * + * @return void + */ + public function checkNewsletterSubscription() + { + global $config; + $login = get_parameter('login', false); + + // Newsletter advice. + $newsletter = db_get_value( + 'middlename', + 'tusuario', + 'id_user', + $config['id_user'] + ); + if (license_free() === true + && $newsletter != 1 + && $login === false + ) { + $this->notify( + [ + 'type' => 'NOTIF.NEWSLETTER.SUBSCRIPTION', + 'title' => __('Not subscribed to the newsletter'), + 'message' => __('Click here to start the newsletter subscription process'), + 'url' => 'javascript: force_run_newsletter();', + ] + ); + } else { + $this->cleanNotifications('NOTIF.NEWSLETTER.SUBSCRIPTION'); + } + } + + + /** + * Check if user 'admin' is enabled and using default password. + * + * @return void + */ + public function checkDefaultPassword() + { + global $config; + // Check default password for "admin". + $admin_with_default_pass = db_get_value_sql( + 'SELECT count(*) FROM tusuario + WHERE + id_user="admin" + AND password="1da7ee7d45b96d0e1f45ee4ee23da560" + AND is_admin=1 + and disabled!=1' + ); + + if ($admin_with_default_pass > 0) { + $this->notify( + [ + 'type' => 'NOTIF.SECURITY.DEFAULT_PASSWORD', + 'title' => __('Default password for "Admin" user has not been changed.'), + 'message' => __('Please change the default password because is a common vulnerability reported.'), + 'url' => ui_get_full_url( + 'index.php?sec=gusuarios&sec2=godmode/users/user_list' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.SECURITY.DEFAULT_PASSWORD'); + } + } + + + /** + * Undocumented function + * + * @return void + */ + public function checkFont() + { + global $config; + + if (($config['fontpath'] == '') + || (file_exists($config['fontpath']) === false) + ) { + $this->notify( + [ + 'type' => 'NOTIF.MISC.FONTPATH', + 'title' => __('Default font doesnt exist'), + 'message' => __('Your defined font doesnt exist or is not defined. Please check font parameters in your config'), + 'url' => ui_get_full_url( + 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=vis' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.MISC.FONTPATH'); + } + } + + + /** + * Checks if develop_bypass is enabbled. + * + * @return void + */ + public function checkDevelopBypass() + { + global $develop_bypass; + + if ($develop_bypass == 1) { + $this->notify( + [ + 'type' => 'NOTIF.MISC.DEVELOPBYPASS', + 'title' => __('Developer mode is enabled'), + 'message' => __( + 'Your %s has the "develop_bypass" mode enabled. This is a developer mode and should be disabled in a production system. This value is written in the main index.php file', + get_product_name() + ), + 'url' => ui_get_full_url('index.php'), + ] + ); + } else { + $this->cleanNotifications('NOTIF.MISC.DEVELOPBYPASS'); + } + } + + + /** + * Check if event storm protection is enabled. + * + * @return void + */ + public function checkEventStormProtection() + { + global $config; + if ($config['event_storm_protection']) { + $this->notify( + [ + 'type' => 'NOTIF.MISC.EVENTSTORMPROTECTION', + 'title' => __('Event storm protection is activated.'), + 'message' => __('You need to restart server after altering this configuration setting. No events will be generated during this mode.'), + 'url' => ui_get_full_url( + 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=general' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.MISC.EVENTSTORMPROTECTION'); + } + } + + + /** + * Check if there're new updates available. + * + * @return void + */ + public function checkUpdates() + { + global $config; + + if (isset($_SESSION['new_update'])) { + if (!empty($_SESSION['return_installation_open'])) { + if (!$_SESSION['return_installation_open']['return']) { + foreach ($_SESSION['return_installation_open']['text'] as $message) { + $this->notify( + [ + 'type' => 'NOTIF.UPDATEMANAGER.OPENSETUP', + 'title' => __('Error, first setup "Open update".'), + 'message' => $message, + 'url' => ui_get_full_url( + 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=general' + ), + ] + ); + } + } else { + $this->cleanNotifications('NOTIF.UPDATEMANAGER.OPENSETUP'); + } + } else { + $this->cleanNotifications('NOTIF.UPDATEMANAGER.OPENSETUP'); + } + + if ($_SESSION['new_update'] == 'new') { + $this->notify( + [ + 'type' => 'NOTIF.UPDATEMANAGER.UPDATE', + 'title' => __( + 'New %s Console update', + get_product_name() + ), + 'message' => __('There is a new update available. Please go to Administration:Setup:Update Manager for more details.'), + 'url' => ui_get_full_url( + 'index.php?sec=gsetup&sec2=godmode/update_manager/update_manager&tab=online' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.UPDATEMANAGER.UPDATE'); + } + } else { + $this->cleanNotifications('NOTIF.UPDATEMANAGER.OPENSETUP'); + $this->cleanNotifications('NOTIF.UPDATEMANAGER.UPDATE'); + } + } + + +} diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index 2fd79d6d43..3af3db3f69 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -1,2364 +1,2775 @@ $value, - 'token' => $token)); +function config_create_value($token, $value) +{ + return db_process_sql_insert( + 'tconfig', + [ + 'value' => $value, + 'token' => $token, + ] + ); } + /** * Update a single config value in the database. - * - * If the config token doesn't exists, it's created. - * - * @param string Config token to update. - * @param string New value to set. * - * @return bool True if success. False on failure. + * If the config token doesn't exists, it's created. + * + * @param string $token Config token to update. + * @param string $value New value to set. + * + * @return boolean True if success. False on failure. */ -function config_update_value ($token, $value) { - global $config; - // Include functions_io to can call __() function - include_once($config['homedir'] . '/include/functions_io.php'); - - if ($token == 'list_ACL_IPs_for_API') { - $value = str_replace(array("\r\n", "\r", "\n"), ";", - io_safe_output($value)); - } - - if ($token == 'default_assign_tags') { - $value = ($value); - } - - if (!isset ($config[$token])) { - $config[$token] = $value; - return (bool) config_create_value ($token, io_safe_input($value)); - } - - /* If it has not changed */ - if ($config[$token] == $value) - return true; - - $config[$token] = $value; - $value = io_safe_output($value); - - $result = db_process_sql_update ('tconfig', - array ('value' => io_safe_input($value)), - array ('token' => $token)); - - if ($result === 0) - return true; - else - return (bool) $result; +function config_update_value($token, $value) +{ + global $config; + // Include functions_io to can call __() function. + include_once $config['homedir'].'/include/functions_io.php'; + + if ($token == 'list_ACL_IPs_for_API') { + $value = str_replace( + [ + "\r\n", + "\r", + "\n", + ], + ';', + io_safe_output($value) + ); + } + + if ($token == 'default_assign_tags') { + $value = ($value); + } + + if (!isset($config[$token])) { + $config[$token] = $value; + return (bool) config_create_value($token, io_safe_input($value)); + } + + // If it has not changed. + if ($config[$token] == $value) { + return true; + } + + $config[$token] = $value; + $value = io_safe_output($value); + + $result = db_process_sql_update( + 'tconfig', + ['value' => io_safe_input($value)], + ['token' => $token] + ); + + if ($result === 0) { + return true; + } else { + return (bool) $result; + } } + /** - * Updates all config values in case setup page was invoked + * Updates all config values in case setup page was invoked + * + * @return boolean */ -function config_update_config () { - global $config; - - // Include functions_io to can call __() function - include_once($config['homedir'] . '/include/functions_io.php'); - - /* If user is not even log it, don't try this */ - if (! isset ($config['id_user'])) { - $config['error_config_update_config'] = array(); - $config['error_config_update_config']['correct'] = false; - $config['error_config_update_config']['message'] = __('Failed updated: User did not login.'); - - return false; - } - - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - $config['error_config_update_config'] = array(); - $config['error_config_update_config']['correct'] = false; - $config['error_config_update_config']['message'] = __('Failed updated: User is not admin.'); - - return false; - } - - $update_config = (bool) get_parameter ('update_config'); - - if ($update_config) { - db_pandora_audit("Setup", "Setup has changed"); - } - else { - //Do none - - return false; - } - - $error_update = array(); - - $sec2 = get_parameter_get('sec2'); - switch ($sec2) { - case 'godmode/setup/setup': - $section_setup = get_parameter ('section'); - //////// MAIN SETUP - // Setup now is divided in different tabs - switch ($section_setup) { - case 'general': - if (!config_update_value ('language', (string) get_parameter ('language'))) - $error_update[] = __('Language settings'); - if (!config_update_value ('remote_config', (string) get_parameter ('remote_config'))) - $error_update[] = __('Remote config directory'); - if (!config_update_value ('phantomjs_bin', (string) get_parameter ('phantomjs_bin'))) - $error_update[] = __('phantomjs config directory'); - if (!config_update_value ('loginhash_pwd', io_input_password((string) get_parameter ('loginhash_pwd')))) - $error_update[] = __('Auto login (hash) password'); - if (!config_update_value ('timesource', (string) get_parameter ('timesource'))) - $error_update[] = __('Time source'); - if (!config_update_value ('autoupdate', (bool) get_parameter ('autoupdate'))) - $error_update[] = __('Automatic check for updates'); - if (!config_update_value ('cert_path', (bool) get_parameter ('cert_path'))) - $error_update[] = __('SSL cert path'); - if (!config_update_value ('https', (bool) get_parameter ('https'))) - $error_update[] = __('Enforce https'); - if (!config_update_value ('use_cert', (bool) get_parameter ('use_cert'))) - $error_update[] = __('Use cert.'); - if (!config_update_value ('attachment_store', (string) get_parameter ('attachment_store'))) - $error_update[] = __('Attachment store'); - if (!config_update_value ('list_ACL_IPs_for_API', (string) get_parameter('list_ACL_IPs_for_API'))) - $error_update[] = __('IP list with API access'); - if (!config_update_value ('api_password', io_input_password(get_parameter('api_password')))) - $error_update[] = __('API password'); - if (!config_update_value ('activate_gis', (bool) get_parameter ('activate_gis'))) - $error_update[] = __('Enable GIS features'); - if (!config_update_value ('integria_inventory', get_parameter ('integria_inventory'))) - $error_update[] = __('Integria inventory'); - if (!config_update_value ('integria_api_password', io_input_password(get_parameter ('integria_api_password')))) - $error_update[] = __('Integria API password'); - if (!config_update_value ('integria_url', get_parameter ('integria_url'))) - $error_update[] = __('Integria URL'); - if (!config_update_value ('activate_netflow', (bool) get_parameter ('activate_netflow'))) - $error_update[] = __('Enable Netflow'); - $timezone = (string) get_parameter ('timezone'); - if ($timezone != "") { - if (!config_update_value ('timezone', $timezone)) - $error_update[] = __('Timezone setup'); - } - if (!config_update_value ('sound_alert', get_parameter('sound_alert'))) - $error_update[] = __('Sound for Alert fired'); - if (!config_update_value ('sound_critical', get_parameter('sound_critical'))) - $error_update[] = __('Sound for Monitor critical'); - if (!config_update_value ('sound_warning', get_parameter('sound_warning'))) - $error_update[] = __('Sound for Monitor warning'); - # Update of Pandora FMS license - $update_manager_installed = db_get_value('value', 'tconfig', 'token', 'update_manager_installed'); - - if ($update_manager_installed == 1) { - $license_info_key = get_parameter('license_info_key', ''); - if (!empty($license_info_key)) { - $values = array(db_escape_key_identifier('value') => $license_info_key); - $where = array(db_escape_key_identifier('key') => 'customer_key'); - $update_manage_settings_result = db_process_sql_update('tupdate_settings', $values, $where); - if ($update_manage_settings_result === false) - $error_update[] = __('License information'); - } - } - if (!config_update_value ('public_url', get_parameter('public_url'))) - $error_update[] = __('Public URL'); - if (!config_update_value ('referer_security', get_parameter('referer_security'))) - $error_update[] = __('Referer security'); - if (!config_update_value ('event_storm_protection', get_parameter('event_storm_protection'))) - $error_update[] = __('Event storm protection'); - if (!config_update_value ('command_snapshot', get_parameter('command_snapshot'))) - $error_update[] = __('Command Snapshot'); - if (!config_update_value ('server_log_dir', get_parameter('server_log_dir'))) - $error_update[] = __('Server logs directory'); - if (!config_update_value ('max_log_size', get_parameter('max_log_size'))) - $error_update[] = __('Log size limit in system logs viewer extension'); - if (!config_update_value ('tutorial_mode', get_parameter('tutorial_mode'))) - $error_update[] = __('Tutorial mode'); - if (!config_update_value ('past_planned_downtimes', get_parameter('past_planned_downtimes'))) - $error_update[] = __('Allow create planned downtimes in the past'); - if (!config_update_value ('limit_parameters_massive', get_parameter('limit_parameters_massive'))) - $error_update[] = __('Limit parameters bulk'); - if (!config_update_value ('identification_reminder', get_parameter('identification_reminder'))) - $error_update[] = __('Identification_reminder'); - if (!config_update_value ('include_agents', (bool)get_parameter('include_agents'))) - $error_update[] = __('Include_agents'); - if (!config_update_value ('alias_as_name', get_parameter('alias_as_name'))) - $error_update[] = __('alias_as_name'); - if (!config_update_value ('auditdir', get_parameter('auditdir'))) - $error_update[] = __('Audit log directory'); - break; - case 'enterprise': - if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { - if (!config_update_value ('trap2agent', (string) get_parameter ('trap2agent'))) - $error_update[] = __('Forward SNMP traps to agent (if exist)'); - if (!config_update_value ('acl_enterprise', get_parameter ('acl_enterprise'))) - $error_update[] = __('Use Enterprise ACL System'); - if (!config_update_value ('metaconsole', get_parameter ('metaconsole'))) - $error_update[] = __('Activate Metaconsole'); - if (!config_update_value ('collection_max_size', get_parameter('collection_max_size'))) - $error_update[] = __('Size of collection'); - if (!config_update_value ('event_replication', (int)get_parameter('event_replication'))) - $error_update[] = __('Events replication'); - if ((int)get_parameter('event_replication') == 1) { - if (!config_update_value ('replication_interval', (int)get_parameter('replication_interval'))) - $error_update[] = __('Replication interval'); - if (!config_update_value ('replication_limit', (int)get_parameter('replication_limit'))) - $error_update[] = __('Replication limit'); - if (!config_update_value ('replication_mode', (string)get_parameter('replication_mode'))) - $error_update[] = __('Replication mode'); - if (!config_update_value ('show_events_in_local', (string)get_parameter('show_events_in_local'))) - $error_update[] = __('Show events list in local console (read only)'); - } - if (!config_update_value ('replication_dbengine', (string)get_parameter('replication_dbengine'))) - $error_update[] = __('Replication DB engine'); - if (!config_update_value ('replication_dbhost', (string)get_parameter('replication_dbhost'))) - $error_update[] = __('Replication DB host'); - if (!config_update_value ('replication_dbname', (string)get_parameter('replication_dbname'))) - $error_update[] = __('Replication DB database'); - if (!config_update_value ('replication_dbuser', (string)get_parameter('replication_dbuser'))) - $error_update[] = __('Replication DB user'); - if (!config_update_value ('replication_dbpass', io_input_password((string)get_parameter('replication_dbpass')))) - $error_update[] = __('Replication DB password'); - if (!config_update_value ('replication_dbport', (string)get_parameter('replication_dbport'))) - $error_update[] = __('Replication DB port'); - if (!config_update_value ('metaconsole_agent_cache', (int)get_parameter('metaconsole_agent_cache'))) - $error_update[] = __('Metaconsole agent cache'); - if (!config_update_value ('log_collector', (bool)get_parameter('log_collector'))) - $error_update[] = __('Activate Log Collector'); - if (!config_update_value ('enable_update_manager', get_parameter('enable_update_manager'))) - $error_update[] = __('Enable Update Manager'); - if (!config_update_value ('ipam_ocuppied_critical_treshold', get_parameter('ipam_ocuppied_critical_treshold'))) - $error_update[] = __('Ipam Ocuppied Manager Critical'); - if (!config_update_value ('ipam_ocuppied_warning_treshold', get_parameter('ipam_ocuppied_warning_treshold'))) - $error_update[] = __('Ipam Ocuppied Manager Warning'); +function config_update_config() +{ + global $config; - $inventory_changes_blacklist = get_parameter('inventory_changes_blacklist', array()); - if (!config_update_value ('inventory_changes_blacklist', implode(',',$inventory_changes_blacklist))) - $error_update[] = __('Inventory changes blacklist'); + // Include functions_io to can call __() function. + include_once $config['homedir'].'/include/functions_io.php'; - if (!config_update_value ('email_from_dir', get_parameter('email_from_dir'))) - $error_update[] = __('From dir'); - if (!config_update_value ('email_from_name', get_parameter('email_from_name'))) - $error_update[] = __('From name'); - if (!config_update_value ('email_smtpServer', get_parameter('email_smtpServer'))) - $error_update[] = __('Server SMTP'); - if (!config_update_value ('email_smtpPort', (int)get_parameter('email_smtpPort'))) - $error_update[] = __('Port SMTP'); - if (!config_update_value ('email_encryption', get_parameter('email_encryption'))) - $error_update[] = __('Encryption'); - if (!config_update_value ('email_username', get_parameter('email_username'))) - $error_update[] = __('Email user'); - if (!config_update_value ('email_password', get_parameter('email_password'))) - $error_update[] = __('Email password'); - - } - break; - case 'pass': - if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { - if (!config_update_value ('enable_pass_policy', get_parameter('enable_pass_policy'))) - $error_update[] = __('Enable password policy'); - - if (!config_update_value ('pass_size', get_parameter('pass_size'))) - $error_update[] = __('Min. size password'); - if (!config_update_value ('pass_expire', get_parameter('pass_expire'))) - $error_update[] = __('Password expiration'); - if (!config_update_value ('first_login', get_parameter('first_login'))) - $error_update[] = __('Force change password on first login'); - if (!config_update_value ('mins_fail_pass', get_parameter('mins_fail_pass'))) - $error_update[] = __('User blocked if login fails'); - if (!config_update_value ('number_attempts', get_parameter('number_attempts'))) - $error_update[] = __('Number of failed login attempts'); - if (!config_update_value ('pass_needs_numbers', get_parameter('pass_needs_numbers'))) - $error_update[] = __('Password must have numbers'); - if (!config_update_value ('pass_needs_symbols', get_parameter('pass_needs_symbols'))) - $error_update[] = __('Password must have symbols'); - if (!config_update_value ('enable_pass_policy_admin', get_parameter('enable_pass_policy_admin'))) - $error_update[] = __('Apply password policy to admin users'); - if (!config_update_value ('enable_pass_history', get_parameter('enable_pass_history'))) - $error_update[] = __('Enable password history'); - if (!config_update_value ('compare_pass', get_parameter('compare_pass'))) - $error_update[] = __('Compare previous password'); - if (!config_update_value ('reset_pass_option', (bool)get_parameter('reset_pass_option'))) - $error_update[] = __('Activate reset password'); - } - break; - case 'auth': - //////// AUTHENTICATION SETUP - if (!config_update_value ('auth', get_parameter ('auth'))) - $error_update[] = __('Authentication method'); - if (!config_update_value ('autocreate_remote_users', get_parameter ('autocreate_remote_users'))) - $error_update[] = __('Autocreate remote users'); - if (!config_update_value ('default_remote_profile', get_parameter ('default_remote_profile'))) - $error_update[] = __('Autocreate profile'); - if (!config_update_value ('default_remote_group', get_parameter ('default_remote_group'))) - $error_update[] = __('Autocreate profile group'); - if (!config_update_value ('default_assign_tags', implode(",",get_parameter ('default_assign_tags')))) - $error_update[] = __('Autocreate profile tags'); - if (!config_update_value ('default_no_hierarchy', (int)get_parameter ('default_no_hierarchy'))) - $error_update[] = __('Automatically assigned no hierarchy'); - if (!config_update_value ('autocreate_blacklist', get_parameter ('autocreate_blacklist'))) - $error_update[] = __('Autocreate blacklist'); - - if (!config_update_value ('ad_server', get_parameter ('ad_server'))) - $error_update[] = __('Active directory server'); - if (!config_update_value ('ad_port', get_parameter ('ad_port'))) - $error_update[] = __('Active directory port'); - if (!config_update_value ('ad_start_tls', get_parameter ('ad_start_tls'))) - $error_update[] = __('Start TLS'); - if (!config_update_value ('ad_advanced_config', get_parameter ('ad_advanced_config'))) - $error_update[] = __('Advanced Config AD'); - if (!config_update_value ('ldap_advanced_config', get_parameter ('ldap_advanced_config'))) - $error_update[] = __('Advanced Config LDAP'); - if (!config_update_value ('ad_domain', get_parameter ('ad_domain'))) - $error_update[] = __('Domain'); - if (!config_update_value ('ad_adv_perms', get_parameter ('ad_adv_perms'))) - $error_update[] = __('Advanced Permisions AD'); - if (!config_update_value ('ldap_adv_perms', get_parameter ('ldap_adv_perms'))) - $error_update[] = __('Advanced Permissions LDAP'); - if (!config_update_value ('ldap_server', get_parameter ('ldap_server'))) - $error_update[] = __('LDAP server'); - if (!config_update_value ('ldap_port', get_parameter ('ldap_port'))) - $error_update[] = __('LDAP port'); - if (!config_update_value ('ldap_version', get_parameter ('ldap_version'))) - $error_update[] = __('LDAP version'); - if (!config_update_value ('ldap_start_tls', get_parameter ('ldap_start_tls'))) - $error_update[] = __('Start TLS'); - if (!config_update_value ('ldap_base_dn', get_parameter ('ldap_base_dn'))) - $error_update[] = __('Base DN'); - if (!config_update_value ('ldap_login_attr', get_parameter ('ldap_login_attr'))) - $error_update[] = __('Login attribute'); - if (!config_update_value ('ldap_admin_login', get_parameter ('ldap_admin_login'))) - $error_update[] = __('Admin LDAP login'); - if (!config_update_value ('ldap_admin_pass', get_parameter ('ldap_admin_pass'))) - $error_update[] = __('Admin LDAP password'); - if (!config_update_value ('fallback_local_auth', get_parameter ('fallback_local_auth'))) - $error_update[] = __('Fallback to local authentication'); - if (!config_update_value ('ldap_login_user_attr', get_parameter ('ldap_login_user_attr'))) - $error_update[] = __('Login user attribute'); - if (!config_update_value ('ldap_function', get_parameter ('ldap_function'))) - $error_update[] = __('LDAP function'); - - if (isset($config['fallback_local_auth']) && $config['fallback_local_auth'] == 0) { - if (!config_update_value ('ldap_save_password', get_parameter ('ldap_save_password'))) - $error_update[] = __('Save Password'); - } - else if (isset($config['fallback_local_auth']) && $config['fallback_local_auth'] == 1) { - config_update_value ('ldap_save_password', 1); - } + // If user is not even log it, don't try this. + if (! isset($config['id_user'])) { + $config['error_config_update_config'] = []; + $config['error_config_update_config']['correct'] = false; + $config['error_config_update_config']['message'] = __('Failed updated: User did not login.'); - if (!config_update_value ('rpandora_server', get_parameter ('rpandora_server'))) - $error_update[] = __('MySQL host'); - if (!config_update_value ('rpandora_port', get_parameter ('rpandora_port'))) - $error_update[] = __('MySQL port'); - if (!config_update_value ('rpandora_dbname', get_parameter ('rpandora_dbname'))) - $error_update[] = __('Database name'); - if (!config_update_value ('rpandora_user', get_parameter ('rpandora_user'))) - $error_update[] = __('User'); - if (!config_update_value ('rpandora_pass', io_input_password(get_parameter ('rpandora_pass')))) - $error_update[] = __('Password'); - - if (!config_update_value ('rintegria_server', get_parameter ('rintegria_server'))) - $error_update[] = __('Integria host'); - if (!config_update_value ('rintegria_port', get_parameter ('rintegria_port'))) - $error_update[] = __('MySQL port'); - if (!config_update_value ('rintegria_dbname', get_parameter ('rintegria_dbname'))) - $error_update[] = __('Database name'); - if (!config_update_value ('rintegria_user', get_parameter ('rintegria_user'))) - $error_update[] = __('User'); - if (!config_update_value ('rintegria_pass', io_input_password(get_parameter ('rintegria_pass')))) - $error_update[] = __('Password'); - if (!config_update_value ('saml_path', get_parameter ('saml_path'))) - $error_update[] = __('Saml path'); - if (!config_update_value ('double_auth_enabled', get_parameter ('double_auth_enabled'))) - $error_update[] = __('Double authentication'); - if (!config_update_value ('session_timeout', get_parameter ('session_timeout'))) - $error_update[] = __('Session timeout'); - ///////////// - break; - case 'perf': - //////// PERFORMANCE SETUP - if (!config_update_value ('event_purge', get_parameter ('event_purge'))) - $error_update[] = - $check_metaconsole_events_history = get_parameter ('metaconsole_events_history', -1); - if ($check_metaconsole_events_history != -1) - if (!config_update_value ('metaconsole_events_history', get_parameter ('metaconsole_events_history'))) - $error_update[] = __('Max. days before delete events'); - if (!config_update_value ('trap_purge', get_parameter ('trap_purge'))) - $error_update[] = __('Max. days before delete traps'); - if (!config_update_value ('string_purge', get_parameter ('string_purge'))) - $error_update[] = __('Max. days before delete string data'); - if (!config_update_value ('audit_purge', get_parameter ('audit_purge'))) - $error_update[] = __('Max. days before delete audit events'); - if (!config_update_value ('gis_purge', get_parameter ('gis_purge'))) - $error_update[] = __('Max. days before delete GIS data'); - if (!config_update_value ('days_purge', (int) get_parameter ('days_purge'))) - $error_update[] = __('Max. days before purge'); - if (!config_update_value ('days_delete_unknown', (int) get_parameter ('days_delete_unknown'))) - $error_update[] = __('Max. days before delete unknown modules'); - if (!config_update_value ('days_compact', (int) get_parameter ('days_compact'))) - $error_update[] = __('Max. days before compact data'); - if (!config_update_value ('days_autodisable_deletion', (int) get_parameter ('days_autodisable_deletion'))) - $error_update[] = __('Max. days before autodisable deletion'); - if (!config_update_value ('report_limit', (int) get_parameter ('report_limit'))) - $error_update[] = __('Item limit for realtime reports)'); - if (!config_update_value ('step_compact', (int) get_parameter ('step_compact'))) - $error_update[] = __('Compact interpolation in hours (1 Fine-20 bad)'); - if (!config_update_value ('event_view_hr', (int) get_parameter ('event_view_hr'))) - $error_update[] = __('Default hours for event view'); - if (!config_update_value ('realtimestats', get_parameter ('realtimestats'))) - $error_update[] = __('Use realtime statistics'); - if (!config_update_value ('stats_interval', get_parameter ('stats_interval'))) - $error_update[] = __('Batch statistics period (secs)'); - if (!config_update_value ('agentaccess', (int) get_parameter ('agentaccess'))) - $error_update[] = __('Use agent access graph'); - if (!config_update_value ('num_files_attachment', (int) get_parameter ('num_files_attachment'))) - $error_update[] = __('Max. recommended number of files in attachment directory'); - if (!config_update_value ('delete_notinit', get_parameter ('delete_notinit'))) - $error_update[] = __('Delete not init modules'); - if (!config_update_value ('big_operation_step_datos_purge', get_parameter ('big_operation_step_datos_purge'))) - $error_update[] = __('Big Operatiopn Step to purge old data'); - if (!config_update_value ('small_operation_step_datos_purge', get_parameter ('small_operation_step_datos_purge'))) - $error_update[] = __('Small Operation Step to purge old data'); - if (!config_update_value ('num_past_special_days', get_parameter ('num_past_special_days'))) - $error_update[] = __('Retention period of past special days'); - if (!config_update_value ('max_macro_fields', get_parameter ('max_macro_fields'))) - $error_update[] = __('Max. macro data fields'); - if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { - if (!config_update_value ('inventory_purge', get_parameter ('inventory_purge'))) - $error_update[] = __('Max. days before delete inventory data'); - } - if (!config_update_value ('max_graph_container', get_parameter ('max_graph_container'))) - $error_update[] = __('Graph container - Max. Items'); - ///////////// - break; - - case 'vis': - //////// VISUAL STYLES SETUP - if (!config_update_value ('date_format', (string) get_parameter ('date_format'))) - $error_update[] = __('Date format string'); - if (!config_update_value ('prominent_time', (string) get_parameter ('prominent_time'))) - $error_update[] = __('Timestamp or time comparation'); - if (!config_update_value ('graph_color1', (string) get_parameter ('graph_color1'))) - $error_update[] = __('Graph color #1'); - if (!config_update_value ('graph_color2', (string) get_parameter ('graph_color2'))) - $error_update[] = __('Graph color #2'); - if (!config_update_value ('graph_color3', (string) get_parameter ('graph_color3'))) - $error_update[] = __('Graph color #3'); - if (!config_update_value ('graph_color4', (string) get_parameter ('graph_color4'))) - $error_update[] = __('Graph color #4'); - if (!config_update_value ('graph_color5', (string) get_parameter ('graph_color5'))) - $error_update[] = __('Graph color #5'); - if (!config_update_value ('graph_color6', (string) get_parameter ('graph_color6'))) - $error_update[] = __('Graph color #6'); - if (!config_update_value ('graph_color7', (string) get_parameter ('graph_color7'))) - $error_update[] = __('Graph color #7'); - if (!config_update_value ('graph_color8', (string) get_parameter ('graph_color8'))) - $error_update[] = __('Graph color #8'); - if (!config_update_value ('graph_color9', (string) get_parameter ('graph_color9'))) - $error_update[] = __('Graph color #9'); - if (!config_update_value ('graph_color10', (string) get_parameter ('graph_color10'))) - $error_update[] = __('Graph color #10'); - if (!config_update_value ('interface_unit', (string) get_parameter ('interface_unit', __('Bytes') ))) - $error_update[] = __('Value to interface graphics'); - if (!config_update_value ('graph_precision', (string) get_parameter ('graph_precision', 1))) - $error_update[] = __('Data precision for reports'); - $style = (string) get_parameter ('style'); - if ($style != $config['style']) - $style = substr ($style, 0, strlen ($style) - 4); - if (!config_update_value ('style', $style)) - $error_update[] = __('Style template'); - if (!config_update_value ('block_size', (int) get_parameter ('block_size'))) - $error_update[] = __('Block size for pagination'); - if (!config_update_value ('round_corner', (bool) get_parameter ('round_corner'))) - $error_update[] = __('Use round corners'); - if (!config_update_value ('show_qr_code_header', (bool) get_parameter ('show_qr_code_header'))) - $error_update[] = __('Show QR code header'); - if (!config_update_value ('status_images_set', (string) get_parameter ('status_images_set'))) - $error_update[] = __('Status icon set'); - if (!config_update_value ('fontpath', (string) get_parameter ('fontpath'))) - $error_update[] = __('Font path'); - if (!config_update_value ('font_size', get_parameter('font_size'))) - $error_update[] = __('Font size'); + return false; + } - if (!config_update_value ('custom_favicon', (string) get_parameter ('custom_favicon'))) - $error_update[] = __('Custom favicon'); - if (!config_update_value ('custom_logo', (string) get_parameter ('custom_logo'))) - $error_update[] = __('Custom logo'); - if (!config_update_value ('custom_logo_white_bg', (string) get_parameter ('custom_logo_white_bg'))) - $error_update[] = __('Custom logo white background'); - if (!config_update_value ('custom_logo_login', (string) get_parameter ('custom_logo_login'))) - $error_update[] = __('Custom logo login'); - if (!config_update_value ('custom_splash_login', (string) get_parameter ('custom_splash_login'))) - $error_update[] = __('Custom splash login'); - if (!config_update_value ('custom_docs_logo', (string) get_parameter ('custom_docs_logo'))) - $error_update[] = __('Custom documentation logo'); - if (!config_update_value ('custom_support_logo', (string) get_parameter ('custom_support_logo'))) - $error_update[] = __('Custom support logo'); - if (!config_update_value ('custom_network_center_logo', (string) get_parameter ('custom_network_center_logo'))) - $error_update[] = __('Custom networkmap center logo'); - if (!config_update_value ('custom_mobile_console_logo', (string) get_parameter ('custom_mobile_console_logo'))) - $error_update[] = __('Custom networkmap center logo'); - if (!config_update_value ('custom_title1_login', (string) get_parameter ('custom_title1_login'))) - $error_update[] = __('Custom title1 login'); - if (!config_update_value ('custom_title2_login', (string) get_parameter ('custom_title2_login'))) - $error_update[] = __('Custom title2 login'); - if (!config_update_value ('login_background', (string) get_parameter ('login_background'))) - $error_update[] = __('Login background'); - - if (!config_update_value ('custom_docs_url', (string) get_parameter ('custom_docs_url'))) - $error_update[] = __('Custom Docs url'); - if (!config_update_value ('custom_support_url', (string) get_parameter ('custom_support_url'))) - $error_update[] = __('Custom support url'); - if (!config_update_value ('rb_product_name', (string) get_parameter ('rb_product_name'))) - $error_update[] = __('Product name'); - if (!config_update_value ('rb_copyright_notice', (string) get_parameter ('rb_copyright_notice'))) - $error_update[] = __('Copyright notice'); + if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + $config['error_config_update_config'] = []; + $config['error_config_update_config']['correct'] = false; + $config['error_config_update_config']['message'] = __('Failed updated: User is not admin.'); - if (!config_update_value ('meta_custom_logo', (string) get_parameter ('meta_custom_logo'))) - $error_update[] = __('Custom logo metaconsole'); - if (!config_update_value ('meta_custom_logo_white_bg', (string) get_parameter ('meta_custom_logo_white_bg'))) - $error_update[] = __('Custom logo metaconsole (white background)'); - if (!config_update_value ('meta_custom_logo_login', (string) get_parameter ('meta_custom_logo_login'))) - $error_update[] = __('Custom logo login metaconsole'); - if (!config_update_value ('meta_custom_splash_login', (string) get_parameter ('meta_custom_splash_login'))) - $error_update[] = __('Custom splash login metaconsole'); - if (!config_update_value ('meta_custom_title1_login', (string) get_parameter ('meta_custom_title1_login'))) - $error_update[] = __('Custom title1 login metaconsole'); - if (!config_update_value ('meta_custom_title2_login', (string) get_parameter ('meta_custom_title2_login'))) - $error_update[] = __('Custom title2 login metaconsole'); - if (!config_update_value ('meta_login_background', (string) get_parameter ('meta_login_background'))) - $error_update[] = __('Login background metaconsole'); + return false; + } - if (!config_update_value ('meta_custom_docs_url', (string) get_parameter ('meta_custom_docs_url'))) - $error_update[] = __('Custom Docs url'); - if (!config_update_value ('meta_custom_support_url', (string) get_parameter ('meta_custom_support_url'))) - $error_update[] = __('Custom support url'); + $update_config = (bool) get_parameter('update_config'); - if (!config_update_value ('vc_refr', get_parameter('vc_refr'))) - $error_update[] = __('Default interval for refresh on Visual Console'); - if (!config_update_value ('vc_favourite_view', (int) get_parameter('vc_favourite_view', 0))) - $error_update[] = __('Default line favourite_view for the Visual Console'); - if (!config_update_value ('vc_menu_items', (int) get_parameter('vc_menu_items', 10))) - $error_update[] = __('Default line menu items for the Visual Console'); - if (!config_update_value ('vc_line_thickness', (int) get_parameter('vc_line_thickness'))) - $error_update[] = __('Default line thickness for the Visual Console'); + if ($update_config) { + db_pandora_audit('Setup', 'Setup has changed'); + } else { + // Do nothing. + return false; + } - if (!config_update_value ('ser_menu_items', (int) get_parameter('ser_menu_items', 10))) - $error_update[] = __('Default line menu items for the Services'); + $error_update = []; - if (!config_update_value ('agent_size_text_small', get_parameter('agent_size_text_small'))) - $error_update[] = __('Agent size text'); - if (!config_update_value ('agent_size_text_medium', get_parameter('agent_size_text_medium'))) - $error_update[] = __('Agent size text'); - if (!config_update_value ('module_size_text_small', get_parameter('module_size_text_small'))) - $error_update[] = __('Module size text'); - if (!config_update_value ('module_size_text_medium', get_parameter('module_size_text_medium'))) - $error_update[] = __('Description size text'); - if (!config_update_value ('description_size_text', get_parameter('description_size_text'))) - $error_update[] = __('Description size text'); - if (!config_update_value ('item_title_size_text', get_parameter('item_title_size_text'))) - $error_update[] = __('Item title size text'); - if (!config_update_value ('gis_label', get_parameter ('gis_label'))) - $error_update[] = __('GIS Labels'); - if (!config_update_value ('simple_module_value', get_parameter ('simple_module_value'))) - $error_update[] = __('Show units in values report'); - if (!config_update_value ('gis_default_icon', get_parameter ('gis_default_icon'))) - $error_update[] = __('Default icon in GIS'); - if (!config_update_value ('autohidden_menu', get_parameter('autohidden_menu'))) - $error_update[] = __('Autohidden menu'); - if (!config_update_value ('visual_animation', get_parameter('visual_animation'))) - $error_update[] = __('visual_animation'); - if (!config_update_value ('disable_help', get_parameter('disable_help'))) - $error_update[] = __('Disable help'); - if (!config_update_value ('fixed_graph', get_parameter('fixed_graph'))) - $error_update[] = __('Fixed graph'); - if (!config_update_value ('fixed_header', get_parameter('fixed_header'))) - $error_update[] = __('Fixed header'); - if (!config_update_value ('fixed_menu', get_parameter('fixed_menu'))) - $error_update[] = __('Fixed menu'); - if (!config_update_value ('paginate_module', get_parameter('paginate_module'))) - $error_update[] = __('Paginate module'); - if (!config_update_value ('graphviz_bin_dir', get_parameter('graphviz_bin_dir'))) - $error_update[] = __('Custom graphviz directory'); - if (!config_update_value ('networkmap_max_width', get_parameter('networkmap_max_width'))) - $error_update[] = __('Networkmap max width'); - if (!config_update_value ('short_module_graph_data', get_parameter('short_module_graph_data'))) - $error_update[] = __('Shortened module graph data'); - if (!config_update_value ('show_group_name', get_parameter('show_group_name'))) - $error_update[] = __('Show the group name instead the group icon.'); - if (!config_update_value ('custom_graph_width', (int) get_parameter('custom_graph_width', 1))) - $error_update[] = __('Default line thickness for the Custom Graph.'); - if (!config_update_value ('type_module_charts', (string) get_parameter('type_module_charts', 'area'))) - $error_update[] = __('Default type of module charts.'); - if (!config_update_value ('type_interface_charts', (string) get_parameter('type_interface_charts', 'line'))) - $error_update[] = __('Default type of interface charts.'); - if (!config_update_value ('render_proc', (bool) get_parameter('render_proc', false))) - $error_update[] = __('Display data of proc modules in other format'); - if (!config_update_value ('render_proc_ok', (string) get_parameter('render_proc_ok', __('Ok') ))) - $error_update[] = __('Display text proc modules have state is ok'); - if (!config_update_value ('render_proc_fail', (string) get_parameter('render_proc_fail', __('Fail') ))) - $error_update[] = __('Display text when proc modules have state critical'); - //Daniel maya 02/06/2016 Display menu with click --INI - if (!config_update_value ('click_display', (bool) get_parameter('click_display', false))) - $error_update[] = __('Display lateral menus with left click'); - //Daniel maya 02/06/2016 Display menu with click --END - if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { - if (!config_update_value ('service_label_font_size', get_parameter('service_label_font_size', false))) - $error_update[] = __('Service label font size'); - if (!config_update_value ('service_item_padding_size', get_parameter('service_item_padding_size', false))) - $error_update[] = __('Service item padding size'); - } - if (!config_update_value ('percentil', (int) get_parameter('percentil', 0))) - $error_update[] = __('Default percentil'); + $sec2 = get_parameter_get('sec2'); + switch ($sec2) { + case 'godmode/setup/setup': + $section_setup = get_parameter('section'); + // MAIN SETUP. + // Setup now is divided in different tabs. + switch ($section_setup) { + case 'general': + if (!config_update_value('language', (string) get_parameter('language'))) { + $error_update[] = __('Language settings'); + } - if (!config_update_value ('full_scale_option', (int) get_parameter('full_scale_option', 0))) - $error_update[] = __('Default full scale (TIP)'); + if (!config_update_value('remote_config', (string) get_parameter('remote_config'))) { + $error_update[] = __('Remote config directory'); + } - if (!config_update_value ('type_mode_graph', (int) get_parameter('type_mode_graph', 0))) - $error_update[] = __('Default soft graphs'); + if (!config_update_value('phantomjs_bin', (string) get_parameter('phantomjs_bin'))) { + $error_update[] = __('phantomjs config directory'); + } - if (!config_update_value ('zoom_graph', (int) get_parameter('zoom_graph', 1))) - $error_update[] = __('Default zoom graphs'); + if (!config_update_value('loginhash_pwd', io_input_password((string) get_parameter('loginhash_pwd')))) { + $error_update[] = __('Auto login (hash) password'); + } - if (!config_update_value ('graph_image_height', (int) get_parameter('graph_image_height', 280))) - $error_update[] = __('Default height of the chart image'); + if (!config_update_value('timesource', (string) get_parameter('timesource'))) { + $error_update[] = __('Time source'); + } - if (!config_update_value ('classic_menu', (bool) get_parameter('classic_menu', false))) - $error_update[] = __('Classic menu mode'); + if (!config_update_value('autoupdate', (bool) get_parameter('autoupdate'))) { + $error_update[] = __('Automatic check for updates'); + } + if (!config_update_value('cert_path', (bool) get_parameter('cert_path'))) { + $error_update[] = __('SSL cert path'); + } - //-------------------------------------------------- - // CUSTOM VALUES POST PROCESS - //-------------------------------------------------- - $custom_value = get_parameter('custom_value'); - $custom_text = get_parameter('custom_text'); - $custom_value_add = (bool)get_parameter('custom_value_add', 0); - $custom_value_to_delete = get_parameter('custom_value_to_delete', 0); - - $custom_value = str_replace(',', '.', $custom_value); - - if ($custom_value_add) { - require_once("include/functions_post_process.php"); - - if (!post_process_add_custom_value( - $custom_text, (string)$custom_value)) - $error_update[] = __('Add the custom post process'); - } - - if ($custom_value_to_delete > 0) { - require_once("include/functions_post_process.php"); - - if (!post_process_delete_custom_value($custom_value_to_delete)) { - $error_update[] = __('Delete the custom post process'); - } - } - //-------------------------------------------------- + if (!config_update_value('https', (bool) get_parameter('https'))) { + $error_update[] = __('Enforce https'); + } - //-------------------------------------------------- - // CUSTOM INTERVAL VALUES - //-------------------------------------------------- - $interval_values = get_parameter ('interval_values'); - - // Add new interval value if is provided - $interval_value = (float) get_parameter ('interval_value', 0); - - if ($interval_value > 0) { - $interval_unit = (int) get_parameter ('interval_unit'); - $new_interval = $interval_value * $interval_unit; - - if ($interval_values === '') { - $interval_values = $new_interval; - } - else { - $interval_values_array = explode(',',$interval_values); - if(!in_array($new_interval, $interval_values_array)) { - $interval_values_array[] = $new_interval; - $interval_values = implode(',',$interval_values_array); - } - } - } - - // Delete interval value if is required - $interval_to_delete = (float) get_parameter('interval_to_delete'); - if ($interval_to_delete > 0) { - $interval_values_array = explode(',',$interval_values); - foreach ($interval_values_array as $k => $iva) { - if ($interval_to_delete == $iva) { - unset($interval_values_array[$k]); - } - } - $interval_values = implode(',',$interval_values_array); - } - - if (!config_update_value ('interval_values', $interval_values)) - $error_update[] = __('Delete interval'); - //-------------------------------------------------- - - if (!config_update_value ('custom_report_info', get_parameter('custom_report_info'))) - $error_update[] = __('Custom report info'); - - - // Juanma (06/05/2014) New feature: Custom front page for reports - if (!config_update_value ('custom_report_front', get_parameter('custom_report_front'))) - $error_update[] = __('Custom report front'); - - if (!config_update_value ('custom_report_front_font', get_parameter('custom_report_front_font'))) - $error_update[] = __('Custom report front') . ' - ' . __('Font family'); - - if (!config_update_value ('custom_report_front_logo', get_parameter('custom_report_front_logo'))) - $error_update[] = __('Custom report front') . ' - ' . __('Custom logo'); - - if (!config_update_value ('custom_report_front_header', get_parameter('custom_report_front_header'))) - $error_update[] = __('Custom report front') . ' - ' . __('Header'); - - if (!config_update_value ('custom_report_front_firstpage', get_parameter('custom_report_front_firstpage'))) - $error_update[] = __('Custom report front') . ' - ' . __('First page'); - - if (!config_update_value ('custom_report_front_footer', get_parameter('custom_report_front_footer'))) - $error_update[] = __('Custom report front') . ' - ' . __('Footer'); + if (!config_update_value('use_cert', (bool) get_parameter('use_cert'))) { + $error_update[] = __('Use cert.'); + } - if (!config_update_value ('csv_divider', (string) get_parameter('csv_divider', ';'))) - $error_update[] = __('CSV divider'); - - break; - case 'net': - if (!config_update_value ('netflow_path', get_parameter ('netflow_path'))) - $error_update[] = __('Data storage path'); - if (!config_update_value ('netflow_interval', (int)get_parameter ('netflow_interval'))) - $error_update[] = __('Daemon interval'); - if (!config_update_value ('netflow_daemon', get_parameter ('netflow_daemon'))) - $error_update[] = __('Daemon binary path'); - if (!config_update_value ('netflow_nfdump', get_parameter ('netflow_nfdump'))) - $error_update[] = __('Nfdump binary path'); - if (!config_update_value ('netflow_nfexpire', get_parameter ('netflow_nfexpire'))) - $error_update[] = __('Nfexpire binary path'); - if (!config_update_value ('netflow_max_resolution', (int)get_parameter ('netflow_max_resolution'))) - $error_update[] = __('Maximum chart resolution'); - if (!config_update_value ('netflow_disable_custom_lvfilters', get_parameter ('netflow_disable_custom_lvfilters'))) - $error_update[] = __('Disable custom live view filters'); - if (!config_update_value ('netflow_max_lifetime', (int) get_parameter ('netflow_max_lifetime'))) - $error_update[] = __('Netflow max lifetime'); - if (!config_update_value ('netflow_get_ip_hostname', (int) get_parameter ('netflow_get_ip_hostname'))) - $error_update[] = __('Name resolution for IP address'); - break; - case 'log': - if (!config_update_value ('elasticsearch_ip', get_parameter('elasticsearch_ip'))) - $error_update[] = __('IP ElasticSearch server'); - if (!config_update_value ('elasticsearch_port', get_parameter('elasticsearch_port'))) - $error_update[] = __('Port ElasticSearch server'); - if (!config_update_value ('number_logs_viewed', (int)get_parameter('number_logs_viewed'))) - $error_update[] = __('Number of logs viewed'); - if (!config_update_value ('Days_purge_old_information', (int)get_parameter('Days_purge_old_information'))) - $error_update[] = __('Days to purge old information'); - break; - case 'hist_db': - if (!config_update_value ('history_db_enabled', get_parameter ('history_db_enabled'))) - $error_update[] = __('Enable history database'); - if (!config_update_value ('history_event_enabled', get_parameter ('history_event_enabled'))) - $error_update[] = __('Enable history event'); - if (!config_update_value ('history_db_host', get_parameter ('history_db_host'))) - $error_update[] = __('Host'); - if (!config_update_value ('history_db_port', get_parameter ('history_db_port'))) - $error_update[] = __('Port'); - if (!config_update_value ('history_db_name', get_parameter ('history_db_name'))) - $error_update[] = __('Database name'); - if (!config_update_value ('history_db_user', get_parameter ('history_db_user'))) - $error_update[] = __('Database user'); - if (!config_update_value ('history_db_pass', io_input_password(get_parameter ('history_db_pass')))) - $error_update[] = __('Database password'); - if (!config_update_value ('history_db_days', get_parameter ('history_db_days'))) - $error_update[] = __('Days'); - if (!config_update_value ('history_event_days', get_parameter ('history_event_days'))) - $error_update[] = __('Event Days'); - if (!config_update_value ('history_db_step', get_parameter ('history_db_step'))) - $error_update[] = __('Step'); - if (!config_update_value ('history_db_delay', get_parameter ('history_db_delay'))) - $error_update[] = __('Delay'); - break; - case 'ehorus': - if (!config_update_value('ehorus_enabled', (int) get_parameter('ehorus_enabled', $config['ehorus_enabled']))) - $error_update[] = __('Enable eHorus'); - if (!config_update_value('ehorus_user', (string) get_parameter('ehorus_user', $config['ehorus_user']))) - $error_update[] = __('eHorus user'); - if (!config_update_value('ehorus_pass', io_input_password((string) get_parameter('ehorus_pass', $config['ehorus_pass'])))) - $error_update[] = __('eHorus password'); - if (!config_update_value('ehorus_hostname', (string) get_parameter('ehorus_hostname', $config['ehorus_hostname']))) - $error_update[] = __('eHorus API hostname'); - if (!config_update_value('ehorus_port', (int) get_parameter('ehorus_port', $config['ehorus_port']))) - $error_update[] = __('eHorus API port'); - if (!config_update_value('ehorus_req_timeout', (int) get_parameter('ehorus_req_timeout', $config['ehorus_req_timeout']))) - $error_update[] = __('eHorus request timeout'); - if (!config_update_value('ehorus_custom_field', (string) get_parameter('ehorus_custom_field', $config['ehorus_custom_field']))) - $error_update[] = __('eHorus id custom field'); - break; - } - } + if (!config_update_value('attachment_store', (string) get_parameter('attachment_store'))) { + $error_update[] = __('Attachment store'); + } - if (count($error_update) > 0) { - $config['error_config_update_config'] = array(); - $config['error_config_update_config']['correct'] = false; - $values = implode(', ', $error_update); - $config['error_config_update_config']['message'] = sprintf(__('Failed updated: the next values cannot update: %s'), $values); - } - else { - $config['error_config_update_config'] = array(); - $config['error_config_update_config']['correct'] = true; - } + if (!config_update_value('list_ACL_IPs_for_API', (string) get_parameter('list_ACL_IPs_for_API'))) { + $error_update[] = __('IP list with API access'); + } - enterprise_include_once('include/functions_policies.php'); - $enterprise = enterprise_include_once ('include/functions_skins.php'); - if ($enterprise !== ENTERPRISE_NOT_HOOK) { - $config['relative_path'] = get_parameter('relative_path', $config['relative_path']); - } + if (!config_update_value('api_password', io_input_password(get_parameter('api_password')))) { + $error_update[] = __('API password'); + } + + if (!config_update_value('activate_gis', (bool) get_parameter('activate_gis'))) { + $error_update[] = __('Enable GIS features'); + } + + if (!config_update_value('integria_inventory', get_parameter('integria_inventory'))) { + $error_update[] = __('Integria inventory'); + } + + if (!config_update_value('integria_api_password', io_input_password(get_parameter('integria_api_password')))) { + $error_update[] = __('Integria API password'); + } + + if (!config_update_value('integria_url', get_parameter('integria_url'))) { + $error_update[] = __('Integria URL'); + } + + if (!config_update_value('activate_netflow', (bool) get_parameter('activate_netflow'))) { + $error_update[] = __('Enable Netflow'); + } + + $timezone = (string) get_parameter('timezone'); + if ($timezone != '') { + if (!config_update_value('timezone', $timezone)) { + $error_update[] = __('Timezone setup'); + } + } + + if (!config_update_value('sound_alert', get_parameter('sound_alert'))) { + $error_update[] = __('Sound for Alert fired'); + } + + if (!config_update_value('sound_critical', get_parameter('sound_critical'))) { + $error_update[] = __('Sound for Monitor critical'); + } + + if (!config_update_value('sound_warning', get_parameter('sound_warning'))) { + $error_update[] = __('Sound for Monitor warning'); + } + + // Update of Pandora FMS license. + $update_manager_installed = db_get_value('value', 'tconfig', 'token', 'update_manager_installed'); + + if ($update_manager_installed == 1) { + $license_info_key = get_parameter('license_info_key', ''); + if (!empty($license_info_key)) { + $values = [db_escape_key_identifier('value') => $license_info_key]; + $where = [db_escape_key_identifier('key') => 'customer_key']; + $update_manage_settings_result = db_process_sql_update('tupdate_settings', $values, $where); + if ($update_manage_settings_result === false) { + $error_update[] = __('License information'); + } + } + } + + if (!config_update_value('public_url', get_parameter('public_url'))) { + $error_update[] = __('Public URL'); + } + + if (!config_update_value('referer_security', get_parameter('referer_security'))) { + $error_update[] = __('Referer security'); + } + + if (!config_update_value('event_storm_protection', get_parameter('event_storm_protection'))) { + $error_update[] = __('Event storm protection'); + } + + if (!config_update_value('command_snapshot', get_parameter('command_snapshot'))) { + $error_update[] = __('Command Snapshot'); + } + + if (!config_update_value('server_log_dir', get_parameter('server_log_dir'))) { + $error_update[] = __('Server logs directory'); + } + + if (!config_update_value('max_log_size', get_parameter('max_log_size'))) { + $error_update[] = __('Log size limit in system logs viewer extension'); + } + + if (!config_update_value('tutorial_mode', get_parameter('tutorial_mode'))) { + $error_update[] = __('Tutorial mode'); + } + + if (!config_update_value('past_planned_downtimes', get_parameter('past_planned_downtimes'))) { + $error_update[] = __('Allow create planned downtimes in the past'); + } + + if (!config_update_value('limit_parameters_massive', get_parameter('limit_parameters_massive'))) { + $error_update[] = __('Limit parameters bulk'); + } + + if (!config_update_value('identification_reminder', get_parameter('identification_reminder'))) { + $error_update[] = __('Identification_reminder'); + } + + if (!config_update_value('include_agents', (bool) get_parameter('include_agents'))) { + $error_update[] = __('Include_agents'); + } + + if (!config_update_value('alias_as_name', get_parameter('alias_as_name'))) { + $error_update[] = __('alias_as_name'); + } + + if (!config_update_value('auditdir', get_parameter('auditdir'))) { + $error_update[] = __('Audit log directory'); + } + break; + + case 'enterprise': + if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { + if (!config_update_value('trap2agent', (string) get_parameter('trap2agent'))) { + $error_update[] = __('Forward SNMP traps to agent (if exist)'); + } + + if (!config_update_value('acl_enterprise', get_parameter('acl_enterprise'))) { + $error_update[] = __('Use Enterprise ACL System'); + } + + if (!config_update_value('metaconsole', get_parameter('metaconsole'))) { + $error_update[] = __('Activate Metaconsole'); + } + + if (!config_update_value('collection_max_size', get_parameter('collection_max_size'))) { + $error_update[] = __('Size of collection'); + } + + if (!config_update_value('event_replication', (int) get_parameter('event_replication'))) { + $error_update[] = __('Events replication'); + } + + if ((int) get_parameter('event_replication') == 1) { + if (!config_update_value('replication_interval', (int) get_parameter('replication_interval'))) { + $error_update[] = __('Replication interval'); + } + + if (!config_update_value('replication_limit', (int) get_parameter('replication_limit'))) { + $error_update[] = __('Replication limit'); + } + + if (!config_update_value('replication_mode', (string) get_parameter('replication_mode'))) { + $error_update[] = __('Replication mode'); + } + + if (!config_update_value('show_events_in_local', (string) get_parameter('show_events_in_local'))) { + $error_update[] = __('Show events list in local console (read only)'); + } + } + + if (!config_update_value('replication_dbengine', (string) get_parameter('replication_dbengine'))) { + $error_update[] = __('Replication DB engine'); + } + + if (!config_update_value('replication_dbhost', (string) get_parameter('replication_dbhost'))) { + $error_update[] = __('Replication DB host'); + } + + if (!config_update_value('replication_dbname', (string) get_parameter('replication_dbname'))) { + $error_update[] = __('Replication DB database'); + } + + if (!config_update_value('replication_dbuser', (string) get_parameter('replication_dbuser'))) { + $error_update[] = __('Replication DB user'); + } + + if (!config_update_value('replication_dbpass', io_input_password((string) get_parameter('replication_dbpass')))) { + $error_update[] = __('Replication DB password'); + } + + if (!config_update_value('replication_dbport', (string) get_parameter('replication_dbport'))) { + $error_update[] = __('Replication DB port'); + } + + if (!config_update_value('metaconsole_agent_cache', (int) get_parameter('metaconsole_agent_cache'))) { + $error_update[] = __('Metaconsole agent cache'); + } + + if (!config_update_value('log_collector', (bool) get_parameter('log_collector'))) { + $error_update[] = __('Activate Log Collector'); + } + + if (!config_update_value('enable_update_manager', get_parameter('enable_update_manager'))) { + $error_update[] = __('Enable Update Manager'); + } + + if (!config_update_value('ipam_ocuppied_critical_treshold', get_parameter('ipam_ocuppied_critical_treshold'))) { + $error_update[] = __('Ipam Ocuppied Manager Critical'); + } + + if (!config_update_value('ipam_ocuppied_warning_treshold', get_parameter('ipam_ocuppied_warning_treshold'))) { + $error_update[] = __('Ipam Ocuppied Manager Warning'); + } + + $inventory_changes_blacklist = get_parameter('inventory_changes_blacklist', []); + if (!config_update_value('inventory_changes_blacklist', implode(',', $inventory_changes_blacklist))) { + $error_update[] = __('Inventory changes blacklist'); + } + + if (!config_update_value('email_from_dir', get_parameter('email_from_dir'))) { + $error_update[] = __('From dir'); + } + + if (!config_update_value('email_from_name', get_parameter('email_from_name'))) { + $error_update[] = __('From name'); + } + + if (!config_update_value('email_smtpServer', get_parameter('email_smtpServer'))) { + $error_update[] = __('Server SMTP'); + } + + if (!config_update_value('email_smtpPort', (int) get_parameter('email_smtpPort'))) { + $error_update[] = __('Port SMTP'); + } + + if (!config_update_value('email_encryption', get_parameter('email_encryption'))) { + $error_update[] = __('Encryption'); + } + + if (!config_update_value('email_username', get_parameter('email_username'))) { + $error_update[] = __('Email user'); + } + + if (!config_update_value('email_password', get_parameter('email_password'))) { + $error_update[] = __('Email password'); + } + } + break; + + case 'pass': + if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { + if (!config_update_value('enable_pass_policy', get_parameter('enable_pass_policy'))) { + $error_update[] = __('Enable password policy'); + } + + if (!config_update_value('pass_size', get_parameter('pass_size'))) { + $error_update[] = __('Min. size password'); + } + + if (!config_update_value('pass_expire', get_parameter('pass_expire'))) { + $error_update[] = __('Password expiration'); + } + + if (!config_update_value('first_login', get_parameter('first_login'))) { + $error_update[] = __('Force change password on first login'); + } + + if (!config_update_value('mins_fail_pass', get_parameter('mins_fail_pass'))) { + $error_update[] = __('User blocked if login fails'); + } + + if (!config_update_value('number_attempts', get_parameter('number_attempts'))) { + $error_update[] = __('Number of failed login attempts'); + } + + if (!config_update_value('pass_needs_numbers', get_parameter('pass_needs_numbers'))) { + $error_update[] = __('Password must have numbers'); + } + + if (!config_update_value('pass_needs_symbols', get_parameter('pass_needs_symbols'))) { + $error_update[] = __('Password must have symbols'); + } + + if (!config_update_value('enable_pass_policy_admin', get_parameter('enable_pass_policy_admin'))) { + $error_update[] = __('Apply password policy to admin users'); + } + + if (!config_update_value('enable_pass_history', get_parameter('enable_pass_history'))) { + $error_update[] = __('Enable password history'); + } + + if (!config_update_value('compare_pass', get_parameter('compare_pass'))) { + $error_update[] = __('Compare previous password'); + } + + if (!config_update_value('reset_pass_option', (bool) get_parameter('reset_pass_option'))) { + $error_update[] = __('Activate reset password'); + } + } + break; + + case 'auth': + // AUTHENTICATION SETUP. + if (!config_update_value('auth', get_parameter('auth'))) { + $error_update[] = __('Authentication method'); + } + + if (!config_update_value('autocreate_remote_users', get_parameter('autocreate_remote_users'))) { + $error_update[] = __('Autocreate remote users'); + } + + if (!config_update_value('default_remote_profile', get_parameter('default_remote_profile'))) { + $error_update[] = __('Autocreate profile'); + } + + if (!config_update_value('default_remote_group', get_parameter('default_remote_group'))) { + $error_update[] = __('Autocreate profile group'); + } + + if (!config_update_value('default_assign_tags', implode(',', get_parameter('default_assign_tags')))) { + $error_update[] = __('Autocreate profile tags'); + } + + if (!config_update_value('default_no_hierarchy', (int) get_parameter('default_no_hierarchy'))) { + $error_update[] = __('Automatically assigned no hierarchy'); + } + + if (!config_update_value('autocreate_blacklist', get_parameter('autocreate_blacklist'))) { + $error_update[] = __('Autocreate blacklist'); + } + + if (!config_update_value('ad_server', get_parameter('ad_server'))) { + $error_update[] = __('Active directory server'); + } + + if (!config_update_value('ad_port', get_parameter('ad_port'))) { + $error_update[] = __('Active directory port'); + } + + if (!config_update_value('ad_start_tls', get_parameter('ad_start_tls'))) { + $error_update[] = __('Start TLS'); + } + + if (!config_update_value('ad_advanced_config', get_parameter('ad_advanced_config'))) { + $error_update[] = __('Advanced Config AD'); + } + + if (!config_update_value('ldap_advanced_config', get_parameter('ldap_advanced_config'))) { + $error_update[] = __('Advanced Config LDAP'); + } + + if (!config_update_value('ad_domain', get_parameter('ad_domain'))) { + $error_update[] = __('Domain'); + } + + if (!config_update_value('ad_adv_perms', get_parameter('ad_adv_perms'))) { + $error_update[] = __('Advanced Permisions AD'); + } + + if (!config_update_value('ldap_adv_perms', get_parameter('ldap_adv_perms'))) { + $error_update[] = __('Advanced Permissions LDAP'); + } + + if (!config_update_value('ldap_server', get_parameter('ldap_server'))) { + $error_update[] = __('LDAP server'); + } + + if (!config_update_value('ldap_port', get_parameter('ldap_port'))) { + $error_update[] = __('LDAP port'); + } + + if (!config_update_value('ldap_version', get_parameter('ldap_version'))) { + $error_update[] = __('LDAP version'); + } + + if (!config_update_value('ldap_start_tls', get_parameter('ldap_start_tls'))) { + $error_update[] = __('Start TLS'); + } + + if (!config_update_value('ldap_base_dn', get_parameter('ldap_base_dn'))) { + $error_update[] = __('Base DN'); + } + + if (!config_update_value('ldap_login_attr', get_parameter('ldap_login_attr'))) { + $error_update[] = __('Login attribute'); + } + + if (!config_update_value('ldap_admin_login', get_parameter('ldap_admin_login'))) { + $error_update[] = __('Admin LDAP login'); + } + + if (!config_update_value('ldap_admin_pass', get_parameter('ldap_admin_pass'))) { + $error_update[] = __('Admin LDAP password'); + } + + if (!config_update_value('fallback_local_auth', get_parameter('fallback_local_auth'))) { + $error_update[] = __('Fallback to local authentication'); + } + + if (!config_update_value('ldap_login_user_attr', get_parameter('ldap_login_user_attr'))) { + $error_update[] = __('Login user attribute'); + } + + if (!config_update_value('ldap_function', get_parameter('ldap_function'))) { + $error_update[] = __('LDAP function'); + } + + if (isset($config['fallback_local_auth']) && $config['fallback_local_auth'] == 0) { + if (!config_update_value('ldap_save_password', get_parameter('ldap_save_password'))) { + $error_update[] = __('Save Password'); + } + } else if (isset($config['fallback_local_auth']) && $config['fallback_local_auth'] == 1) { + config_update_value('ldap_save_password', 1); + } + + if (!config_update_value('rpandora_server', get_parameter('rpandora_server'))) { + $error_update[] = __('MySQL host'); + } + + if (!config_update_value('rpandora_port', get_parameter('rpandora_port'))) { + $error_update[] = __('MySQL port'); + } + + if (!config_update_value('rpandora_dbname', get_parameter('rpandora_dbname'))) { + $error_update[] = __('Database name'); + } + + if (!config_update_value('rpandora_user', get_parameter('rpandora_user'))) { + $error_update[] = __('User'); + } + + if (!config_update_value('rpandora_pass', io_input_password(get_parameter('rpandora_pass')))) { + $error_update[] = __('Password'); + } + + if (!config_update_value('rintegria_server', get_parameter('rintegria_server'))) { + $error_update[] = __('Integria host'); + } + + if (!config_update_value('rintegria_port', get_parameter('rintegria_port'))) { + $error_update[] = __('MySQL port'); + } + + if (!config_update_value('rintegria_dbname', get_parameter('rintegria_dbname'))) { + $error_update[] = __('Database name'); + } + + if (!config_update_value('rintegria_user', get_parameter('rintegria_user'))) { + $error_update[] = __('User'); + } + + if (!config_update_value('rintegria_pass', io_input_password(get_parameter('rintegria_pass')))) { + $error_update[] = __('Password'); + } + + if (!config_update_value('saml_path', get_parameter('saml_path'))) { + $error_update[] = __('Saml path'); + } + + if (!config_update_value('double_auth_enabled', get_parameter('double_auth_enabled'))) { + $error_update[] = __('Double authentication'); + } + + if (!config_update_value('session_timeout', get_parameter('session_timeout'))) { + $error_update[] = __('Session timeout'); + } + break; + + case 'perf': + // PERFORMANCE SETUP. + if (!config_update_value('event_purge', get_parameter('event_purge'))) { + $check_metaconsole_events_history = get_parameter('metaconsole_events_history', -1); + $error_update[] = $check_metaconsole_events_history; + } + + if ($check_metaconsole_events_history != -1) { + if (!config_update_value('metaconsole_events_history', get_parameter('metaconsole_events_history'))) { + $error_update[] = __('Max. days before delete events'); + } + } + + if (!config_update_value('trap_purge', get_parameter('trap_purge'))) { + $error_update[] = __('Max. days before delete traps'); + } + + if (!config_update_value('string_purge', get_parameter('string_purge'))) { + $error_update[] = __('Max. days before delete string data'); + } + + if (!config_update_value('audit_purge', get_parameter('audit_purge'))) { + $error_update[] = __('Max. days before delete audit events'); + } + + if (!config_update_value('gis_purge', get_parameter('gis_purge'))) { + $error_update[] = __('Max. days before delete GIS data'); + } + + if (!config_update_value('days_purge', (int) get_parameter('days_purge'))) { + $error_update[] = __('Max. days before purge'); + } + + if (!config_update_value('days_delete_unknown', (int) get_parameter('days_delete_unknown'))) { + $error_update[] = __('Max. days before delete unknown modules'); + } + + if (!config_update_value('days_compact', (int) get_parameter('days_compact'))) { + $error_update[] = __('Max. days before compact data'); + } + + if (!config_update_value('days_autodisable_deletion', (int) get_parameter('days_autodisable_deletion'))) { + $error_update[] = __('Max. days before autodisable deletion'); + } + + if (!config_update_value('report_limit', (int) get_parameter('report_limit'))) { + $error_update[] = __('Item limit for realtime reports)'); + } + + if (!config_update_value('step_compact', (int) get_parameter('step_compact'))) { + $error_update[] = __('Compact interpolation in hours (1 Fine-20 bad)'); + } + + if (!config_update_value('event_view_hr', (int) get_parameter('event_view_hr'))) { + $error_update[] = __('Default hours for event view'); + } + + if (!config_update_value('realtimestats', get_parameter('realtimestats'))) { + $error_update[] = __('Use realtime statistics'); + } + + if (!config_update_value('stats_interval', get_parameter('stats_interval'))) { + $error_update[] = __('Batch statistics period (secs)'); + } + + if (!config_update_value('agentaccess', (int) get_parameter('agentaccess'))) { + $error_update[] = __('Use agent access graph'); + } + + if (!config_update_value('num_files_attachment', (int) get_parameter('num_files_attachment'))) { + $error_update[] = __('Max. recommended number of files in attachment directory'); + } + + if (!config_update_value('delete_notinit', get_parameter('delete_notinit'))) { + $error_update[] = __('Delete not init modules'); + } + + if (!config_update_value('big_operation_step_datos_purge', get_parameter('big_operation_step_datos_purge'))) { + $error_update[] = __('Big Operatiopn Step to purge old data'); + } + + if (!config_update_value('small_operation_step_datos_purge', get_parameter('small_operation_step_datos_purge'))) { + $error_update[] = __('Small Operation Step to purge old data'); + } + + if (!config_update_value('num_past_special_days', get_parameter('num_past_special_days'))) { + $error_update[] = __('Retention period of past special days'); + } + + if (!config_update_value('max_macro_fields', get_parameter('max_macro_fields'))) { + $error_update[] = __('Max. macro data fields'); + } + + if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { + if (!config_update_value('inventory_purge', get_parameter('inventory_purge'))) { + $error_update[] = __('Max. days before delete inventory data'); + } + } + + if (!config_update_value('max_graph_container', get_parameter('max_graph_container'))) { + $error_update[] = __('Graph container - Max. Items'); + } + break; + + case 'vis': + // VISUAL STYLES SETUP. + if (!config_update_value('date_format', (string) get_parameter('date_format'))) { + $error_update[] = __('Date format string'); + } + + if (!config_update_value('prominent_time', (string) get_parameter('prominent_time'))) { + $error_update[] = __('Timestamp or time comparation'); + } + + if (!config_update_value('graph_color1', (string) get_parameter('graph_color1'))) { + $error_update[] = __('Graph color #1'); + } + + if (!config_update_value('graph_color2', (string) get_parameter('graph_color2'))) { + $error_update[] = __('Graph color #2'); + } + + if (!config_update_value('graph_color3', (string) get_parameter('graph_color3'))) { + $error_update[] = __('Graph color #3'); + } + + if (!config_update_value('graph_color4', (string) get_parameter('graph_color4'))) { + $error_update[] = __('Graph color #4'); + } + + if (!config_update_value('graph_color5', (string) get_parameter('graph_color5'))) { + $error_update[] = __('Graph color #5'); + } + + if (!config_update_value('graph_color6', (string) get_parameter('graph_color6'))) { + $error_update[] = __('Graph color #6'); + } + + if (!config_update_value('graph_color7', (string) get_parameter('graph_color7'))) { + $error_update[] = __('Graph color #7'); + } + + if (!config_update_value('graph_color8', (string) get_parameter('graph_color8'))) { + $error_update[] = __('Graph color #8'); + } + + if (!config_update_value('graph_color9', (string) get_parameter('graph_color9'))) { + $error_update[] = __('Graph color #9'); + } + + if (!config_update_value('graph_color10', (string) get_parameter('graph_color10'))) { + $error_update[] = __('Graph color #10'); + } + + if (!config_update_value('interface_unit', (string) get_parameter('interface_unit', __('Bytes')))) { + $error_update[] = __('Value to interface graphics'); + } + + if (!config_update_value('graph_precision', (string) get_parameter('graph_precision', 1))) { + $error_update[] = __('Data precision for reports'); + } + + $style = (string) get_parameter('style'); + if ($style != $config['style']) { + $style = substr($style, 0, (strlen($style) - 4)); + } + + if (!config_update_value('style', $style)) { + $error_update[] = __('Style template'); + } + + if (!config_update_value('block_size', (int) get_parameter('block_size'))) { + $error_update[] = __('Block size for pagination'); + } + + if (!config_update_value('round_corner', (bool) get_parameter('round_corner'))) { + $error_update[] = __('Use round corners'); + } + + if (!config_update_value('show_qr_code_header', (bool) get_parameter('show_qr_code_header'))) { + $error_update[] = __('Show QR code header'); + } + + if (!config_update_value('status_images_set', (string) get_parameter('status_images_set'))) { + $error_update[] = __('Status icon set'); + } + + if (!config_update_value('fontpath', (string) get_parameter('fontpath'))) { + $error_update[] = __('Font path'); + } + + if (!config_update_value('font_size', get_parameter('font_size'))) { + $error_update[] = __('Font size'); + } + + if (!config_update_value('custom_favicon', (string) get_parameter('custom_favicon'))) { + $error_update[] = __('Custom favicon'); + } + + if (!config_update_value('custom_logo', (string) get_parameter('custom_logo'))) { + $error_update[] = __('Custom logo'); + } + + if (!config_update_value('custom_logo_white_bg', (string) get_parameter('custom_logo_white_bg'))) { + $error_update[] = __('Custom logo white background'); + } + + if (!config_update_value('custom_logo_login', (string) get_parameter('custom_logo_login'))) { + $error_update[] = __('Custom logo login'); + } + + if (!config_update_value('custom_splash_login', (string) get_parameter('custom_splash_login'))) { + $error_update[] = __('Custom splash login'); + } + + if (!config_update_value('custom_docs_logo', (string) get_parameter('custom_docs_logo'))) { + $error_update[] = __('Custom documentation logo'); + } + + if (!config_update_value('custom_support_logo', (string) get_parameter('custom_support_logo'))) { + $error_update[] = __('Custom support logo'); + } + + if (!config_update_value('custom_network_center_logo', (string) get_parameter('custom_network_center_logo'))) { + $error_update[] = __('Custom networkmap center logo'); + } + + if (!config_update_value('custom_mobile_console_logo', (string) get_parameter('custom_mobile_console_logo'))) { + $error_update[] = __('Custom networkmap center logo'); + } + + if (!config_update_value('custom_title1_login', (string) get_parameter('custom_title1_login'))) { + $error_update[] = __('Custom title1 login'); + } + + if (!config_update_value('custom_title2_login', (string) get_parameter('custom_title2_login'))) { + $error_update[] = __('Custom title2 login'); + } + + if (!config_update_value('login_background', (string) get_parameter('login_background'))) { + $error_update[] = __('Login background'); + } + + if (!config_update_value('custom_docs_url', (string) get_parameter('custom_docs_url'))) { + $error_update[] = __('Custom Docs url'); + } + + if (!config_update_value('custom_support_url', (string) get_parameter('custom_support_url'))) { + $error_update[] = __('Custom support url'); + } + + if (!config_update_value('rb_product_name', (string) get_parameter('rb_product_name'))) { + $error_update[] = __('Product name'); + } + + if (!config_update_value('rb_copyright_notice', (string) get_parameter('rb_copyright_notice'))) { + $error_update[] = __('Copyright notice'); + } + + if (!config_update_value('meta_custom_logo', (string) get_parameter('meta_custom_logo'))) { + $error_update[] = __('Custom logo metaconsole'); + } + + if (!config_update_value('meta_custom_logo_white_bg', (string) get_parameter('meta_custom_logo_white_bg'))) { + $error_update[] = __('Custom logo metaconsole (white background)'); + } + + if (!config_update_value('meta_custom_logo_login', (string) get_parameter('meta_custom_logo_login'))) { + $error_update[] = __('Custom logo login metaconsole'); + } + + if (!config_update_value('meta_custom_splash_login', (string) get_parameter('meta_custom_splash_login'))) { + $error_update[] = __('Custom splash login metaconsole'); + } + + if (!config_update_value('meta_custom_title1_login', (string) get_parameter('meta_custom_title1_login'))) { + $error_update[] = __('Custom title1 login metaconsole'); + } + + if (!config_update_value('meta_custom_title2_login', (string) get_parameter('meta_custom_title2_login'))) { + $error_update[] = __('Custom title2 login metaconsole'); + } + + if (!config_update_value('meta_login_background', (string) get_parameter('meta_login_background'))) { + $error_update[] = __('Login background metaconsole'); + } + + if (!config_update_value('meta_custom_docs_url', (string) get_parameter('meta_custom_docs_url'))) { + $error_update[] = __('Custom Docs url'); + } + + if (!config_update_value('meta_custom_support_url', (string) get_parameter('meta_custom_support_url'))) { + $error_update[] = __('Custom support url'); + } + + if (!config_update_value('vc_refr', get_parameter('vc_refr'))) { + $error_update[] = __('Default interval for refresh on Visual Console'); + } + + if (!config_update_value('vc_favourite_view', (int) get_parameter('vc_favourite_view', 0))) { + $error_update[] = __('Default line favourite_view for the Visual Console'); + } + + if (!config_update_value('vc_menu_items', (int) get_parameter('vc_menu_items', 10))) { + $error_update[] = __('Default line menu items for the Visual Console'); + } + + if (!config_update_value('vc_line_thickness', (int) get_parameter('vc_line_thickness'))) { + $error_update[] = __('Default line thickness for the Visual Console'); + } + + if (!config_update_value('ser_menu_items', (int) get_parameter('ser_menu_items', 10))) { + $error_update[] = __('Default line menu items for the Services'); + } + + if (!config_update_value('agent_size_text_small', get_parameter('agent_size_text_small'))) { + $error_update[] = __('Agent size text'); + } + + if (!config_update_value('agent_size_text_medium', get_parameter('agent_size_text_medium'))) { + $error_update[] = __('Agent size text'); + } + + if (!config_update_value('module_size_text_small', get_parameter('module_size_text_small'))) { + $error_update[] = __('Module size text'); + } + + if (!config_update_value('module_size_text_medium', get_parameter('module_size_text_medium'))) { + $error_update[] = __('Description size text'); + } + + if (!config_update_value('description_size_text', get_parameter('description_size_text'))) { + $error_update[] = __('Description size text'); + } + + if (!config_update_value('item_title_size_text', get_parameter('item_title_size_text'))) { + $error_update[] = __('Item title size text'); + } + + if (!config_update_value('gis_label', get_parameter('gis_label'))) { + $error_update[] = __('GIS Labels'); + } + + if (!config_update_value('simple_module_value', get_parameter('simple_module_value'))) { + $error_update[] = __('Show units in values report'); + } + + if (!config_update_value('gis_default_icon', get_parameter('gis_default_icon'))) { + $error_update[] = __('Default icon in GIS'); + } + + if (!config_update_value('autohidden_menu', get_parameter('autohidden_menu'))) { + $error_update[] = __('Autohidden menu'); + } + + if (!config_update_value('visual_animation', get_parameter('visual_animation'))) { + $error_update[] = __('visual_animation'); + } + + if (!config_update_value('disable_help', get_parameter('disable_help'))) { + $error_update[] = __('Disable help'); + } + + if (!config_update_value('fixed_graph', get_parameter('fixed_graph'))) { + $error_update[] = __('Fixed graph'); + } + + if (!config_update_value('fixed_header', get_parameter('fixed_header'))) { + $error_update[] = __('Fixed header'); + } + + if (!config_update_value('fixed_menu', get_parameter('fixed_menu'))) { + $error_update[] = __('Fixed menu'); + } + + if (!config_update_value('paginate_module', get_parameter('paginate_module'))) { + $error_update[] = __('Paginate module'); + } + + if (!config_update_value('graphviz_bin_dir', get_parameter('graphviz_bin_dir'))) { + $error_update[] = __('Custom graphviz directory'); + } + + if (!config_update_value('networkmap_max_width', get_parameter('networkmap_max_width'))) { + $error_update[] = __('Networkmap max width'); + } + + if (!config_update_value('short_module_graph_data', get_parameter('short_module_graph_data'))) { + $error_update[] = __('Shortened module graph data'); + } + + if (!config_update_value('show_group_name', get_parameter('show_group_name'))) { + $error_update[] = __('Show the group name instead the group icon.'); + } + + if (!config_update_value('custom_graph_width', (int) get_parameter('custom_graph_width', 1))) { + $error_update[] = __('Default line thickness for the Custom Graph.'); + } + + if (!config_update_value('type_module_charts', (string) get_parameter('type_module_charts', 'area'))) { + $error_update[] = __('Default type of module charts.'); + } + + if (!config_update_value('type_interface_charts', (string) get_parameter('type_interface_charts', 'line'))) { + $error_update[] = __('Default type of interface charts.'); + } + + if (!config_update_value('render_proc', (bool) get_parameter('render_proc', false))) { + $error_update[] = __('Display data of proc modules in other format'); + } + + if (!config_update_value('render_proc_ok', (string) get_parameter('render_proc_ok', __('Ok')))) { + $error_update[] = __('Display text proc modules have state is ok'); + } + + if (!config_update_value('render_proc_fail', (string) get_parameter('render_proc_fail', __('Fail')))) { + $error_update[] = __('Display text when proc modules have state critical'); + } + + // Daniel maya 02/06/2016 Display menu with click --INI. + if (!config_update_value('click_display', (bool) get_parameter('click_display', false))) { + $error_update[] = __('Display lateral menus with left click'); + } + + // Daniel maya 02/06/2016 Display menu with click --END. + if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { + if (!config_update_value('service_label_font_size', get_parameter('service_label_font_size', false))) { + $error_update[] = __('Service label font size'); + } + + if (!config_update_value('service_item_padding_size', get_parameter('service_item_padding_size', false))) { + $error_update[] = __('Service item padding size'); + } + } + + if (!config_update_value('percentil', (int) get_parameter('percentil', 0))) { + $error_update[] = __('Default percentil'); + } + + if (!config_update_value('full_scale_option', (int) get_parameter('full_scale_option', 0))) { + $error_update[] = __('Default full scale (TIP)'); + } + + if (!config_update_value('type_mode_graph', (int) get_parameter('type_mode_graph', 0))) { + $error_update[] = __('Default soft graphs'); + } + + if (!config_update_value('zoom_graph', (int) get_parameter('zoom_graph', 1))) { + $error_update[] = __('Default zoom graphs'); + } + + if (!config_update_value('graph_image_height', (int) get_parameter('graph_image_height', 280))) { + $error_update[] = __('Default height of the chart image'); + } + + if (!config_update_value('classic_menu', (bool) get_parameter('classic_menu', false))) { + $error_update[] = __('Classic menu mode'); + } + + // -------------------------------------------------- + // CUSTOM VALUES POST PROCESS + // -------------------------------------------------- + $custom_value = get_parameter('custom_value'); + $custom_text = get_parameter('custom_text'); + $custom_value_add = (bool) get_parameter('custom_value_add', 0); + $custom_value_to_delete = get_parameter('custom_value_to_delete', 0); + + $custom_value = str_replace(',', '.', $custom_value); + + if ($custom_value_add) { + include_once 'include/functions_post_process.php'; + + if (!post_process_add_custom_value( + $custom_text, + (string) $custom_value + ) + ) { + $error_update[] = __('Add the custom post process'); + } + } + + if ($custom_value_to_delete > 0) { + include_once 'include/functions_post_process.php'; + + if (!post_process_delete_custom_value($custom_value_to_delete)) { + $error_update[] = __('Delete the custom post process'); + } + } + + // -------------------------------------------------- + // -------------------------------------------------- + // CUSTOM INTERVAL VALUES + // -------------------------------------------------- + $interval_values = get_parameter('interval_values'); + + // Add new interval value if is provided. + $interval_value = (float) get_parameter('interval_value', 0); + + if ($interval_value > 0) { + $interval_unit = (int) get_parameter('interval_unit'); + $new_interval = ($interval_value * $interval_unit); + + if ($interval_values === '') { + $interval_values = $new_interval; + } else { + $interval_values_array = explode(',', $interval_values); + if (!in_array($new_interval, $interval_values_array)) { + $interval_values_array[] = $new_interval; + $interval_values = implode(',', $interval_values_array); + } + } + } + + // Delete interval value if is required. + $interval_to_delete = (float) get_parameter('interval_to_delete'); + if ($interval_to_delete > 0) { + $interval_values_array = explode(',', $interval_values); + foreach ($interval_values_array as $k => $iva) { + if ($interval_to_delete == $iva) { + unset($interval_values_array[$k]); + } + } + + $interval_values = implode(',', $interval_values_array); + } + + if (!config_update_value('interval_values', $interval_values)) { + $error_update[] = __('Delete interval'); + } + + // -------------------------------------------------- + if (!config_update_value('custom_report_info', get_parameter('custom_report_info'))) { + $error_update[] = __('Custom report info'); + } + + // Juanma (06/05/2014) New feature: Custom front page for reports. + if (!config_update_value('custom_report_front', get_parameter('custom_report_front'))) { + $error_update[] = __('Custom report front'); + } + + if (!config_update_value('custom_report_front_font', get_parameter('custom_report_front_font'))) { + $error_update[] = __('Custom report front').' - '.__('Font family'); + } + + if (!config_update_value('custom_report_front_logo', get_parameter('custom_report_front_logo'))) { + $error_update[] = __('Custom report front').' - '.__('Custom logo'); + } + + if (!config_update_value('custom_report_front_header', get_parameter('custom_report_front_header'))) { + $error_update[] = __('Custom report front').' - '.__('Header'); + } + + if (!config_update_value('custom_report_front_firstpage', get_parameter('custom_report_front_firstpage'))) { + $error_update[] = __('Custom report front').' - '.__('First page'); + } + + if (!config_update_value('custom_report_front_footer', get_parameter('custom_report_front_footer'))) { + $error_update[] = __('Custom report front').' - '.__('Footer'); + } + + if (!config_update_value('csv_divider', (string) get_parameter('csv_divider', ';'))) { + $error_update[] = __('CSV divider'); + } + break; + + case 'net': + if (!config_update_value('netflow_path', get_parameter('netflow_path'))) { + $error_update[] = __('Data storage path'); + } + + if (!config_update_value('netflow_interval', (int) get_parameter('netflow_interval'))) { + $error_update[] = __('Daemon interval'); + } + + if (!config_update_value('netflow_daemon', get_parameter('netflow_daemon'))) { + $error_update[] = __('Daemon binary path'); + } + + if (!config_update_value('netflow_nfdump', get_parameter('netflow_nfdump'))) { + $error_update[] = __('Nfdump binary path'); + } + + if (!config_update_value('netflow_nfexpire', get_parameter('netflow_nfexpire'))) { + $error_update[] = __('Nfexpire binary path'); + } + + if (!config_update_value('netflow_max_resolution', (int) get_parameter('netflow_max_resolution'))) { + $error_update[] = __('Maximum chart resolution'); + } + + if (!config_update_value('netflow_disable_custom_lvfilters', get_parameter('netflow_disable_custom_lvfilters'))) { + $error_update[] = __('Disable custom live view filters'); + } + + if (!config_update_value('netflow_max_lifetime', (int) get_parameter('netflow_max_lifetime'))) { + $error_update[] = __('Netflow max lifetime'); + } + + if (!config_update_value('netflow_get_ip_hostname', (int) get_parameter('netflow_get_ip_hostname'))) { + $error_update[] = __('Name resolution for IP address'); + } + break; + + case 'log': + if (!config_update_value('elasticsearch_ip', get_parameter('elasticsearch_ip'))) { + $error_update[] = __('IP ElasticSearch server'); + } + + if (!config_update_value('elasticsearch_port', get_parameter('elasticsearch_port'))) { + $error_update[] = __('Port ElasticSearch server'); + } + + if (!config_update_value('number_logs_viewed', (int) get_parameter('number_logs_viewed'))) { + $error_update[] = __('Number of logs viewed'); + } + + if (!config_update_value('Days_purge_old_information', (int) get_parameter('Days_purge_old_information'))) { + $error_update[] = __('Days to purge old information'); + } + break; + + case 'hist_db': + if (!config_update_value('history_db_enabled', get_parameter('history_db_enabled'))) { + $error_update[] = __('Enable history database'); + } + + if (!config_update_value('history_event_enabled', get_parameter('history_event_enabled'))) { + $error_update[] = __('Enable history event'); + } + + if (!config_update_value('history_db_host', get_parameter('history_db_host'))) { + $error_update[] = __('Host'); + } + + if (!config_update_value('history_db_port', get_parameter('history_db_port'))) { + $error_update[] = __('Port'); + } + + if (!config_update_value('history_db_name', get_parameter('history_db_name'))) { + $error_update[] = __('Database name'); + } + + if (!config_update_value('history_db_user', get_parameter('history_db_user'))) { + $error_update[] = __('Database user'); + } + + if (!config_update_value('history_db_pass', io_input_password(get_parameter('history_db_pass')))) { + $error_update[] = __('Database password'); + } + + if (!config_update_value('history_db_days', get_parameter('history_db_days'))) { + $error_update[] = __('Days'); + } + + if (!config_update_value('history_event_days', get_parameter('history_event_days'))) { + $error_update[] = __('Event Days'); + } + + if (!config_update_value('history_db_step', get_parameter('history_db_step'))) { + $error_update[] = __('Step'); + } + + if (!config_update_value('history_db_delay', get_parameter('history_db_delay'))) { + $error_update[] = __('Delay'); + } + break; + + case 'ehorus': + if (!config_update_value('ehorus_enabled', (int) get_parameter('ehorus_enabled', $config['ehorus_enabled']))) { + $error_update[] = __('Enable eHorus'); + } + + if (!config_update_value('ehorus_user', (string) get_parameter('ehorus_user', $config['ehorus_user']))) { + $error_update[] = __('eHorus user'); + } + + if (!config_update_value('ehorus_pass', io_input_password((string) get_parameter('ehorus_pass', $config['ehorus_pass'])))) { + $error_update[] = __('eHorus password'); + } + + if (!config_update_value('ehorus_hostname', (string) get_parameter('ehorus_hostname', $config['ehorus_hostname']))) { + $error_update[] = __('eHorus API hostname'); + } + + if (!config_update_value('ehorus_port', (int) get_parameter('ehorus_port', $config['ehorus_port']))) { + $error_update[] = __('eHorus API port'); + } + + if (!config_update_value('ehorus_req_timeout', (int) get_parameter('ehorus_req_timeout', $config['ehorus_req_timeout']))) { + $error_update[] = __('eHorus request timeout'); + } + + if (!config_update_value('ehorus_custom_field', (string) get_parameter('ehorus_custom_field', $config['ehorus_custom_field']))) { + $error_update[] = __('eHorus id custom field'); + } + break; + + default: + // Ignore. + break; + } + + default: + // Ignore. + break; + } + + if (count($error_update) > 0) { + $config['error_config_update_config'] = []; + $config['error_config_update_config']['correct'] = false; + $values = implode(', ', $error_update); + $config['error_config_update_config']['message'] = sprintf(__('Failed updated: the next values cannot update: %s'), $values); + } else { + $config['error_config_update_config'] = []; + $config['error_config_update_config']['correct'] = true; + } + + enterprise_include_once('include/functions_policies.php'); + $enterprise = enterprise_include_once('include/functions_skins.php'); + if ($enterprise !== ENTERPRISE_NOT_HOOK) { + $config['relative_path'] = get_parameter('relative_path', $config['relative_path']); + } } + /** - * Process config variables + * Process config variables. + * + * @return void */ -function config_process_config () { - global $config; - - $configs = db_get_all_rows_in_table ('tconfig'); - - if (empty ($configs)) { - include ($config["homedir"]."/general/error_emptyconfig.php"); - exit; - } - - $is_windows = false; - if (substr(strtolower(PHP_OS), 0, 3) === 'win') { - $is_windows = true; - } - - /* Compatibility fix */ - foreach ($configs as $c) { - $config[$c['token']] = $c['value']; - } - - if (!isset ($config['language'])) { - config_update_value ('language', 'en'); - } - - if (isset ($config['homeurl']) && (strlen($config['homeurl']) > 0)) { - if ($config['homeurl'][0] != '/') { - $config['homeurl'] = '/'.$config['homeurl']; - } - } - - if (!isset ($config['remote_config'])) { - if ($is_windows) - $default = 'C:\\PandoraFMS\\Pandora_Server\\data_in'; - else - $default = '/var/spool/pandora/data_in'; - - config_update_value ('remote_config', $default); - } - - if (!isset ($config['phantomjs_bin'])) { - if ($is_windows){ - $default = 'C:\\PandoraFMS\\phantomjs'; - } - else{ - $default = '/usr/bin'; - } - config_update_value ('phantomjs_bin', $default); - } - - if (!isset ($config['date_format'])) { - config_update_value ('date_format', 'F j, Y, g:i a'); - } - - if (!isset ($config['event_view_hr'])) { - config_update_value ('event_view_hr', 8); - } - - if (!isset ($config['report_limit'])) { - config_update_value ('report_limit', 100); - } - - if (!isset ($config['loginhash_pwd'])) { - config_update_value ('loginhash_pwd', io_input_password(rand (0, 1000) * rand (0, 1000)."pandorahash")); - } - - if (!isset ($config["trap2agent"])) { - config_update_value ('trap2agent', 0); - } - - if (!isset ($config["prominent_time"])) { - // Prominent time tells us what to show prominently when a timestamp is - // displayed. The comparation (... days ago) or the timestamp (full date) - config_update_value ('prominent_time', 'comparation'); - } - - if (!isset ($config["timesource"])) { - // Timesource says where time comes from (system or mysql) - config_update_value ('timesource', 'system'); - } - - if (!isset ($config["https"])) { - // Sets whether or not we want to enforce https. We don't want to go to a - // potentially unexisting config by default - config_update_value ('https', false); - } - if (!isset ($config["use_cert"])) { - config_update_value ('use_cert', false); - } - - if (!isset ($config['cert_path'])) { - // Sets name and path of ssl path for use in application - config_update_value ('cert_path', '/etc/ssl/certs/pandorafms.pem'); - } - - if (!isset ($config["num_files_attachment"])) { - config_update_value ('num_files_attachment', 100); - } - - if (!isset ($config['status_images_set'])) { - config_update_value ('status_images_set', 'default'); - } - - // Load user session - if (isset ($_SESSION['id_usuario'])) - $config["id_user"] = $_SESSION["id_usuario"]; - - if (!isset ($config["round_corner"])) { - config_update_value ('round_corner', false); - } - - if (!isset ($config["show_qr_code_header"])) { - config_update_value ('show_qr_code_header', false); - } - - if (!isset ($config["agentaccess"])) { - config_update_value ('agentaccess', true); - } - - if (!isset ($config["timezone"])) { - config_update_value ('timezone', "Europe/Berlin"); - } - - if (!isset ($config["stats_interval"])) { - config_update_value ('stats_interval', SECONDS_5MINUTES); - } - - if (!isset ($config["realtimestats"])) { - config_update_value ('realtimestats', 1); - } - - if (!isset ($config["delete_notinit"])) { - config_update_value ('delete_notinit', 0); - } - - if (!isset ($config["big_operation_step_datos_purge"])) { - config_update_value ('big_operation_step_datos_purge', 100); - } - - if (!isset ($config["small_operation_step_datos_purge"])) { - config_update_value ('small_operation_step_datos_purge', 1000); - } - - if (!isset ($config["num_past_special_days"])) { - config_update_value ('num_past_special_days', 0); - } - - if (isset($config['enterprise_installed'])) { - if (!isset($config['inventory_purge'])) { - config_update_value ('inventory_purge', 21); - } - } - - if (!isset($config['max_graph_container'])) { - config_update_value ('max_graph_container', 10); - } - - if (!isset($config['max_macro_fields'])) { - config_update_value ('max_macro_fields', 10); - } - - if (!isset ($config["event_purge"])) { - config_update_value ('event_purge', 15); - } - - if (!isset ($config["metaconsole_events_history"])) { - config_update_value ('metaconsole_events_history', 0); - } - - if (!isset ($config["trap_purge"])) { - config_update_value ('trap_purge', 7); - } - - if (!isset ($config["string_purge"])) { - config_update_value ('string_purge', 14); - } - - if (!isset ($config["audit_purge"])) { - config_update_value ('audit_purge', 30); - } - - if (!isset ($config["acl_enterprise"])) { - config_update_value ('acl_enterprise', 0); - } - - if (!isset ($config["metaconsole"])) { - config_update_value ('metaconsole', 0); - } - - if (!isset ($config["gis_purge"])) { - config_update_value ('gis_purge', 7); - } - - if (!isset ($config["collection_max_size"])) { - config_update_value ('collection_max_size', 1000000); - } - - if (!isset ($config["event_replication"])) { - config_update_value ('event_replication', 0); - } - - if (!isset ($config["replication_interval"])) { - config_update_value ('replication_interval', 10); - } - - if (!isset ($config["replication_limit"])) { - config_update_value ('replication_limit', 50); - } - - if (!isset ($config["replication_dbengine"])) { - config_update_value ('replication_dbengine', 'mysql'); - } - - if (!isset ($config["replication_dbhost"])) { - config_update_value ('replication_dbhost', ""); - } - - if (!isset ($config["replication_dbname"])) { - config_update_value ('replication_dbname', ""); - } - - if (!isset ($config["replication_dbuser"])) { - config_update_value ('replication_dbuser', ""); - } - - if (!isset ($config["replication_dbpass"])) { - config_update_value ('replication_dbpass', ""); - } - - if (!isset ($config["replication_dbport"])) { - config_update_value ('replication_dbport', ""); - } - - if (!isset ($config["replication_mode"])) { - config_update_value ('replication_mode', "only_validated"); - } - - if (!isset ($config["metaconsole_agent_cache"])) { - config_update_value ('metaconsole_agent_cache', 0); - } - - if (!isset ($config["show_events_in_local"])) { - config_update_value ('show_events_in_local', 0); - } - - if (!isset ($config["log_collector"])) { - config_update_value ('log_collector', 0); - } - - if (!isset ($config["enable_update_manager"])) { - config_update_value ('enable_update_manager', 1); - } - - if (!isset ($config["ipam_ocuppied_critical_treshold"])) { - config_update_value ('ipam_ocuppied_critical_treshold', 90); - } - - if (!isset ($config["ipam_ocuppied_warning_treshold"])) { - config_update_value ('ipam_ocuppied_warning_treshold', 80); - } - - if (!isset ($config["reset_pass_option"])) { - config_update_value ('reset_pass_option', 0); - } - - if (!isset ($config["include_agents"])) { - config_update_value ('include_agents', 0); - } - - if (!isset ($config["alias_as_name"])) { - config_update_value ('alias_as_name', 0); - } - - if (!isset ($config["auditdir"])) { - config_update_value ('auditdir',"/var/www/html/pandora_console"); - } - - if (!isset ($config["elasticsearch_ip"])) { - config_update_value ('elasticsearch_ip', ""); - } - - if (!isset ($config["elasticsearch_port"])) { - config_update_value ('elasticsearch_port', 9200); - } - - if (!isset ($config["number_logs_viewed"])) { - config_update_value ('number_logs_viewed', 50); - } - - if (!isset ($config["Days_purge_old_information"])) { - config_update_value ('Days_purge_old_information', 90); - } - - if (!isset ($config["font_size"])) { - config_update_value ('font_size', 6); - } - - if (!isset ($config["limit_parameters_massive"])) { - config_update_value ('limit_parameters_massive', ini_get("max_input_vars") / 2); - } - - /* - *Parse the ACL IP list for access API - */ - $temp_list_ACL_IPs_for_API = array(); - if (isset($config['list_ACL_IPs_for_API'])) { - if (!empty($config['list_ACL_IPs_for_API'])) { - $temp_list_ACL_IPs_for_API = explode(';', $config['list_ACL_IPs_for_API']); - } - } - $config['list_ACL_IPs_for_API'] = $temp_list_ACL_IPs_for_API; - $keysConfig = array_keys($config); - - - // This is not set here. The first time, when no - // setup is done, update_manager extension manage it - // the first time make a conenction and disable itself - // Not Managed here ! - - // if (!isset ($config["autoupdate"])) { - // config_update_value ('autoupdate', true); - // } - - require_once ($config["homedir"] . "/include/auth/mysql.php"); - require_once ($config["homedir"] . "/include/functions_io.php"); - - - // Next is the directory where "/attachment" directory is placed, - // to upload files stores. This MUST be writtable by http server - // user, and should be in pandora root. By default, Pandora adds - // /attachment to this, so by default is the pandora console home - // dir. - if (!isset ($config['attachment_store'])) { - config_update_value('attachment_store', - io_safe_input($config['homedir']) . '/attachment'); - } - else { - //Fixed when the user moves the pandora console to another dir - //after the first uses. - if (!is_dir($config['attachment_store'])) { - config_update_value('attachment_store', - $config['homedir'] . '/attachment'); - } - } - - - if (!isset ($config['fontpath'])) { - $home = str_replace('\\', '/', $config['homedir'] ); - config_update_value('fontpath', - $home . '/include/fonts/smallfont.ttf'); - } - - if (!isset ($config['style'])) { - config_update_value ( 'style', 'pandora'); - } - - if (!isset ($config["login_background"])) { - config_update_value ('login_background', ''); - } - - if (!isset ($config["login_background_meta"])) { - config_update_value ('login_background_meta', 'background_metaconsole.png'); - } - - if (!isset ($config["paginate_module"])) { - config_update_value ('paginate_module', false); - } - - if (!isset ($config["graphviz_bin_dir"])) { - config_update_value ('graphviz_bin_dir', ""); - } - - if (!isset ($config["disable_help"])) { - config_update_value ('disable_help', false); - } - - if (!isset ($config["fixed_header"])) { - config_update_value ('fixed_header', false); - } - - if (!isset ($config["fixed_graph"])) { - config_update_value ('fixed_graph', false); - } - - if (!isset ($config["fixed_menu"])) { - config_update_value ('fixed_menu', false); - } - - if (!isset ($config["custom_favicon"])) { - config_update_value ('custom_favicon', ''); - } - - if (!isset ($config["custom_logo"])) { - config_update_value ('custom_logo', 'pandora_logo_head_4.png'); - } - - if (!isset ($config["custom_logo_white_bg"])) { - config_update_value ('custom_logo_white_bg', 'pandora_logo_head_white_bg.png'); - } - - if (!isset ($config["custom_logo_login"])) { - config_update_value ('custom_logo_login', 'login_logo_v7.png'); - } - - if (!isset ($config["custom_splash_login"])) { - config_update_value ('custom_splash_login', 'splash_image_default.png'); - } - - if (!isset ($config["custom_docs_logo"])) { - config_update_value ('custom_docs_logo', ''); - } - - if (!isset ($config["custom_support_logo"])) { - config_update_value ('custom_support_logo', ''); - } - - if (!isset ($config["custom_network_center_logo"])) { - config_update_value ('custom_network_center_logo', ''); - } - - if (!isset ($config["custom_mobile_console_logo"])) { - config_update_value ('custom_mobile_console_logo', ''); - } - - if (!isset ($config["custom_title1_login"])) { - config_update_value ('custom_title1_login', __('WELCOME TO PANDORA FMS')); - } - - if (!isset ($config["custom_title2_login"])) { - config_update_value ('custom_title2_login', __('NEXT GENERATION')); - } - - if (!isset ($config["custom_docs_url"])) { - config_update_value ('custom_docs_url', 'http://wiki.pandorafms.com/'); - } - - if (!isset ($config["custom_support_url"])) { - config_update_value ('custom_support_url', 'https://support.artica.es'); - } - - if (!isset ($config['rb_product_name'])) { - config_update_value('rb_product_name', get_product_name()); - } - - if (!isset ($config['rb_copyright_notice'])) { - config_update_value('rb_copyright_notice', get_copyright_notice()); - } - - if (!isset ($config["meta_custom_docs_url"])) { - config_update_value ('meta_custom_docs_url', 'http://wiki.pandorafms.com/index.php?title=Main_Page'); - } - - if (!isset ($config["meta_custom_support_url"])) { - config_update_value ('meta_custom_support_url', 'https://support.artica.es'); - } - - if (!isset ($config["meta_custom_logo"])) { - config_update_value ('meta_custom_logo', 'logo_pandora_metaconsola.png'); - } - - if (!isset ($config["meta_custom_logo_white_bg"])) { - config_update_value ('pandora_logo_head_white_bg', 'pandora_logo_head_white_bg.png'); - } - - if (!isset ($config["meta_custom_logo_login"])) { - config_update_value ('meta_custom_logo_login', 'pandora_logo.png'); - } - - if (!isset ($config["meta_custom_splash_login"])) { - config_update_value ('meta_custom_splash_login', 'splash_image_metaconsola.png'); - } - - if (!isset ($config["meta_custom_title1_login"])) { - config_update_value ('meta_custom_title1_login', __('PANDORA FMS NEXT GENERATION')); - } - - if (!isset ($config["meta_custom_title2_login"])) { - config_update_value ('meta_custom_title2_login', __('METACONSOLE')); - } - - if (!isset($config['vc_favourite_view'])) { - config_update_value('vc_favourite_view', 0); - } - if (!isset($config['vc_menu_items'])) { - config_update_value('vc_menu_items', 10); - } - if (!isset($config['ser_menu_items'])) { - config_update_value('ser_menu_items', 10); - } - - if (!isset ($config['history_db_enabled'])) { - config_update_value ( 'history_db_enabled', false); - } - - if (!isset ($config['history_event_enabled'])) { - config_update_value ( 'history_event_enabled', false); - } - - if (!isset ($config['history_db_host'])) { - config_update_value ( 'history_db_host', ''); - } - - if (!isset ($config['history_db_port'])) { - config_update_value ( 'history_db_port', 3306); - } - - if (!isset ($config['history_db_name'])) { - config_update_value ( 'history_db_name', 'pandora'); - } - - if (!isset ($config['history_db_user'])) { - config_update_value ( 'history_db_user', 'pandora'); - } - - if (!isset ($config['history_db_pass'])) { - config_update_value ( 'history_db_pass', ''); - } - - if (!isset ($config['history_db_days'])) { - config_update_value ( 'history_db_days', 0); - } - - if (!isset ($config['history_event_days'])) { - config_update_value ('history_event_days', 90); - } - - if (!isset ($config['history_db_step'])) { - config_update_value ( 'history_db_step', 0); - } - - if (!isset ($config['history_db_delay'])) { - config_update_value ( 'history_db_delay', 0); - } - - if (!isset ($config['email_from_dir'])) { - config_update_value ( 'email_from_dir', "pandora@pandorafms.org"); - } - - if (!isset ($config['email_from_name'])) { - config_update_value ( 'email_from_name', "Pandora FMS"); - } - - if (!isset ($config['email_smtpServer'])) { - config_update_value ( 'email_smtpServer', "127.0.0.1"); - } - - if (!isset ($config['email_smtpPort'])) { - config_update_value ( 'email_smtpPort', 25); - } - - if (!isset ($config['email_encryption'])) { - config_update_value ( 'email_encryption', 0); - } - - if (!isset ($config['email_username'])) { - config_update_value ( 'email_username', ""); - } - - if (!isset ($config['email_password'])) { - config_update_value ( 'email_password', ""); - } - - if (!isset ($config['activate_gis'])) { - config_update_value ( 'activate_gis', 0); - } - - if (!isset ($config['activate_netflow'])) { - config_update_value ( 'activate_netflow', 0); - } - - if (!isset ($config['netflow_path'])) { - if ($is_windows) - $default = 'C:\\PandoraFMS\\Pandora_Server\\data_in\\netflow'; - else - $default = '/var/spool/pandora/data_in/netflow'; - - config_update_value ( 'netflow_path', $default); - } - - if (!isset ($config['netflow_interval'])) { - config_update_value ( 'netflow_interval', SECONDS_10MINUTES); - } - - if (!isset ($config['netflow_daemon'])) { - config_update_value ( 'netflow_daemon', '/usr/bin/nfcapd'); - } - - if (!isset ($config['netflow_nfdump'])) { - config_update_value ( 'netflow_nfdump', '/usr/bin/nfdump'); - } - - if (!isset ($config['netflow_nfexpire'])) { - config_update_value ( 'netflow_nfexpire', '/usr/bin/nfexpire'); - } - - if (!isset ($config['netflow_max_resolution'])) { - config_update_value ( 'netflow_max_resolution', '50'); - } - - if (!isset ($config['netflow_disable_custom_lvfilters'])) { - config_update_value ( 'netflow_disable_custom_lvfilters', 0); - } - - if (!isset ($config['netflow_max_lifetime'])) { - config_update_value ( 'netflow_max_lifetime', '5'); - } - - if (!isset ($config['auth'])) { - config_update_value ( 'auth', 'mysql'); - } - - if (!isset ($config['autocreate_remote_users'])) { - config_update_value ('autocreate_remote_users', 0); - } - - if (!isset ($config['autocreate_blacklist'])) { - config_update_value ('autocreate_blacklist', ''); - } - - if (!isset ($config['default_remote_profile'])) { - config_update_value ('default_remote_profile', 0); - } - - if (!isset ($config['default_remote_group'])) { - config_update_value ('default_remote_group', 0); - } - - if (!isset ($config['default_assign_tags'])) { - config_update_value ( 'default_assign_tags', ''); - } - if (!isset ($config['default_no_hierarchy'])) { - config_update_value ('default_no_hierarchy', 0); - } - - if (!isset ($config['ldap_server'])) { - config_update_value ( 'ldap_server', 'localhost'); - } - - if (!isset ($config['ldap_port'])) { - config_update_value ( 'ldap_port', 389); - } - - if (!isset ($config['ldap_version'])) { - config_update_value ( 'ldap_version', '3'); - } - - if (!isset ($config['ldap_start_tls'])) { - config_update_value ( 'ldap_start_tls', 0); - } - - if (!isset ($config['ldap_base_dn'])) { - config_update_value('ldap_base_dn', - 'ou=People,dc=edu,dc=example,dc=org'); - } - - if (!isset ($config['ldap_login_attr'])) { - config_update_value ( 'ldap_login_attr', 'uid'); - } - - if (!isset ($config['ldap_admin_login'])) { - config_update_value ( 'ldap_admin_login', ''); - } - - if (!isset ($config['ldap_admin_pass'])) { - config_update_value ( 'ldap_admin_pass', ''); - } - - if (!isset ($config['ldap_function'])) { - config_update_value ( 'ldap_function', 'local'); - } - - if (!isset ($config['fallback_local_auth'])) { - config_update_value ( 'fallback_local_auth', '0'); - } - - if (!isset ($config['ad_server'])) { - config_update_value ( 'ad_server', 'localhost'); - } - - if (!isset ($config['ad_port'])) { - config_update_value ( 'ad_port', 389); - } - - if (!isset ($config['ad_start_tls'])) { - config_update_value ( 'ad_start_tls', 0); - } - - if (!isset ($config['ad_advanced_config'])) { - config_update_value ( 'ad_advanced_config', 0); - } - - if (!isset ($config['ldap_advanced_config'])) { - config_update_value ( 'ldap_advanced_config', 0); - } - - if (!isset ($config['ad_adv_user_node'])) { - config_update_value ( 'ad_adv_user_node', 1); - } - - if (!isset ($config['ldap_adv_user_node'])) { - config_update_value ( 'ldap_adv_user_node', 1); - } - - if (!isset ($config['ad_domain'])) { - config_update_value ( 'ad_domain', ''); - } - - if (!isset ($config['ad_adv_perms'])) { - config_update_value ('ad_adv_perms', ''); - } - else { - if (!json_decode(io_safe_output($config['ad_adv_perms']))) { - $temp_ad_adv_perms = array(); - if (!isset($config['ad_adv_perms']) && $config['ad_adv_perms'] != '') { - $perms = explode(';', io_safe_output($config['ad_adv_perms'])); - foreach ($perms as $ad_adv_perm) { - if (preg_match('/[\[\]]/',$ad_adv_perm)) { - $all_data = explode (",", io_safe_output($ad_adv_perm)); - $profile = $all_data[0]; - $group_pnd = $all_data[1]; - $groups_ad = str_replace(array("[","]"), "", $all_data[2]); - $tags = str_replace(array("[","]"), "", $all_data[3]); - $groups_ad = explode('|', $groups_ad); - $tags_name = explode('|', $tags); - $tags_ids = array(); - foreach ($tags_name as $tag) { - $tags_ids[] = tags_get_id($tag); - } - $profile = profile_get_profiles( - array( - "name" => io_safe_input($profile))); - if (!$profile) - continue; - $profile_id = array_keys($profile); - $id_grupo = groups_get_id (io_safe_input($group_pnd), false); - $new_ad_adv_perms[] = - array('profile' => $profile_id[0], - 'group' => array($id_grupo), - 'tags' => $tags_ids, - 'groups_ad' => $groups_ad); - } - else { - $all_data = explode (",", io_safe_output($ad_adv_perm)); - $profile = $all_data[0]; - $group_pnd = $all_data[1]; - $groups_ad = $all_data[2]; - $tags = $all_data[3]; - $profile = profile_get_profiles( - array( - "name" => io_safe_input($profile))); - if (!$profile) - continue; - $profile_id = array_keys($profile); - $id_grupo = groups_get_id (io_safe_input($group_pnd), false); - - $new_ad_adv_perms[] = - array('profile' => $profile_id[0], - 'group' => array($id_grupo), - 'tags' => array($tags), - 'groups_ad' => array($groups_ad)); - } - } - - if (!empty($new_ad_adv_perms)) { - $temp_ad_adv_perms = json_encode($new_ad_adv_perms); - } - } - config_update_value ('ad_adv_perms', $temp_ad_adv_perms); - } - } - - if (!isset ($config['ldap_adv_perms'])) { - config_update_value ('ldap_adv_perms', ''); - } - else { - if (!json_decode(io_safe_output($config['ldap_adv_perms']))) { - $temp_ldap_adv_perms = array(); - if (!isset($config['ad_adv_perms']) && $config['ldap_adv_perms'] != '') { - $perms = explode(';', io_safe_output($config['ldap_adv_perms'])); - foreach ($perms as $ad_adv_perm) { - if (preg_match('/[\[\]]/',$ad_adv_perm)) { - $all_data = explode (",", io_safe_output($ad_adv_perm)); - $profile = $all_data[0]; - $group_pnd = $all_data[1]; - $groups_ad = str_replace(array("[","]"), "", $all_data[2]); - $tags = str_replace(array("[","]"), "", $all_data[3]); - $groups_ad = explode('|', $groups_ad); - $tags_name = explode('|', $tags); - $tags_ids = array(); - foreach ($tags_name as $tag) { - $tags_ids[] = tags_get_id($tag); - } - $profile = profile_get_profiles( - array( - "name" => io_safe_input($profile))); - if (!$profile) - continue; - $profile_id = array_keys($profile); - $id_grupo = groups_get_id (io_safe_input($group_pnd), false); - $new_ldap_adv_perms[] = - array('profile' => $profile_id[0], - 'group' => array($id_grupo), - 'tags' => $tags_ids, - 'groups_ldap' => $groups_ldap); - } - else { - $all_data = explode (",", io_safe_output($ad_adv_perm)); - $profile = $all_data[0]; - $group_pnd = $all_data[1]; - $groups_ad = $all_data[2]; - $tags = $all_data[3]; - $profile = profile_get_profiles( - array( - "name" => io_safe_input($profile))); - if (!$profile) - continue; - $profile_id = array_keys($profile); - $id_grupo = groups_get_id (io_safe_input($group_pnd), false); - - $new_ldap_adv_perms[] = - array('profile' => $profile_id[0], - 'group' => array($id_grupo), - 'tags' => array($tags), - 'groups_ldap' => array($groups_ldap)); - } - } - - if (!empty($new_ldap_adv_perms)) { - $temp_ldap_adv_perms = json_encode($new_ldap_adv_perms); - } - } - config_update_value ('ldap_adv_perms', $temp_ldap_adv_perms); - } - } - - if (!isset ($config['rpandora_server'])) { - config_update_value ( 'rpandora_server', 'localhost'); - } - - if (!isset ($config['rpandora_port'])) { - config_update_value ( 'rpandora_port', 3306); - } - - if (!isset ($config['rpandora_dbname'])) { - config_update_value ( 'rpandora_dbname', 'pandora'); - } - - if (!isset ($config['rpandora_user'])) { - config_update_value ( 'rpandora_user', 'pandora'); - } - - if (!isset ($config['rpandora_pass'])) { - config_update_value ( 'rpandora_pass', ''); - } - - if (!isset ($config['rintegria_server'])) { - config_update_value ( 'rintegria_server', 'localhost'); - } - - if (!isset ($config['rintegria_port'])) { - config_update_value ( 'rintegria_port', 3306); - } - - if (!isset ($config['rintegria_dbname'])) { - config_update_value ( 'rintegria_dbname', 'integria'); - } - - if (!isset ($config['rintegria_user'])) { - config_update_value ( 'rintegria_user', 'integria'); - } - - if (!isset ($config['rintegria_pass'])) { - config_update_value ( 'rintegria_pass', ''); - } - - if (!isset ($config['saml_path'])) { - config_update_value ('saml_path', '/opt/'); - } - - if (!isset ($config['autoupdate'])) { - config_update_value ( 'autoupdate', 1); - } - - if (!isset ($config['api_password'])) { - config_update_value( 'api_password', ''); - } - - if (defined('METACONSOLE')) { - // Customizable sections (Metaconsole) - enterprise_include_once ('include/functions_enterprise.php'); - $customizable_sections = enterprise_hook('enterprise_get_customizable_sections'); - - if($customizable_sections != ENTERPRISE_NOT_HOOK) { - foreach($customizable_sections as $k => $v) { - if (!isset ($config[$k])) { - config_update_value($k, $v['default']); - } - } - } - - if (!isset ($config['meta_num_elements'])) { - config_update_value('meta_num_elements', 100); - } - } - - if (!isset ($config['relative_path']) && (isset ($_POST['nick']) - || isset ($config['id_user'])) && isset($config['enterprise_installed'])) { - - $isFunctionSkins = enterprise_include_once ('include/functions_skins.php'); - if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK) { - - // Try to update user table in order to refresh skin inmediatly - $is_user_updating = get_parameter("sec2", ""); - - if ($is_user_updating == 'operation/users/user_edit') { - $id = get_parameter_get ("id", $config["id_user"]); // ID given as parameter - $user_info = get_user_info ($id); - - //If current user is editing himself or if the user has UM (User Management) rights on any groups the user is part of AND the authorization scheme allows for users/admins to update info - if (($config["id_user"] == $id || check_acl ($config["id_user"], users_get_groups ($id), "UM")) && $config["user_can_update_info"]) { - $view_mode = false; - } - else { - $view_mode = true; - } - - if (isset ($_GET["modified"]) && !$view_mode) { - $upd_info["id_skin"] = get_parameter ("skin", $user_info["id_skin"]); - $return_update_skin = update_user ($id, $upd_info); - } - } - - if(!is_metaconsole()) { - // Skins are available only in console mode - - if (isset($config['id_user'])){ - $relative_path = enterprise_hook('skins_set_image_skin_path',array($config['id_user'])); - } - else{ - $relative_path = enterprise_hook('skins_set_image_skin_path',array(get_parameter('nick'))); - } - } - else { - $relative_path = ''; - } - $config['relative_path'] = $relative_path; - } - } - - if (!isset ($config['dbtype'])) { - config_update_value ('dbtype', 'mysql'); - } - - if (!isset ($config['vc_refr'])) { - config_update_value ('vc_refr', 300); - } - - if (!isset($config['agent_size_text_small'])) { - config_update_value ('agent_size_text_small', 18); - } - - if (!isset($config['agent_size_text_medium'])) { - config_update_value ('agent_size_text_medium', 50); - } - - if (!isset($config['module_size_text_small'])) { - config_update_value ('module_size_text_small', 25); - } - - if (!isset($config['module_size_text_medium'])) { - config_update_value ('module_size_text_medium', 50); - } - - if (!isset($config['description_size_text'])) { - config_update_value ('description_size_text', 60); - } - - if (!isset($config['item_title_size_text'])) { - config_update_value ('item_title_size_text', 45); - } - - if (!isset($config['simple_module_value'])) { - config_update_value ('simple_module_value', 1); - } - - if (!isset($config['gis_label'])) { - config_update_value ('gis_label', 0); - } - - if (!isset($config['interface_unit'])) { - config_update_value ('interface_unit', __('Bytes')); - } - - if (!isset($config['graph_precision'])) { - config_update_value ('graph_precision', 1); - } - else { - if (!isset($config['enterprise_installed'])) { - config_update_value ('graph_precision', 1); - } - } - - if (!isset($config['gis_default_icon'])) { - config_update_value ('gis_default_icon', "marker"); - } - - if (!isset($config['interval_values'])) { - config_update_value ('interval_values', ""); - } - - if (!isset($config['public_url'])) { - config_update_value ('public_url', ""); - } - - if (!isset($config['referer_security'])) { - config_update_value ('referer_security', 0); - } - - if (!isset($config['event_storm_protection'])) { - config_update_value ('event_storm_protection', 0); - } - - if (!isset($config['server_log_dir'])) { - config_update_value ('server_log_dir', ""); - } - - if (!isset($config['max_log_size'])) { - config_update_value ('max_log_size', 512); - } - - if (!isset($config['show_group_name'])) { - config_update_value ('show_group_name', 0); - } - - if (!isset($config['custom_graph_width'])) { - config_update_value ('custom_graph_width', 1); - } - - if (!isset($config['type_module_charts'])) { - config_update_value ('type_module_charts', 'area'); - } - - if (!isset($config['type_interface_charts'])) { - config_update_value ('type_interface_charts', 'line'); - } - - if (!isset($config['render_proc'])) { - config_update_value ('render_proc', 0); - } - - if (!isset($config['graph_image_height'])) { - config_update_value ('graph_image_height', 280); - } - - if (!isset($config['zoom_graph'])) { - config_update_value ('zoom_graph', 1); - } - - if (!isset($config["render_proc_ok"])) { - config_update_value ('render_proc_ok', __('Ok') ); - } - if (!isset($config["render_proc_fail"])) { - config_update_value ('render_proc_fail', __('Fail') ); - } - //Daniel maya 02/06/2016 Display menu with click --INI - if (!isset($config["click_display"])) { - config_update_value ('click_display', 1); - } - //Daniel maya 02/06/2016 Display menu with click --END - if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { - if (!isset($config["service_label_font_size"])) { - config_update_value ('service_label_font_size', 20); - } - - if (!isset($config["service_item_padding_size"])) { - config_update_value ('service_item_padding_size', 80); - } - } - if (!isset($config["classic_menu"])) { - config_update_value ('classic_menu', 0); - } - - if (!isset($config["csv_divider"])) { - config_update_value ('csv_divider', ";"); - } - - if (!isset($config['command_snapshot'])) { - config_update_value ('command_snapshot', 1); - } - - if (!isset($config['custom_report_info'])) { - config_update_value ('custom_report_info', 1); - } - - // Juanma (06/05/2014) New feature: Custom front page for reports - if (!isset($config['custom_report_front'])) { - config_update_value ('custom_report_front', 0); - } - - if (!isset($config['custom_report_front_font'])) { - config_update_value ('custom_report_front_font', 'FreeSans.ttf'); - } - - if (!isset($config['custom_report_front_logo'])) { - config_update_value ('custom_report_front_logo', - 'images/pandora_logo_white.jpg'); - } - - if (!isset($config['custom_report_front_header'])) { - config_update_value ('custom_report_front_header', ''); - } - - if (!isset($config['custom_report_front_firstpage'])) { - config_update_value ('custom_report_front_firstpage', - "<p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><img src="(_URLIMAGE_)/images/pandora_report_logo.png" alt="" width="800" /></p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><span style="font-size: xx-large;">(_REPORT_NAME_)</span></p> <p style="text-align: center;"><span style="font-size: large;">(_DATETIME_)</span></p>"); - } - - if (!isset($config['custom_report_front_footer'])) { - config_update_value ('custom_report_front_footer', ''); - } - - if (!isset($config['autohidden_menu'])) { - config_update_value ('autohidden_menu', 0); - } - - if (!isset($config['visual_animation'])) { - config_update_value ('visual_animation', 1); - } - - if (!isset($config['networkmap_max_width'])) { - config_update_value ('networkmap_max_width', 900); - } - - if (!isset($config['short_module_graph_data'])) { - config_update_value ('short_module_graph_data', ''); - } - - if (!isset($config['tutorial_mode'])) { - config_update_value ('tutorial_mode', 'full'); - } - - if (!isset($config['post_process_custom_values'])) { - config_update_value ('post_process_custom_values', - json_encode(array())); - } - - if (!isset($config['update_manager_proxy_server'])) { - config_update_value ('update_manager_proxy_server', - ""); - } - if (!isset($config['update_manager_proxy_port'])) { - config_update_value ('update_manager_proxy_port', - ""); - } - if (!isset($config['update_manager_proxy_user'])) { - config_update_value ('update_manager_proxy_user', - ""); - } - if (!isset($config['update_manager_proxy_password'])) { - config_update_value ('update_manager_proxy_password', - ""); - } - - if (!isset ($config["session_timeout"])) { - config_update_value ('session_timeout', 90); - } - - if (!isset ($config["max_file_size"])) { - config_update_value ('max_file_size', "2M"); - } - - if (!isset ($config["initial_wizard"])) { - config_update_value ('initial_wizard', 0); - } - - if (!isset ($config["identification_reminder"])) { - config_update_value ('identification_reminder', 1); - } - - if (!isset ($config["identification_reminder_timestamp"])) { - config_update_value ('identification_reminder_timestamp', 0); - } - - if (!isset ($config["instance_registered"])) { - config_update_value ('instance_registered', 0); - } - - // eHorus - if (!isset($config['ehorus_enabled'])) { - config_update_value('ehorus_enabled', 0); - } - if (!isset($config['ehorus_custom_field'])) { - config_update_value('ehorus_custom_field', 'eHorusID'); - } - if (!isset($config['ehorus_hostname'])) { - config_update_value('ehorus_hostname', 'portal.ehorus.com'); - } - if (!isset($config['ehorus_port'])) { - config_update_value('ehorus_port', 18080); - } - if (!isset($config['ehorus_req_timeout'])) { - config_update_value('ehorus_req_timeout', 5); - } - - if (is_metaconsole()) { - if (!isset($config["metaconsole_deploy_collection"])) { - config_update_value('metaconsole_deploy_collection', 0); - } - - if (!isset($config["metaconsole_deploy_inventory_plugin"])) { - config_update_value('metaconsole_deploy_inventory_plugin', 0); - } - - if (!isset($config["metaconsole_deploy_plugin_server"])) { - config_update_value('metaconsole_deploy_plugin_server', 0); - } - } - - /* Finally, check if any value was overwritten in a form */ - config_update_config(); +function config_process_config() +{ + global $config; + + $configs = db_get_all_rows_in_table('tconfig'); + + if (empty($configs)) { + include $config['homedir'].'/general/error_emptyconfig.php'; + exit; + } + + $is_windows = false; + if (substr(strtolower(PHP_OS), 0, 3) === 'win') { + $is_windows = true; + } + + // Compatibility fix. + foreach ($configs as $c) { + $config[$c['token']] = $c['value']; + } + + if (!isset($config['language'])) { + config_update_value('language', 'en'); + } + + if (isset($config['homeurl']) && (strlen($config['homeurl']) > 0)) { + if ($config['homeurl'][0] != '/') { + $config['homeurl'] = '/'.$config['homeurl']; + } + } + + if (!isset($config['remote_config'])) { + if ($is_windows) { + $default = 'C:\\PandoraFMS\\Pandora_Server\\data_in'; + } else { + $default = '/var/spool/pandora/data_in'; + } + + config_update_value('remote_config', $default); + } + + if (!isset($config['phantomjs_bin'])) { + if ($is_windows) { + $default = 'C:\\PandoraFMS\\phantomjs'; + } else { + $default = '/usr/bin'; + } + + config_update_value('phantomjs_bin', $default); + } + + if (!isset($config['date_format'])) { + config_update_value('date_format', 'F j, Y, g:i a'); + } + + if (!isset($config['event_view_hr'])) { + config_update_value('event_view_hr', 8); + } + + if (!isset($config['report_limit'])) { + config_update_value('report_limit', 100); + } + + if (!isset($config['loginhash_pwd'])) { + config_update_value('loginhash_pwd', io_input_password((rand(0, 1000) * rand(0, 1000)).'pandorahash')); + } + + if (!isset($config['trap2agent'])) { + config_update_value('trap2agent', 0); + } + + if (!isset($config['prominent_time'])) { + // Prominent time tells us what to show prominently when a timestamp is + // displayed. The comparation (... days ago) or the timestamp (full date). + config_update_value('prominent_time', 'comparation'); + } + + if (!isset($config['timesource'])) { + // Timesource says where time comes from (system or mysql). + config_update_value('timesource', 'system'); + } + + if (!isset($config['https'])) { + // Sets whether or not we want to enforce https. We don't want to go to a + // potentially unexisting config by default. + config_update_value('https', false); + } + + if (!isset($config['use_cert'])) { + config_update_value('use_cert', false); + } + + if (!isset($config['cert_path'])) { + // Sets name and path of ssl path for use in application. + config_update_value('cert_path', '/etc/ssl/certs/pandorafms.pem'); + } + + if (!isset($config['num_files_attachment'])) { + config_update_value('num_files_attachment', 100); + } + + if (!isset($config['status_images_set'])) { + config_update_value('status_images_set', 'default'); + } + + // Load user session. + if (isset($_SESSION['id_usuario'])) { + $config['id_user'] = $_SESSION['id_usuario']; + } + + if (!isset($config['round_corner'])) { + config_update_value('round_corner', false); + } + + if (!isset($config['show_qr_code_header'])) { + config_update_value('show_qr_code_header', false); + } + + if (!isset($config['agentaccess'])) { + config_update_value('agentaccess', true); + } + + if (!isset($config['timezone'])) { + config_update_value('timezone', 'Europe/Berlin'); + } + + if (!isset($config['stats_interval'])) { + config_update_value('stats_interval', SECONDS_5MINUTES); + } + + if (!isset($config['realtimestats'])) { + config_update_value('realtimestats', 1); + } + + if (!isset($config['delete_notinit'])) { + config_update_value('delete_notinit', 0); + } + + if (!isset($config['big_operation_step_datos_purge'])) { + config_update_value('big_operation_step_datos_purge', 100); + } + + if (!isset($config['small_operation_step_datos_purge'])) { + config_update_value('small_operation_step_datos_purge', 1000); + } + + if (!isset($config['num_past_special_days'])) { + config_update_value('num_past_special_days', 0); + } + + if (isset($config['enterprise_installed'])) { + if (!isset($config['inventory_purge'])) { + config_update_value('inventory_purge', 21); + } + } + + if (!isset($config['max_graph_container'])) { + config_update_value('max_graph_container', 10); + } + + if (!isset($config['max_macro_fields'])) { + config_update_value('max_macro_fields', 10); + } + + if (!isset($config['event_purge'])) { + config_update_value('event_purge', 15); + } + + if (!isset($config['metaconsole_events_history'])) { + config_update_value('metaconsole_events_history', 0); + } + + if (!isset($config['trap_purge'])) { + config_update_value('trap_purge', 7); + } + + if (!isset($config['string_purge'])) { + config_update_value('string_purge', 14); + } + + if (!isset($config['audit_purge'])) { + config_update_value('audit_purge', 30); + } + + if (!isset($config['acl_enterprise'])) { + config_update_value('acl_enterprise', 0); + } + + if (!isset($config['metaconsole'])) { + config_update_value('metaconsole', 0); + } + + if (!isset($config['gis_purge'])) { + config_update_value('gis_purge', 7); + } + + if (!isset($config['collection_max_size'])) { + config_update_value('collection_max_size', 1000000); + } + + if (!isset($config['event_replication'])) { + config_update_value('event_replication', 0); + } + + if (!isset($config['replication_interval'])) { + config_update_value('replication_interval', 10); + } + + if (!isset($config['replication_limit'])) { + config_update_value('replication_limit', 50); + } + + if (!isset($config['replication_dbengine'])) { + config_update_value('replication_dbengine', 'mysql'); + } + + if (!isset($config['replication_dbhost'])) { + config_update_value('replication_dbhost', ''); + } + + if (!isset($config['replication_dbname'])) { + config_update_value('replication_dbname', ''); + } + + if (!isset($config['replication_dbuser'])) { + config_update_value('replication_dbuser', ''); + } + + if (!isset($config['replication_dbpass'])) { + config_update_value('replication_dbpass', ''); + } + + if (!isset($config['replication_dbport'])) { + config_update_value('replication_dbport', ''); + } + + if (!isset($config['replication_mode'])) { + config_update_value('replication_mode', 'only_validated'); + } + + if (!isset($config['metaconsole_agent_cache'])) { + config_update_value('metaconsole_agent_cache', 0); + } + + if (!isset($config['show_events_in_local'])) { + config_update_value('show_events_in_local', 0); + } + + if (!isset($config['log_collector'])) { + config_update_value('log_collector', 0); + } + + if (!isset($config['enable_update_manager'])) { + config_update_value('enable_update_manager', 1); + } + + if (!isset($config['ipam_ocuppied_critical_treshold'])) { + config_update_value('ipam_ocuppied_critical_treshold', 90); + } + + if (!isset($config['ipam_ocuppied_warning_treshold'])) { + config_update_value('ipam_ocuppied_warning_treshold', 80); + } + + if (!isset($config['reset_pass_option'])) { + config_update_value('reset_pass_option', 0); + } + + if (!isset($config['include_agents'])) { + config_update_value('include_agents', 0); + } + + if (!isset($config['alias_as_name'])) { + config_update_value('alias_as_name', 0); + } + + if (!isset($config['auditdir'])) { + config_update_value('auditdir', '/var/www/html/pandora_console'); + } + + if (!isset($config['elasticsearch_ip'])) { + config_update_value('elasticsearch_ip', ''); + } + + if (!isset($config['elasticsearch_port'])) { + config_update_value('elasticsearch_port', 9200); + } + + if (!isset($config['number_logs_viewed'])) { + config_update_value('number_logs_viewed', 50); + } + + if (!isset($config['Days_purge_old_information'])) { + config_update_value('Days_purge_old_information', 90); + } + + if (!isset($config['font_size'])) { + config_update_value('font_size', 6); + } + + if (!isset($config['limit_parameters_massive'])) { + config_update_value('limit_parameters_massive', (ini_get('max_input_vars') / 2)); + } + + /* + * Parse the ACL IP list for access API + */ + + $temp_list_ACL_IPs_for_API = []; + if (isset($config['list_ACL_IPs_for_API'])) { + if (!empty($config['list_ACL_IPs_for_API'])) { + $temp_list_ACL_IPs_for_API = explode(';', $config['list_ACL_IPs_for_API']); + } + } + + $config['list_ACL_IPs_for_API'] = $temp_list_ACL_IPs_for_API; + $keysConfig = array_keys($config); + + // This is not set here. The first time, when no + // setup is done, update_manager extension manage it + // the first time make a conenction and disable itself + // Not Managed here ! + // if (!isset ($config["autoupdate"])) { + // config_update_value ('autoupdate', true);. + include_once $config['homedir'].'/include/auth/mysql.php'; + include_once $config['homedir'].'/include/functions_io.php'; + + // Next is the directory where "/attachment" directory is placed, + // to upload files stores. This MUST be writtable by http server + // user, and should be in pandora root. By default, Pandora adds + // /attachment to this, so by default is the pandora console home + // dir. + if (!isset($config['attachment_store'])) { + config_update_value( + 'attachment_store', + io_safe_input($config['homedir']).'/attachment' + ); + } else { + // Fixed when the user moves the pandora console to another dir + // after the first uses. + if (!is_dir($config['attachment_store'])) { + config_update_value( + 'attachment_store', + $config['homedir'].'/attachment' + ); + } + } + + if (!isset($config['fontpath'])) { + $home = str_replace('\\', '/', $config['homedir']); + config_update_value( + 'fontpath', + $home.'/include/fonts/smallfont.ttf' + ); + } + + if (!isset($config['style'])) { + config_update_value('style', 'pandora'); + } + + if (!isset($config['login_background'])) { + config_update_value('login_background', ''); + } + + if (!isset($config['login_background_meta'])) { + config_update_value('login_background_meta', 'background_metaconsole.png'); + } + + if (!isset($config['paginate_module'])) { + config_update_value('paginate_module', false); + } + + if (!isset($config['graphviz_bin_dir'])) { + config_update_value('graphviz_bin_dir', ''); + } + + if (!isset($config['disable_help'])) { + config_update_value('disable_help', false); + } + + if (!isset($config['fixed_header'])) { + config_update_value('fixed_header', false); + } + + if (!isset($config['fixed_graph'])) { + config_update_value('fixed_graph', false); + } + + if (!isset($config['fixed_menu'])) { + config_update_value('fixed_menu', false); + } + + if (!isset($config['custom_favicon'])) { + config_update_value('custom_favicon', ''); + } + + if (!isset($config['custom_logo'])) { + config_update_value('custom_logo', 'pandora_logo_head_4.png'); + } + + if (!isset($config['custom_logo_white_bg'])) { + config_update_value('custom_logo_white_bg', 'pandora_logo_head_white_bg.png'); + } + + if (!isset($config['custom_logo_login'])) { + config_update_value('custom_logo_login', 'login_logo_v7.png'); + } + + if (!isset($config['custom_splash_login'])) { + config_update_value('custom_splash_login', 'splash_image_default.png'); + } + + if (!isset($config['custom_docs_logo'])) { + config_update_value('custom_docs_logo', ''); + } + + if (!isset($config['custom_support_logo'])) { + config_update_value('custom_support_logo', ''); + } + + if (!isset($config['custom_network_center_logo'])) { + config_update_value('custom_network_center_logo', ''); + } + + if (!isset($config['custom_mobile_console_logo'])) { + config_update_value('custom_mobile_console_logo', ''); + } + + if (!isset($config['custom_title1_login'])) { + config_update_value('custom_title1_login', __('WELCOME TO PANDORA FMS')); + } + + if (!isset($config['custom_title2_login'])) { + config_update_value('custom_title2_login', __('NEXT GENERATION')); + } + + if (!isset($config['custom_docs_url'])) { + config_update_value('custom_docs_url', 'http://wiki.pandorafms.com/'); + } + + if (!isset($config['custom_support_url'])) { + config_update_value('custom_support_url', 'https://support.artica.es'); + } + + if (!isset($config['rb_product_name'])) { + config_update_value('rb_product_name', get_product_name()); + } + + if (!isset($config['rb_copyright_notice'])) { + config_update_value('rb_copyright_notice', get_copyright_notice()); + } + + if (!isset($config['meta_custom_docs_url'])) { + config_update_value('meta_custom_docs_url', 'http://wiki.pandorafms.com/index.php?title=Main_Page'); + } + + if (!isset($config['meta_custom_support_url'])) { + config_update_value('meta_custom_support_url', 'https://support.artica.es'); + } + + if (!isset($config['meta_custom_logo'])) { + config_update_value('meta_custom_logo', 'logo_pandora_metaconsola.png'); + } + + if (!isset($config['meta_custom_logo_white_bg'])) { + config_update_value('pandora_logo_head_white_bg', 'pandora_logo_head_white_bg.png'); + } + + if (!isset($config['meta_custom_logo_login'])) { + config_update_value('meta_custom_logo_login', 'pandora_logo.png'); + } + + if (!isset($config['meta_custom_splash_login'])) { + config_update_value('meta_custom_splash_login', 'splash_image_metaconsola.png'); + } + + if (!isset($config['meta_custom_title1_login'])) { + config_update_value('meta_custom_title1_login', __('PANDORA FMS NEXT GENERATION')); + } + + if (!isset($config['meta_custom_title2_login'])) { + config_update_value('meta_custom_title2_login', __('METACONSOLE')); + } + + if (!isset($config['vc_favourite_view'])) { + config_update_value('vc_favourite_view', 0); + } + + if (!isset($config['vc_menu_items'])) { + config_update_value('vc_menu_items', 10); + } + + if (!isset($config['ser_menu_items'])) { + config_update_value('ser_menu_items', 10); + } + + if (!isset($config['history_db_enabled'])) { + config_update_value('history_db_enabled', false); + } + + if (!isset($config['history_event_enabled'])) { + config_update_value('history_event_enabled', false); + } + + if (!isset($config['history_db_host'])) { + config_update_value('history_db_host', ''); + } + + if (!isset($config['history_db_port'])) { + config_update_value('history_db_port', 3306); + } + + if (!isset($config['history_db_name'])) { + config_update_value('history_db_name', 'pandora'); + } + + if (!isset($config['history_db_user'])) { + config_update_value('history_db_user', 'pandora'); + } + + if (!isset($config['history_db_pass'])) { + config_update_value('history_db_pass', ''); + } + + if (!isset($config['history_db_days'])) { + config_update_value('history_db_days', 0); + } + + if (!isset($config['history_event_days'])) { + config_update_value('history_event_days', 90); + } + + if (!isset($config['history_db_step'])) { + config_update_value('history_db_step', 0); + } + + if (!isset($config['history_db_delay'])) { + config_update_value('history_db_delay', 0); + } + + if (!isset($config['email_from_dir'])) { + config_update_value('email_from_dir', 'pandora@pandorafms.org'); + } + + if (!isset($config['email_from_name'])) { + config_update_value('email_from_name', 'Pandora FMS'); + } + + if (!isset($config['email_smtpServer'])) { + config_update_value('email_smtpServer', '127.0.0.1'); + } + + if (!isset($config['email_smtpPort'])) { + config_update_value('email_smtpPort', 25); + } + + if (!isset($config['email_encryption'])) { + config_update_value('email_encryption', 0); + } + + if (!isset($config['email_username'])) { + config_update_value('email_username', ''); + } + + if (!isset($config['email_password'])) { + config_update_value('email_password', ''); + } + + if (!isset($config['activate_gis'])) { + config_update_value('activate_gis', 0); + } + + if (!isset($config['activate_netflow'])) { + config_update_value('activate_netflow', 0); + } + + if (!isset($config['netflow_path'])) { + if ($is_windows) { + $default = 'C:\\PandoraFMS\\Pandora_Server\\data_in\\netflow'; + } else { + $default = '/var/spool/pandora/data_in/netflow'; + } + + config_update_value('netflow_path', $default); + } + + if (!isset($config['netflow_interval'])) { + config_update_value('netflow_interval', SECONDS_10MINUTES); + } + + if (!isset($config['netflow_daemon'])) { + config_update_value('netflow_daemon', '/usr/bin/nfcapd'); + } + + if (!isset($config['netflow_nfdump'])) { + config_update_value('netflow_nfdump', '/usr/bin/nfdump'); + } + + if (!isset($config['netflow_nfexpire'])) { + config_update_value('netflow_nfexpire', '/usr/bin/nfexpire'); + } + + if (!isset($config['netflow_max_resolution'])) { + config_update_value('netflow_max_resolution', '50'); + } + + if (!isset($config['netflow_disable_custom_lvfilters'])) { + config_update_value('netflow_disable_custom_lvfilters', 0); + } + + if (!isset($config['netflow_max_lifetime'])) { + config_update_value('netflow_max_lifetime', '5'); + } + + if (!isset($config['auth'])) { + config_update_value('auth', 'mysql'); + } + + if (!isset($config['autocreate_remote_users'])) { + config_update_value('autocreate_remote_users', 0); + } + + if (!isset($config['autocreate_blacklist'])) { + config_update_value('autocreate_blacklist', ''); + } + + if (!isset($config['default_remote_profile'])) { + config_update_value('default_remote_profile', 0); + } + + if (!isset($config['default_remote_group'])) { + config_update_value('default_remote_group', 0); + } + + if (!isset($config['default_assign_tags'])) { + config_update_value('default_assign_tags', ''); + } + + if (!isset($config['default_no_hierarchy'])) { + config_update_value('default_no_hierarchy', 0); + } + + if (!isset($config['ldap_server'])) { + config_update_value('ldap_server', 'localhost'); + } + + if (!isset($config['ldap_port'])) { + config_update_value('ldap_port', 389); + } + + if (!isset($config['ldap_version'])) { + config_update_value('ldap_version', '3'); + } + + if (!isset($config['ldap_start_tls'])) { + config_update_value('ldap_start_tls', 0); + } + + if (!isset($config['ldap_base_dn'])) { + config_update_value( + 'ldap_base_dn', + 'ou=People,dc=edu,dc=example,dc=org' + ); + } + + if (!isset($config['ldap_login_attr'])) { + config_update_value('ldap_login_attr', 'uid'); + } + + if (!isset($config['ldap_admin_login'])) { + config_update_value('ldap_admin_login', ''); + } + + if (!isset($config['ldap_admin_pass'])) { + config_update_value('ldap_admin_pass', ''); + } + + if (!isset($config['ldap_function'])) { + config_update_value('ldap_function', 'local'); + } + + if (!isset($config['fallback_local_auth'])) { + config_update_value('fallback_local_auth', '0'); + } + + if (!isset($config['ad_server'])) { + config_update_value('ad_server', 'localhost'); + } + + if (!isset($config['ad_port'])) { + config_update_value('ad_port', 389); + } + + if (!isset($config['ad_start_tls'])) { + config_update_value('ad_start_tls', 0); + } + + if (!isset($config['ad_advanced_config'])) { + config_update_value('ad_advanced_config', 0); + } + + if (!isset($config['ldap_advanced_config'])) { + config_update_value('ldap_advanced_config', 0); + } + + if (!isset($config['ad_adv_user_node'])) { + config_update_value('ad_adv_user_node', 1); + } + + if (!isset($config['ldap_adv_user_node'])) { + config_update_value('ldap_adv_user_node', 1); + } + + if (!isset($config['ad_domain'])) { + config_update_value('ad_domain', ''); + } + + if (!isset($config['ad_adv_perms'])) { + config_update_value('ad_adv_perms', ''); + } else { + if (!json_decode(io_safe_output($config['ad_adv_perms']))) { + $temp_ad_adv_perms = []; + if (!isset($config['ad_adv_perms']) && $config['ad_adv_perms'] != '') { + $perms = explode(';', io_safe_output($config['ad_adv_perms'])); + foreach ($perms as $ad_adv_perm) { + if (preg_match('/[\[\]]/', $ad_adv_perm)) { + $all_data = explode(',', io_safe_output($ad_adv_perm)); + $profile = $all_data[0]; + $group_pnd = $all_data[1]; + $groups_ad = str_replace(['[', ']'], '', $all_data[2]); + $tags = str_replace(['[', ']'], '', $all_data[3]); + $groups_ad = explode('|', $groups_ad); + $tags_name = explode('|', $tags); + $tags_ids = []; + foreach ($tags_name as $tag) { + $tags_ids[] = tags_get_id($tag); + } + + $profile = profile_get_profiles( + [ + 'name' => io_safe_input($profile), + ] + ); + if (!$profile) { + continue; + } + + $profile_id = array_keys($profile); + $id_grupo = groups_get_id(io_safe_input($group_pnd), false); + $new_ad_adv_perms[] = [ + 'profile' => $profile_id[0], + 'group' => [$id_grupo], + 'tags' => $tags_ids, + 'groups_ad' => $groups_ad, + ]; + } else { + $all_data = explode(',', io_safe_output($ad_adv_perm)); + $profile = $all_data[0]; + $group_pnd = $all_data[1]; + $groups_ad = $all_data[2]; + $tags = $all_data[3]; + $profile = profile_get_profiles( + [ + 'name' => io_safe_input($profile), + ] + ); + if (!$profile) { + continue; + } + + $profile_id = array_keys($profile); + $id_grupo = groups_get_id(io_safe_input($group_pnd), false); + + $new_ad_adv_perms[] = [ + 'profile' => $profile_id[0], + 'group' => [$id_grupo], + 'tags' => [$tags], + 'groups_ad' => [$groups_ad], + ]; + } + } + + if (!empty($new_ad_adv_perms)) { + $temp_ad_adv_perms = json_encode($new_ad_adv_perms); + } + } + + config_update_value('ad_adv_perms', $temp_ad_adv_perms); + } + } + + if (!isset($config['ldap_adv_perms'])) { + config_update_value('ldap_adv_perms', ''); + } else { + if (!json_decode(io_safe_output($config['ldap_adv_perms']))) { + $temp_ldap_adv_perms = []; + if (!isset($config['ad_adv_perms']) && $config['ldap_adv_perms'] != '') { + $perms = explode(';', io_safe_output($config['ldap_adv_perms'])); + foreach ($perms as $ad_adv_perm) { + if (preg_match('/[\[\]]/', $ad_adv_perm)) { + $all_data = explode(',', io_safe_output($ad_adv_perm)); + $profile = $all_data[0]; + $group_pnd = $all_data[1]; + $groups_ad = str_replace(['[', ']'], '', $all_data[2]); + $tags = str_replace(['[', ']'], '', $all_data[3]); + $groups_ad = explode('|', $groups_ad); + $tags_name = explode('|', $tags); + $tags_ids = []; + foreach ($tags_name as $tag) { + $tags_ids[] = tags_get_id($tag); + } + + $profile = profile_get_profiles( + [ + 'name' => io_safe_input($profile), + ] + ); + if (!$profile) { + continue; + } + + $profile_id = array_keys($profile); + $id_grupo = groups_get_id(io_safe_input($group_pnd), false); + $new_ldap_adv_perms[] = [ + 'profile' => $profile_id[0], + 'group' => [$id_grupo], + 'tags' => $tags_ids, + 'groups_ldap' => $groups_ldap, + ]; + } else { + $all_data = explode(',', io_safe_output($ad_adv_perm)); + $profile = $all_data[0]; + $group_pnd = $all_data[1]; + $groups_ad = $all_data[2]; + $tags = $all_data[3]; + $profile = profile_get_profiles( + [ + 'name' => io_safe_input($profile), + ] + ); + if (!$profile) { + continue; + } + + $profile_id = array_keys($profile); + $id_grupo = groups_get_id(io_safe_input($group_pnd), false); + + $new_ldap_adv_perms[] = [ + 'profile' => $profile_id[0], + 'group' => [$id_grupo], + 'tags' => [$tags], + 'groups_ldap' => [$groups_ldap], + ]; + } + } + + if (!empty($new_ldap_adv_perms)) { + $temp_ldap_adv_perms = json_encode($new_ldap_adv_perms); + } + } + + config_update_value('ldap_adv_perms', $temp_ldap_adv_perms); + } + } + + if (!isset($config['rpandora_server'])) { + config_update_value('rpandora_server', 'localhost'); + } + + if (!isset($config['rpandora_port'])) { + config_update_value('rpandora_port', 3306); + } + + if (!isset($config['rpandora_dbname'])) { + config_update_value('rpandora_dbname', 'pandora'); + } + + if (!isset($config['rpandora_user'])) { + config_update_value('rpandora_user', 'pandora'); + } + + if (!isset($config['rpandora_pass'])) { + config_update_value('rpandora_pass', ''); + } + + if (!isset($config['rintegria_server'])) { + config_update_value('rintegria_server', 'localhost'); + } + + if (!isset($config['rintegria_port'])) { + config_update_value('rintegria_port', 3306); + } + + if (!isset($config['rintegria_dbname'])) { + config_update_value('rintegria_dbname', 'integria'); + } + + if (!isset($config['rintegria_user'])) { + config_update_value('rintegria_user', 'integria'); + } + + if (!isset($config['rintegria_pass'])) { + config_update_value('rintegria_pass', ''); + } + + if (!isset($config['saml_path'])) { + config_update_value('saml_path', '/opt/'); + } + + if (!isset($config['autoupdate'])) { + config_update_value('autoupdate', 1); + } + + if (!isset($config['api_password'])) { + config_update_value('api_password', ''); + } + + if (defined('METACONSOLE')) { + // Customizable sections (Metaconsole). + enterprise_include_once('include/functions_enterprise.php'); + $customizable_sections = enterprise_hook('enterprise_get_customizable_sections'); + + if ($customizable_sections != ENTERPRISE_NOT_HOOK) { + foreach ($customizable_sections as $k => $v) { + if (!isset($config[$k])) { + config_update_value($k, $v['default']); + } + } + } + + if (!isset($config['meta_num_elements'])) { + config_update_value('meta_num_elements', 100); + } + } + + if (!isset($config['relative_path']) && (isset($_POST['nick']) + || isset($config['id_user'])) && isset($config['enterprise_installed']) + ) { + $isFunctionSkins = enterprise_include_once('include/functions_skins.php'); + if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK) { + // Try to update user table in order to refresh skin inmediatly. + $is_user_updating = get_parameter('sec2', ''); + + if ($is_user_updating == 'operation/users/user_edit') { + $id = get_parameter_get('id', $config['id_user']); + // ID given as parameter. + $user_info = get_user_info($id); + + // If current user is editing himself or if the user has UM (User Management) rights on any groups the user is part of AND the authorization scheme allows for users/admins to update info. + if (($config['id_user'] == $id || check_acl($config['id_user'], users_get_groups($id), 'UM')) && $config['user_can_update_info']) { + $view_mode = false; + } else { + $view_mode = true; + } + + if (isset($_GET['modified']) && !$view_mode) { + $upd_info['id_skin'] = get_parameter('skin', $user_info['id_skin']); + $return_update_skin = update_user($id, $upd_info); + } + } + + if (!is_metaconsole()) { + // Skins are available only in console mode. + if (isset($config['id_user'])) { + $relative_path = enterprise_hook('skins_set_image_skin_path', [$config['id_user']]); + } else { + $relative_path = enterprise_hook('skins_set_image_skin_path', [get_parameter('nick')]); + } + } else { + $relative_path = ''; + } + + $config['relative_path'] = $relative_path; + } + } + + if (!isset($config['dbtype'])) { + config_update_value('dbtype', 'mysql'); + } + + if (!isset($config['vc_refr'])) { + config_update_value('vc_refr', 300); + } + + if (!isset($config['agent_size_text_small'])) { + config_update_value('agent_size_text_small', 18); + } + + if (!isset($config['agent_size_text_medium'])) { + config_update_value('agent_size_text_medium', 50); + } + + if (!isset($config['module_size_text_small'])) { + config_update_value('module_size_text_small', 25); + } + + if (!isset($config['module_size_text_medium'])) { + config_update_value('module_size_text_medium', 50); + } + + if (!isset($config['description_size_text'])) { + config_update_value('description_size_text', 60); + } + + if (!isset($config['item_title_size_text'])) { + config_update_value('item_title_size_text', 45); + } + + if (!isset($config['simple_module_value'])) { + config_update_value('simple_module_value', 1); + } + + if (!isset($config['gis_label'])) { + config_update_value('gis_label', 0); + } + + if (!isset($config['interface_unit'])) { + config_update_value('interface_unit', __('Bytes')); + } + + if (!isset($config['graph_precision'])) { + config_update_value('graph_precision', 1); + } else { + if (!isset($config['enterprise_installed'])) { + config_update_value('graph_precision', 1); + } + } + + if (!isset($config['gis_default_icon'])) { + config_update_value('gis_default_icon', 'marker'); + } + + if (!isset($config['interval_values'])) { + config_update_value('interval_values', ''); + } + + if (!isset($config['public_url'])) { + config_update_value('public_url', ''); + } + + if (!isset($config['referer_security'])) { + config_update_value('referer_security', 0); + } + + if (!isset($config['event_storm_protection'])) { + config_update_value('event_storm_protection', 0); + } + + if (!isset($config['server_log_dir'])) { + config_update_value('server_log_dir', ''); + } + + if (!isset($config['max_log_size'])) { + config_update_value('max_log_size', 512); + } + + if (!isset($config['show_group_name'])) { + config_update_value('show_group_name', 0); + } + + if (!isset($config['custom_graph_width'])) { + config_update_value('custom_graph_width', 1); + } + + if (!isset($config['type_module_charts'])) { + config_update_value('type_module_charts', 'area'); + } + + if (!isset($config['type_interface_charts'])) { + config_update_value('type_interface_charts', 'line'); + } + + if (!isset($config['render_proc'])) { + config_update_value('render_proc', 0); + } + + if (!isset($config['graph_image_height'])) { + config_update_value('graph_image_height', 280); + } + + if (!isset($config['zoom_graph'])) { + config_update_value('zoom_graph', 1); + } + + if (!isset($config['render_proc_ok'])) { + config_update_value('render_proc_ok', __('Ok')); + } + + if (!isset($config['render_proc_fail'])) { + config_update_value('render_proc_fail', __('Fail')); + } + + // Daniel maya 02/06/2016 Display menu with click --INI. + if (!isset($config['click_display'])) { + config_update_value('click_display', 1); + } + + // Daniel maya 02/06/2016 Display menu with click --END. + if (isset($config['enterprise_installed']) && $config['enterprise_installed'] == 1) { + if (!isset($config['service_label_font_size'])) { + config_update_value('service_label_font_size', 20); + } + + if (!isset($config['service_item_padding_size'])) { + config_update_value('service_item_padding_size', 80); + } + } + + if (!isset($config['classic_menu'])) { + config_update_value('classic_menu', 0); + } + + if (!isset($config['csv_divider'])) { + config_update_value('csv_divider', ';'); + } + + if (!isset($config['command_snapshot'])) { + config_update_value('command_snapshot', 1); + } + + if (!isset($config['custom_report_info'])) { + config_update_value('custom_report_info', 1); + } + + // Juanma (06/05/2014) New feature: Custom front page for reports. + if (!isset($config['custom_report_front'])) { + config_update_value('custom_report_front', 0); + } + + if (!isset($config['custom_report_front_font'])) { + config_update_value('custom_report_front_font', 'FreeSans.ttf'); + } + + if (!isset($config['custom_report_front_logo'])) { + config_update_value( + 'custom_report_front_logo', + 'images/pandora_logo_white.jpg' + ); + } + + if (!isset($config['custom_report_front_header'])) { + config_update_value('custom_report_front_header', ''); + } + + if (!isset($config['custom_report_front_firstpage'])) { + config_update_value( + 'custom_report_front_firstpage', + '<p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><img src="(_URLIMAGE_)/images/pandora_report_logo.png" alt="" width="800" /></p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><span style="font-size: xx-large;">(_REPORT_NAME_)</span></p> <p style="text-align: center;"><span style="font-size: large;">(_DATETIME_)</span></p>' + ); + } + + if (!isset($config['custom_report_front_footer'])) { + config_update_value('custom_report_front_footer', ''); + } + + if (!isset($config['autohidden_menu'])) { + config_update_value('autohidden_menu', 0); + } + + if (!isset($config['visual_animation'])) { + config_update_value('visual_animation', 1); + } + + if (!isset($config['networkmap_max_width'])) { + config_update_value('networkmap_max_width', 900); + } + + if (!isset($config['short_module_graph_data'])) { + config_update_value('short_module_graph_data', ''); + } + + if (!isset($config['tutorial_mode'])) { + config_update_value('tutorial_mode', 'full'); + } + + if (!isset($config['post_process_custom_values'])) { + config_update_value( + 'post_process_custom_values', + json_encode([]) + ); + } + + if (!isset($config['update_manager_proxy_server'])) { + config_update_value( + 'update_manager_proxy_server', + '' + ); + } + + if (!isset($config['update_manager_proxy_port'])) { + config_update_value( + 'update_manager_proxy_port', + '' + ); + } + + if (!isset($config['update_manager_proxy_user'])) { + config_update_value( + 'update_manager_proxy_user', + '' + ); + } + + if (!isset($config['update_manager_proxy_password'])) { + config_update_value( + 'update_manager_proxy_password', + '' + ); + } + + if (!isset($config['session_timeout'])) { + config_update_value('session_timeout', 90); + } + + if (!isset($config['max_file_size'])) { + config_update_value('max_file_size', '2M'); + } + + if (!isset($config['initial_wizard'])) { + config_update_value('initial_wizard', 0); + } + + if (!isset($config['identification_reminder'])) { + config_update_value('identification_reminder', 1); + } + + if (!isset($config['identification_reminder_timestamp'])) { + config_update_value('identification_reminder_timestamp', 0); + } + + if (!isset($config['instance_registered'])) { + config_update_value('instance_registered', 0); + } + + // Ehorus. + if (!isset($config['ehorus_enabled'])) { + config_update_value('ehorus_enabled', 0); + } + + if (!isset($config['ehorus_custom_field'])) { + config_update_value('ehorus_custom_field', 'eHorusID'); + } + + if (!isset($config['ehorus_hostname'])) { + config_update_value('ehorus_hostname', 'portal.ehorus.com'); + } + + if (!isset($config['ehorus_port'])) { + config_update_value('ehorus_port', 18080); + } + + if (!isset($config['ehorus_req_timeout'])) { + config_update_value('ehorus_req_timeout', 5); + } + + if (is_metaconsole()) { + if (!isset($config['metaconsole_deploy_collection'])) { + config_update_value('metaconsole_deploy_collection', 0); + } + + if (!isset($config['metaconsole_deploy_inventory_plugin'])) { + config_update_value('metaconsole_deploy_inventory_plugin', 0); + } + + if (!isset($config['metaconsole_deploy_plugin_server'])) { + config_update_value('metaconsole_deploy_plugin_server', 0); + } + } + + // Finally, check if any value was overwritten in a form. + config_update_config(); } -function config_check () { - global $config; - - // At this first version I'm passing errors using session variables, because the error management - // is done by an AJAX request. Better solutions could be implemented in the future :-) - - if (license_free() && users_is_admin($config['id_user'])) { - - $login = get_parameter ('login', false); - //Registration advice - if ((!isset ($config['instance_registered']) || ($config['instance_registered'] != 1)) && ($login === false)) { - set_pandora_error_for_header( - __('Click here to start the registration process'), - __("This instance is not registered in the Update manager")); - } - - //Newsletter advice - $newsletter = db_get_value ('middlename', 'tusuario', 'id_user', $config['id_user']); - if ($newsletter != 1 && $login === false) { - set_pandora_error_for_header( - __('Click here to start the newsletter subscription process'), - __("Not subscribed to the newsletter")); - } - } - - // Check default password for "admin" - $is_admin = db_get_value('is_admin', 'tusuario', 'id_user', $config['id_user']); - if ($is_admin) { - $hashpass = db_get_sql ("SELECT password - FROM tusuario WHERE id_user = 'admin'"); - if ($hashpass == "1da7ee7d45b96d0e1f45ee4ee23da560") { - set_pandora_error_for_header( - __('Default password for "Admin" user has not been changed.'), - __('Please change the default password because is a common vulnerability reported.')); - } - } - - if (isset ($config['license_expired'])) { - set_pandora_error_for_header( - __('You can not get updates until you renew the license.'), - __('This license has expired.')); - } - - if (!is_writable ("attachment")) { - set_pandora_error_for_header( - __('Please check that the web server has write rights on the {HOMEDIR}/attachment directory'), - __('Attachment directory is not writable by HTTP Server')); - } - - // Get remote file dir. - $remote_config = io_safe_output(db_get_value_filter('value', - 'tconfig', array('token' => 'remote_config'))); - - - if (enterprise_installed()) { - - if (!is_readable ($remote_config)) { - set_pandora_error_for_header( - __('Remote configuration directory is not readble for the console') . - ' - ' . $remote_config); - } - - $remote_config_conf = $remote_config . "/conf"; - if (!is_writable ($remote_config_conf)) { - set_pandora_error_for_header(__('Remote configuration directory is not writtable for the console') . - ' - ' . $remote_config . '/conf'); - } - - $remote_config_col = $remote_config . "/collections"; - if (!is_writable ($remote_config_col)) { - set_pandora_error_for_header( - __('Remote configuration directory is not writtable for the console') . - ' - ' . $remote_config . '/collections'); - } - } - - // Check attachment directory (too much files?) - - $filecount = count(glob($config["homedir"]."/attachment/*")); - // N temporal files of trash should be enough for most people. - if ($filecount > $config['num_files_attachment']) { - set_pandora_error_for_header( - __("There are too much files in attachment directory. This is not fatal, but you should consider cleaning up your attachment directory manually"). " ( $filecount ". __("files") . " )", - __('Too much files in your tempora/attachment directory')); - } - - // Check database maintance - $db_maintance = db_get_value_filter('value', 'tconfig', - array('token' => 'db_maintance')); - - // If never was executed, it means we are in the first Pandora FMS execution. Set current timestamp - if (empty($db_maintance)) { - config_update_value ('db_maintance', date("U")); - } - - $last_maintance = date("U") - $db_maintance; - // ~ about 50 hr - if ($last_maintance > 190000) { - set_pandora_error_for_header( - __("Your database is not maintained correctly. It seems that more than 48hrs have passed without proper maintenance. Please review documents of %s on how to perform this maintenance process (DB Tool) and enable it as soon as possible.", get_product_name()), - __("Database maintance problem")); - } - - $fontpath = io_safe_output(db_get_value_filter('value', 'tconfig', array('token' => 'fontpath'))); - if (($fontpath == "") OR (!file_exists ($fontpath))) { - set_pandora_error_for_header( - __('Your defined font doesnt exist or is not defined. Please check font parameters in your config'), - __("Default font doesnt exist")); - } - - if ($config['event_storm_protection']) { - set_pandora_error_for_header( - __('You need to restart server after altering this configuration setting.'), - __('Event storm protection is activated. No events will be generated during this mode.')); - } - - global $develop_bypass; - - if ($develop_bypass == 1) { - set_pandora_error_for_header( - __('Your %s has the "develop_bypass" mode enabled. This is a developer mode and should be disabled in a production system. This value is written in the main index.php file', get_product_name()), - __("Developer mode is enabled")); - } - - if (isset($_SESSION['new_update'])) { - if (!empty($_SESSION['return_installation_open'])) { - if (!$_SESSION['return_installation_open']['return']) { - foreach ($_SESSION['return_installation_open']['text'] as $message) { - set_pandora_error_for_header( - $message, - __("Error first setup Open update")); - } - } - } - if ($_SESSION['new_update'] == 'new') { - set_pandora_error_for_header( - __('There is a new update available. Please go to Administration:Setup:Update Manager for more details.'), - __("New %s Console update", get_product_name())); - } - } - - // PHP configuration values - $PHPupload_max_filesize = config_return_in_bytes(ini_get('upload_max_filesize')); - $PHPmax_input_time = ini_get('max_input_time'); - $PHPmemory_limit = config_return_in_bytes(ini_get('memory_limit')); - $PHPmax_execution_time = ini_get('max_execution_time'); - $PHPsafe_mode = ini_get('safe_mode'); - $PHPdisable_functions = ini_get('disable_functions'); - - if ($PHPsafe_mode === '1') { - set_pandora_error_for_header( - __('To disable, change it on your PHP configuration file (php.ini) and put safe_mode = Off (Dont forget restart apache process after changes)'), - sprintf(__("PHP safe mode is enabled. Some features may not properly work."))); - } - - if ($PHPmax_input_time !== '-1') { - set_pandora_error_for_header( - sprintf(__('Recommended value is %s'), '-1 (' . __('Unlimited') . ')') . '

' . __('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), - sprintf(__("Not recommended '%s' value in PHP configuration"), 'max_input_time')); - } - - if ($PHPmax_execution_time !== '0') { - set_pandora_error_for_header( - sprintf(__('Recommended value is: %s'), '0 (' . __('Unlimited') . ')') . '

' . __('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), - sprintf(__("Not recommended '%s' value in PHP configuration"), 'max_execution_time')); - } - - $PHPupload_max_filesize_min = config_return_in_bytes('800M'); - - if ($PHPupload_max_filesize < $PHPupload_max_filesize_min) { - set_pandora_error_for_header( - sprintf(__('Recommended value is: %s'), sprintf(__('%s or greater'), '800M')) . '

' . __('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), - sprintf(__("Not recommended '%s' value in PHP configuration"), 'upload_max_filesize')); - } +/** + * Start supervisor. + * + * @return void + */ +function config_check() +{ + global $config; - $PHPmemory_limit_min = config_return_in_bytes('500M'); + include_once __DIR__.'/class/ConsoleSupervisor.php'; - if ($PHPmemory_limit < $PHPmemory_limit_min && $PHPmemory_limit !== '-1') { - set_pandora_error_for_header( - sprintf(__('Recommended value is: %s'), sprintf(__('%s or greater'), '500M')) . '

' . __('Please, change it on your PHP configuration file (php.ini) or contact with administrator'), - sprintf(__("Not recommended '%s' value in PHP configuration"), 'memory_limit')); - } + // Enterprise controlles supervisor using discovery cron task. + if (!license_free()) { + $supervisor = new ConsoleSupervisor(false); + $supervisor->run(); + } - if (preg_match("/system/", $PHPdisable_functions) or preg_match("/exec/", $PHPdisable_functions)) { - set_pandora_error_for_header( - __("Variable disable_functions containts functions system() or exec(), in PHP configuration file (php.ini)"). '

' . - __('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), __("Problems with disable functions in PHP.INI")); - } - - $result_ejecution = exec($config['phantomjs_bin'] . '/phantomjs --version'); - if(!isset($result_ejecution) || $result_ejecution == '') { - if ($config['language'] == 'es') { - set_pandora_error_for_header( - __('To be able to create images of the graphs for PDFs, please install the phantom.js extension. For that, it is necessary to follow these steps:') . - 'Click here', - __("phantomjs is not installed")); - } else { - set_pandora_error_for_header( - __('To be able to create images of the graphs for PDFs, please install the phantom.js extension. For that, it is necessary to follow these steps:') . - 'Click here', - __("phantomjs is not installed")); - } - } - - - $php_version = phpversion(); - $php_version_array = explode('.', $php_version); - if($php_version_array[0] < 7){ - if ($config['language'] == 'es') { - $url_help = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_es:Instalaci%C3%B3n_y_actualizaci%C3%B3n_PHP_7'; - } - else{ - $url_help = 'https://wiki.pandorafms.com/index.php?title=Pandora:Documentation_en:_PHP_7'; - } - - set_pandora_error_for_header( - __('For a correct operation of PandoraFMS, PHP must be updated to version 7.0 or higher.') . "
" . - __('Otherwise, functionalities will be lost.') . "
" . - "
  1. " . __('Report download in PDF format') . "
  2. " . - "
  3. " . __('Emails Sending') . "
  4. " . - "
  5. " . __('Metaconsole Collections') . "
  6. " . - "
  7. " . '...' . "
  8. " . - "
" . - ''.__('Access Help').'', - __("PHP UPDATE REQUIRED")); - } } -function config_return_in_bytes($val) { - $val = trim($val); - $last = strtolower($val[strlen($val) - 1]); - switch ($last) { - // The 'G' modifier is available since PHP 5.1.0 - case 'g': - $val *= 1024; - case 'm': - $val *= 1024; - case 'k': - $val *= 1024; - } - - return $val; + +/** + * Return in bytes + * + * @param string $val Value to convert. + * + * @return integer + */ +function config_return_in_bytes($val) +{ + $val = trim($val); + $last = strtolower($val[(strlen($val) - 1)]); + switch ($last) { + // The 'G' modifier is available since PHP 5.1.0. + case 'g': + $val *= 1024; + case 'm': + $val *= 1024; + case 'k': + $val *= 1024; + default: + // Ignore. + break; + } + + return $val; } -function config_user_set_custom_config() { - global $config; - - $userinfo = get_user_info ($config['id_user']); - - // Refresh the last_connect info in the user table - // if last update was more than 5 minutes ago - if ($userinfo['last_connect'] < (time()-SECONDS_1MINUTE)) { - update_user($config['id_user'], array('last_connect' => time())); - } - if (!empty($userinfo["block_size"]) && ($userinfo["block_size"] != 0)) - $config["block_size"] = $userinfo["block_size"]; +/** + * Undocumented function + * + * @return void + */ +function config_user_set_custom_config() +{ + global $config; - // Each user could have it's own timezone) - if (isset($userinfo["timezone"])) { - if ($userinfo["timezone"] != "") { - date_default_timezone_set($userinfo["timezone"]); - } - } - - if (defined('METACONSOLE')) { - $config['metaconsole_access'] = $userinfo["metaconsole_access"]; - } + $userinfo = get_user_info($config['id_user']); + + // Refresh the last_connect info in the user table. + // if last update was more than 5 minutes ago. + if ($userinfo['last_connect'] < (time() - SECONDS_1MINUTE)) { + update_user($config['id_user'], ['last_connect' => time()]); + } + + if (!empty($userinfo['block_size']) && ($userinfo['block_size'] != 0)) { + $config['block_size'] = $userinfo['block_size']; + } + + // Each user could have it's own timezone). + if (isset($userinfo['timezone'])) { + if ($userinfo['timezone'] != '') { + date_default_timezone_set($userinfo['timezone']); + } + } + + if (defined('METACONSOLE')) { + $config['metaconsole_access'] = $userinfo['metaconsole_access']; + } } -function config_prepare_session() { - global $config; - if(isset($config["id_user"])){ - $user = users_get_user_by_id($config["id_user"]); - $user_sesion_time = $user['session_time']; - } - else{ - $user_sesion_time = null; - } +/** + * Undocumented function + * + * @return void + */ +function config_prepare_session() +{ + global $config; - if ($user_sesion_time == 0) { - // Change the session timeout value to session_timeout minutes // 8*60*60 = 8 hours - $sessionCookieExpireTime = $config["session_timeout"]; - } - else { - // Change the session timeout value to session_timeout minutes // 8*60*60 = 8 hours - $sessionCookieExpireTime = $user_sesion_time; - } + if (isset($config['id_user'])) { + $user = users_get_user_by_id($config['id_user']); + $user_sesion_time = $user['session_time']; + } else { + $user_sesion_time = null; + } - if ($sessionCookieExpireTime <= 0) - $sessionCookieExpireTime = 10 * 365 * 24 * 60 * 60; - else - $sessionCookieExpireTime *= 60; + if ($user_sesion_time == 0) { + // Change the session timeout value to session_timeout minutes // 8*60*60 = 8 hours. + $sessionCookieExpireTime = $config['session_timeout']; + } else { + // Change the session timeout value to session_timeout minutes // 8*60*60 = 8 hours. + $sessionCookieExpireTime = $user_sesion_time; + } - // Reset the expiration time upon page load //session_name() is default name of session PHPSESSID - if (isset($_COOKIE[session_name()])) - setcookie(session_name(), $_COOKIE[session_name()], time() + $sessionCookieExpireTime, "/"); + if ($sessionCookieExpireTime <= 0) { + $sessionCookieExpireTime = (10 * 365 * 24 * 60 * 60); + } else { + $sessionCookieExpireTime *= 60; + } - ini_set("post_max_size", $config["max_file_size"]); - ini_set("upload_max_filesize", $config["max_file_size"]); + // Reset the expiration time upon page load //session_name() is default name of session PHPSESSID. + if (isset($_COOKIE[session_name()])) { + setcookie(session_name(), $_COOKIE[session_name()], (time() + $sessionCookieExpireTime), '/'); + } + + ini_set('post_max_size', $config['max_file_size']); + ini_set('upload_max_filesize', $config['max_file_size']); } -?> From 8041c66f4c7db74260bfa07b5ca4bcfb2a9b0504 Mon Sep 17 00:00:00 2001 From: enriquecd Date: Thu, 7 Feb 2019 16:28:05 +0100 Subject: [PATCH 058/249] Add _id_trap_ macro to snmp alert macros - #3439 Former-commit-id: 81fca58b445355834e136be8f0c09d6ea3a8f54f --- pandora_server/lib/PandoraFMS/Core.pm | 1 + 1 file changed, 1 insertion(+) diff --git a/pandora_server/lib/PandoraFMS/Core.pm b/pandora_server/lib/PandoraFMS/Core.pm index 3bfd1e1a7d..4682c38820 100644 --- a/pandora_server/lib/PandoraFMS/Core.pm +++ b/pandora_server/lib/PandoraFMS/Core.pm @@ -3454,6 +3454,7 @@ sub pandora_evaluate_snmp_alerts ($$$$$$$$$) { # Specific SNMP Trap alert macros for regexp selectors in trap info my %macros; + $macros{'_trap_id_'} = $trap_id; $macros{'_snmp_oid_'} = $trap_oid; $macros{'_snmp_value_'} = $trap_value; From 23a8d0640f3a4902cb2af48070e1aa50cfa3ed90 Mon Sep 17 00:00:00 2001 From: Samuel Carcases Date: Thu, 7 Feb 2019 17:05:05 +0100 Subject: [PATCH 059/249] Update events.build_query.php Former-commit-id: 189244aa57d58eb33dd43f707eb6ac929f58e537 --- pandora_console/operation/events/events.build_query.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/operation/events/events.build_query.php b/pandora_console/operation/events/events.build_query.php index ec6c274cba..f912c66bf1 100755 --- a/pandora_console/operation/events/events.build_query.php +++ b/pandora_console/operation/events/events.build_query.php @@ -172,7 +172,7 @@ if ($meta) { $id_agent = get_parameter('id_agent', 0); if ($id_agent) { $sql_post .= ' AND agent_name IN (SELECT nombre FROM tmetaconsole_agent WHERE - id_tagente ='.$id_agent." AND alias LIKE '".io_safe_input($text_agent)."')"; + id_tagente ='.$id_agent." AND alias LIKE '".$text_agent."')"; $filter_resume['agent'] = $text_agent; } } else { From 7fa344c2a4e8dd90d869dc6cd37a8ab9de85b22c Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 7 Feb 2019 17:53:09 +0100 Subject: [PATCH 060/249] Change the global configuration notification to AJAX Former-commit-id: a9017377c8ed6780170c0f418ec3e9bc39f7782c --- .../godmode/setup/setup_notifications.php | 146 +++++++++++++----- .../include/functions_notifications.php | 26 ++-- 2 files changed, 123 insertions(+), 49 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index d315f14711..f8ce35c9f8 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -56,36 +56,31 @@ if (get_parameter('remove_source_on_database', 0)) { return; } -// Form actions. if (get_parameter('update_config', 0)) { - $res_global = array_reduce( - notifications_get_all_sources(), - function ($carry, $source) { - $id = notifications_desc_to_id($source['description']); - if (empty($id)) { - return false; - } + $source = (int) get_parameter('source', 0); + $element = (string) get_parameter('element', ''); + $value = (int) get_parameter('value', 0); - $enable_value = switch_to_int(get_parameter("enable-$id")); - $mail_value = (int) get_parameter("mail-{$id}", 0); - $user_value = (int) get_parameter("user-{$id}", 0); - $postpone_value = (int) get_parameter("postpone-{$id}", 0); - $all_users = (int) get_parameter("all-{$id}", 0); - $res = db_process_sql_update( + // Update the label value. + ob_clean(); + $res = false; + switch ($element) { + // All users has other action. + case 'all_users': + $res = $value ? notifications_add_group_to_source($source, [0]) : notifications_remove_group_from_source($source, [0]); + break; + + default: + $res = (bool) db_process_sql_update( 'tnotification_source', - [ - 'enabled' => $enable_value, - 'user_editable' => $user_value, - 'also_mail' => $mail_value, - 'max_postpone_time' => $postpone_value, - ], - ['id' => $source['id']] + [$element => $value], + ['id' => $source] ); - $all_users_res = $all_users ? notifications_add_group_to_source($source['id'], [0]) : notifications_remove_group_from_source($source['id'], [0]); - return $all_users_res && $res && $carry; - }, - true - ); + break; + } + + echo json_encode(['result' => $res]); + return; } // Notification table. It is just a wrapper. @@ -103,22 +98,11 @@ $table_content->data = array_map( }, notifications_get_all_sources() ); -$table_content->data[] = html_print_submit_button( - __('Update'), - 'update_button', - false, - 'class="sub upd" style="display: flex; "', - true -); -echo '
'; -html_print_input_hidden('update_config', 1); html_print_table($table_content); -echo '
'; ?> diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 5c232709de..1142f19ebe 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -340,17 +340,15 @@ function notifications_remove_users_from_source($source_id, $users) */ function notifications_add_group_to_source($source_id, $groups) { - // Source id is mandatory + // Source id is mandatory. if (!isset($source_id)) { return false; } - // Insert into database all groups passed + // Insert into database all groups passed. $res = true; foreach ($groups as $group) { - if (empty($group)) { - continue; - } + if (!isset($group)) continue; $res = $res && db_process_sql_insert( 'tnotification_source_group', @@ -560,11 +558,13 @@ function notifications_print_ball() */ function notifications_print_global_source_configuration($source) { - // Get some values to generate the title + // Get some values to generate the title. $id = notifications_desc_to_id($source['description']); $switch_values = [ 'name' => 'enable-'.$id, 'value' => $source['enabled'], + 'id' => 'nt-'.$source['id'].'-enabled', + 'class' => 'elem-clickable', ]; // Search if group all is set and handle that situation @@ -585,17 +585,16 @@ function notifications_print_global_source_configuration($source) $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $id, $is_group_all); $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $id, $is_group_all); $html_selectors .= ''; - // Generate the checkboxes and time select $html_checkboxes = "
"; $html_checkboxes .= ' '; - $html_checkboxes .= html_print_checkbox("all-$id", 1, $is_group_all, true, false, 'notifications_disable_source(event)'); + $html_checkboxes .= html_print_checkbox_extended("all-$id", 1, $is_group_all, false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-all_users"'); $html_checkboxes .= __('Notify all users'); $html_checkboxes .= '
'; - $html_checkboxes .= html_print_checkbox("mail-$id", 1, $source['also_mail'], true); + $html_checkboxes .= html_print_checkbox_extended("mail-$id", 1, $source['also_mail'], false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-also_mail"'); $html_checkboxes .= __('Also email users with notification content'); $html_checkboxes .= '
'; - $html_checkboxes .= html_print_checkbox("user-$id", 1, $source['user_editable'], true); + $html_checkboxes .= html_print_checkbox_extended("user-$id", 1, $source['user_editable'], false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-user_editable"'); $html_checkboxes .= __('Users can modify notification preferences'); $html_checkboxes .= ' '; $html_checkboxes .= '
'; @@ -613,12 +612,15 @@ function notifications_print_global_source_configuration($source) SECONDS_1MONTH => __('1 month'), NOTIFICATIONS_POSTPONE_FOREVER => __('forever'), ], - "postpone-{$id}", + 'nt-'.$source['id'].'-max_postpone_time', $source['max_postpone_time'], '', '', 0, - true + true, + false, + true, + 'elem-changeable' ); // Return all html From 681ad670288a75f728fc69225e5b1d189891f007 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 7 Feb 2019 18:00:51 +0100 Subject: [PATCH 061/249] ConsoleSuperviso - mailing support and minor fixes Former-commit-id: 86db19d675aa2b7ea37af2839764245fde9ee3c4 --- pandora_console/general/header.php | 930 +++++++++--------- .../include/class/ConsoleSupervisor.php | 105 +- pandora_console/include/functions_config.php | 4 +- .../include/functions_notifications.php | 2 +- pandora_console/pandoradb_data.sql | 8 + 5 files changed, 546 insertions(+), 503 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index 1edcf76b77..80191de038 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -4,509 +4,487 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -require_once ("include/functions_messages.php"); -require_once ('include/functions_servers.php'); -require_once ('include/functions_notifications.php'); +require_once 'include/functions_messages.php'; +require_once 'include/functions_servers.php'; +require_once 'include/functions_notifications.php'; // Check permissions - // Global errors/warnings checking. config_check(); ?> - - - + + - - + unset($servers); + // Since this is the header, we don't like to trickle down variables. + $servers_link_open = ''; + $servers_link_close = ''; + + if ($config['show_qr_code_header'] == 0) { + $show_qr_code_header = 'display: none;'; + } else { + $show_qr_code_header = 'display: inline;'; + } + + $table->data[0]['qr'] = ''; + + echo "'; + ?> + + data[0]['clippy'] = ''.html_print_image( + 'images/clippy_icon.png', + true, + [ + 'id' => 'clippy', + 'class' => 'clippy', + 'alt' => __('%s assistant', get_product_name()), + 'title' => __( + '%s assistant', + get_product_name() + ), + ] + ).''; + } + + + $table->data[0][0] = $servers_link_open.$servers_check_img.$servers_link_close; + + + + + // ======= Autorefresh code ============================= + $autorefresh_txt = ''; + $autorefresh_additional = ''; + + $ignored_params = [ + 'agent_config' => false, + 'code' => false, + ]; + + if (!isset($_GET['sec2'])) { + $_GET['sec2'] = ''; + } + + if (!isset($_GET['refr'])) { + $_GET['refr'] = null; + } + + $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '".$config['id_user']."'"); + $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); + + if ($autorefresh_list !== null && array_search($_GET['sec2'], $autorefresh_list) !== false) { + $do_refresh = true; + if ($_GET['sec2'] == 'operation/agentes/pandora_networkmap') { + if ((!isset($_GET['tab'])) || ($_GET['tab'] != 'view')) { + $do_refresh = false; + } + } + + if ($do_refresh) { + $autorefresh_img = html_print_image('images/header_refresh.png', true, ['class' => 'bot', 'alt' => 'lightning', 'title' => __('Configure autorefresh')]); + + if ($_GET['refr']) { + $autorefresh_txt .= ' ('.date('i:s', $config['refr']).')'; + } + + $ignored_params['refr'] = ''; + $values = get_refresh_time_array(); + $autorefresh_additional = ''; + unset($values); + + $autorefresh_link_open_img = ''; + + if ($_GET['refr']) { + $autorefresh_link_open_txt = ''; + } else { + $autorefresh_link_open_txt = ''; + } + + $autorefresh_link_close = ''; + } else { + $autorefresh_img = html_print_image('images/header_refresh_disabled.png', true, ['class' => 'bot autorefresh_disabled', 'alt' => 'lightning', 'title' => __('Disabled autorefresh')]); + + $ignored_params['refr'] = false; + + $autorefresh_link_open_img = ''; + $autorefresh_link_open_txt = ''; + $autorefresh_link_close = ''; + } + } else { + $autorefresh_img = html_print_image('images/header_refresh_disabled.png', true, ['class' => 'bot autorefresh_disabled', 'alt' => 'lightning', 'title' => __('Disabled autorefresh')]); + + $ignored_params['refr'] = false; + + $autorefresh_link_open_img = ''; + $autorefresh_link_open_txt = ''; + $autorefresh_link_close = ''; + } + + $table->data[0][1] = $autorefresh_link_open_img.$autorefresh_img.$autorefresh_link_close; + $table->data[0][2] = $autorefresh_link_open_txt.$autorefresh_txt.$autorefresh_link_close.$autorefresh_additional; + // ====================================================== + $pandora_management = check_acl($config['id_user'], 0, 'PM'); + + echo ''; + + if ($config['alert_cnt'] > 0) { + $maintenance_link = 'javascript:'; + $maintenance_title = __('System alerts detected - Please fix as soon as possible'); + $maintenance_class = $maintenance_id = 'show_systemalert_dialog white'; + + $maintenance_link_open_txt = ''; + $maintenance_link_open_img = ''; + $maintenance_link_close = ''; + if (!$pandora_management) { + $maintenance_img = ''; + } else { + $maintenance_img = $maintenance_link_open_img.html_print_image( + 'images/header_yellow.png', + true, + [ + 'title' => __( + 'You have %d warning(s)', + $config['alert_cnt'] + ), + 'id' => 'yougotalert', + 'class' => 'bot', + ] + ).$maintenance_link_close; + } + } else { + if (!$pandora_management) { + $maintenance_img = ''; + } else { + $maintenance_img = html_print_image('images/header_ready.png', true, ['title' => __('There are not warnings'), 'id' => 'yougotalert', 'class' => 'bot']); + } + } + + $table->data[0][3] = $maintenance_img; + + // Main help icon + if (!$config['disable_help']) { + $table->data[0][4] = ''.html_print_image( + 'images/header_help.png', + true, + [ + 'title' => __('Main help'), + 'id' => 'helpmodal', + 'class' => 'modalpopup', + ] + ).''; + } + + // Logout + $table->data[0][5] = ''; + $table->data[0][5] .= html_print_image('images/header_logout.png', true, ['alt' => __('Logout'), 'class' => 'bot', 'title' => __('Logout')]); + $table->data[0][5] .= ''; + + // User + if (is_user_admin($config['id_user']) == 1) { + $table->data[0][6] = html_print_image('images/header_user_admin.png', true, ['title' => __('Edit my user'), 'class' => 'bot', 'alt' => 'user']); + } else { + $table->data[0][6] = html_print_image('images/header_user.png', true, ['title' => __('Edit my user'), 'class' => 'bot', 'alt' => 'user']); + } + + $table->data[0][6] = ''.$table->data[0][6].''; + + $table->data[0][7] = ' ('.$config['id_user'].')'; + + // Chat messages + $table->data[0][8] = "'; + + // Messages + $msg_cnt = messages_get_count($config['id_user']); + if ($msg_cnt > 0) { + echo ''; + + $table->data[0][9] = ''; + $table->data[0][9] .= html_print_image('images/header_email.png', true, ['title' => __('You have %d unread message(s)', $msg_cnt), 'id' => 'yougotmail', 'class' => 'bot', 'style' => 'width:24px;']); + $table->data[0][9] .= ''; + } + + $table->data[0]['notifications'] = notifications_print_ball(); + + html_print_table($table); + + unset($table); + ?> + + +
- - $logo_title, "border" => '0')); - ?> - - - id = "header_table"; - $table->class = "none"; - $table->cellpadding = 0; - $table->cellspacing = 0; - $table->head = array (); - $table->data = array (); - $table->style[0] = - $table->style['clippy'] = - $table->style[1] = - $table->style[3] = - $table->style[4] = - $table->style[5] = - $table->style[6] = - $table->style[8] = - $table->style[9] = - $table->style['qr'] = - $table->style['notifications'] = - 'width: 22px; text-align:center; height: 22px; padding-right: 9px;padding-left: 9px;'; - $table->style[7] = 'width: 20px; padding-right: 9px;'; - $table->style['searchbar'] = 'width: 180px; min-width: 180px;'; - $table->style[11] = 'padding-left: 10px; padding-right: 5px;width: 16px;'; - $table->width = "100%"; - $table->styleTable = 'margin: auto; margin-top: 0px;'; - $table->rowclass[0] = ''; - - $acl_head_search = true; - if ($config["acl_enterprise"] == 1 && !users_is_admin()) { - $acl_head_search = db_get_sql("SELECT sec FROM tusuario +
+ + $logo_title, + 'border' => '0', + ] + ); + ?> + + + id = 'header_table'; + $table->class = 'none'; + $table->cellpadding = 0; + $table->cellspacing = 0; + $table->head = []; + $table->data = []; + $table->style[0] = $table->style['clippy'] = $table->style[1] = $table->style[3] = $table->style[4] = $table->style[5] = $table->style[6] = $table->style[8] = $table->style[9] = $table->style['qr'] = $table->style['notifications'] = 'width: 22px; text-align:center; height: 22px; padding-right: 9px;padding-left: 9px;'; + $table->style[7] = 'width: 20px; padding-right: 9px;'; + $table->style['searchbar'] = 'width: 180px; min-width: 180px;'; + $table->style[11] = 'padding-left: 10px; padding-right: 5px;width: 16px;'; + $table->width = '100%'; + $table->styleTable = 'margin: auto; margin-top: 0px;'; + $table->rowclass[0] = ''; + + $acl_head_search = true; + if ($config['acl_enterprise'] == 1 && !users_is_admin()) { + $acl_head_search = db_get_sql( + "SELECT sec FROM tusuario INNER JOIN tusuario_perfil ON tusuario.id_user = tusuario_perfil.id_usuario INNER JOIN tprofile_view ON tprofile_view.id_profile = tusuario_perfil.id_perfil - WHERE tusuario.id_user = '".$config['id_user']."' AND (sec = '*' OR sec = 'head_search')"); - } - if ($acl_head_search) { - $table->data[0][11] = ui_print_help_tip (__("Blank characters are used as AND conditions"), true); - - // Search bar - $search_bar = '
'; - if (!isset($config['search_keywords'])) { - $search_bar .= ''; - } - else { - if (strlen($config['search_keywords']) == 0) - $search_bar .= ''; - else - $search_bar .= ''; - } - - $search_bar .= 'data[0][11] = ui_print_help_tip(__('Blank characters are used as AND conditions'), true); + + // Search bar + $search_bar = ''; + if (!isset($config['search_keywords'])) { + $search_bar .= ''; + } else { + if (strlen($config['search_keywords']) == 0) { + $search_bar .= ''; + } else { + $search_bar .= ''; + } + } + + $search_bar .= ''; - - //$search_bar .= 'onClick="javascript: document.quicksearch.submit()"'; - - $search_bar .= ""; - $search_bar .= '
'; - - $table->data[0]['searchbar'] = $search_bar; - } - - // Servers check - $servers = array(); - $servers["all"] = (int) db_get_value ('COUNT(id_server)','tserver'); - $servers["up"] = (int) servers_check_status (); - $servers["down"] = $servers["all"] - $servers["up"]; - if ($servers["up"] == 0) { - //All Servers down or no servers at all - $servers_check_img = html_print_image("images/header_down.png", true, array("alt" => 'cross', "class" => 'bot', 'title' => __('All systems').': '.__('Down'))); - } - elseif ($servers["down"] != 0) { - //Some servers down - $servers_check_img = html_print_image("images/header_warning.png", true, array("alt" => 'error', "class" => 'bot', 'title' => $servers["down"].' '.__('servers down'))); - } - else { - //All servers up - $servers_check_img = html_print_image("images/header_ready.png", true, array("alt" => 'ok', "class" => 'bot', 'title' => __('All systems').': '.__('Ready'))); - } - unset ($servers); // Since this is the header, we don't like to trickle down variables. - - $servers_link_open = ''; - $servers_link_close = ''; - - if ($config['show_qr_code_header'] == 0){ - $show_qr_code_header = 'display: none;'; - } - else { - $show_qr_code_header = 'display: inline;'; - } - - $table->data[0]['qr'] = - ''; - - echo ""; - ?> - - data[0]['clippy'] = - '' . - html_print_image( - "images/clippy_icon.png", - true, - array("id" => 'clippy', - "class" => 'clippy', - "alt" => __('%s assistant', get_product_name()), - 'title' => __('%s assistant', get_product_name()))) . - ''; - } - - - $table->data[0][0] = $servers_link_open . - $servers_check_img . $servers_link_close; - - - - - //======= Autorefresh code ============================= - $autorefresh_txt = ''; - $autorefresh_additional = ''; - - $ignored_params = array ('agent_config' => false, 'code' => false); - - if (!isset($_GET['sec2'])) { - $_GET['sec2'] = ''; - } - if (!isset($_GET['refr'])) { - $_GET['refr'] = null; - } - - $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '" . $config['id_user'] . "'"); - $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); - - if ($autorefresh_list !== null && array_search($_GET['sec2'], $autorefresh_list) !== false) { - $do_refresh = true; - if ($_GET['sec2'] == 'operation/agentes/pandora_networkmap') { - if ((!isset($_GET['tab'])) || ($_GET['tab'] != 'view')) { - $do_refresh = false; - } - } - if ($do_refresh) { - $autorefresh_img = html_print_image("images/header_refresh.png", true, array("class" => 'bot', "alt" => 'lightning', 'title' => __('Configure autorefresh'))); - - if ($_GET['refr']) { - $autorefresh_txt .= ' ('.date ("i:s", $config["refr"]).')'; - } - - $ignored_params['refr'] = ''; - $values = get_refresh_time_array(); - $autorefresh_additional = ''; - unset ($values); - - $autorefresh_link_open_img = - ''; - - if ($_GET['refr']) { - $autorefresh_link_open_txt = - ''; - } - else { - $autorefresh_link_open_txt = ''; - } - - $autorefresh_link_close = ''; - } - else { - $autorefresh_img = html_print_image("images/header_refresh_disabled.png", true, array("class" => 'bot autorefresh_disabled', "alt" => 'lightning', 'title' => __('Disabled autorefresh'))); - - $ignored_params['refr'] = false; - - $autorefresh_link_open_img = ''; - $autorefresh_link_open_txt = ''; - $autorefresh_link_close = ''; - } - } - else { - $autorefresh_img = html_print_image("images/header_refresh_disabled.png", true, array("class" => 'bot autorefresh_disabled', "alt" => 'lightning', 'title' => __('Disabled autorefresh'))); - - $ignored_params['refr'] = false; - - $autorefresh_link_open_img = ''; - $autorefresh_link_open_txt = ''; - $autorefresh_link_close = ''; - } - - $table->data[0][1] = $autorefresh_link_open_img . $autorefresh_img . $autorefresh_link_close; - $table->data[0][2] = $autorefresh_link_open_txt . $autorefresh_txt . $autorefresh_link_close . $autorefresh_additional; - //====================================================== - - - $check_minor_release_available = false; - $pandora_management = check_acl($config['id_user'], 0, "PM"); - - $check_minor_release_available = db_check_minor_relase_available (); - - if ($check_minor_release_available) { - if (users_is_admin($config['id_user'])) { - - if($config['language'] == 'es'){ - set_pandora_error_for_header('Hay una o mas revisiones menores en espera para ser actualizadas. '.__('Sobre actualización de revisión menor').'', 'Revisión/es menor/es disponible/s'); - } - else{ - set_pandora_error_for_header('There are one or more minor releases waiting for update. '.__('About minor release update').'', 'minor release/s available'); - } - } - } - echo ''; + // $search_bar .= 'onClick="javascript: document.quicksearch.submit()"'; + $search_bar .= ""; + $search_bar .= ''; - if ($config["alert_cnt"] > 0) { - $maintenance_link = 'javascript:'; - $maintenance_title = __("System alerts detected - Please fix as soon as possible"); - $maintenance_class = $maintenance_id = 'show_systemalert_dialog white'; - - $maintenance_link_open_txt = - ''; - $maintenance_link_open_img = - ''; - $maintenance_link_close = ''; - if (!$pandora_management) { - $maintenance_img = ''; - } - else { - $maintenance_img = $maintenance_link_open_img . - html_print_image("images/header_yellow.png", - true, array( - "title" => __('You have %d warning(s)', - $config["alert_cnt"]), - "id" => "yougotalert", - "class" => "bot")) . $maintenance_link_close; - } - } - else { - if (!$pandora_management) { - $maintenance_img = ''; - } - else { - $maintenance_img = html_print_image ("images/header_ready.png", true, array ("title" => __('There are not warnings'), "id" => "yougotalert", "class" => "bot")); - } - } - - $table->data[0][3] = $maintenance_img; - - // Main help icon - if (!$config['disable_help']) { - $table->data[0][4] = - '' . - html_print_image("images/header_help.png", true, array( - "title" => __('Main help'), - "id" => "helpmodal", - "class" => "modalpopup")) . - ''; - } - - // Logout - $table->data[0][5] = ''; - $table->data[0][5] .= html_print_image("images/header_logout.png", true, array("alt" => __('Logout'), "class" => 'bot', "title" => __('Logout'))); - $table->data[0][5] .= ''; - - // User - if (is_user_admin ($config["id_user"]) == 1) - $table->data[0][6] = html_print_image("images/header_user_admin.png" , true, array("title" => __('Edit my user'), "class" => 'bot', "alt" => 'user')); - else - $table->data[0][6] = html_print_image("images/header_user.png" , true, array("title" => __('Edit my user'), "class" => 'bot', "alt" => 'user')); - - $table->data[0][6] = '' . $table->data[0][6] . ''; - - $table->data[0][7] = ' (' . $config["id_user"] . ')'; - - // Chat messages - $table->data[0][8] = ""; - - // Messages - $msg_cnt = messages_get_count ($config["id_user"]); - if ($msg_cnt > 0) { - echo ''; - - $table->data[0][9] = ''; - $table->data[0][9] .= html_print_image ("images/header_email.png", true, array ("title" => __('You have %d unread message(s)', $msg_cnt), "id" => "yougotmail", "class" => "bot", 'style' => 'width:24px;')); - $table->data[0][9] .= ''; - } + $table->data[0]['searchbar'] = $search_bar; + } - $table->data[0]['notifications'] = notifications_print_ball(); + // Servers check + $servers = []; + $servers['all'] = (int) db_get_value('COUNT(id_server)', 'tserver'); + $servers['up'] = (int) servers_check_status(); + $servers['down'] = ($servers['all'] - $servers['up']); + if ($servers['up'] == 0) { + // All Servers down or no servers at all + $servers_check_img = html_print_image('images/header_down.png', true, ['alt' => 'cross', 'class' => 'bot', 'title' => __('All systems').': '.__('Down')]); + } else if ($servers['down'] != 0) { + // Some servers down + $servers_check_img = html_print_image('images/header_warning.png', true, ['alt' => 'error', 'class' => 'bot', 'title' => $servers['down'].' '.__('servers down')]); + } else { + // All servers up + $servers_check_img = html_print_image('images/header_ready.png', true, ['alt' => 'ok', 'class' => 'bot', 'title' => __('All systems').': '.__('Ready')]); + } - html_print_table($table); - - unset($table); - ?> -
diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index 3eaedcfcfb..fb9ca0fff7 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -28,7 +28,7 @@ global $config; -require_once __DIR__.'/../functions.php'; +require_once $config['homedir'].'/include/functions_db.php'; require_once $config['homedir'].'/include/functions_io.php'; require_once $config['homedir'].'/include/functions_notifications.php'; require_once $config['homedir'].'/include/functions_servers.php'; @@ -36,7 +36,7 @@ require_once $config['homedir'].'/include/functions_servers.php'; // Enterprise includes. enterprise_include_once('include/functions_metaconsole.php'); enterprise_include_once('include/functions_license.php'); - +enterprise_include_once('extensions/cron/functions.php'); /** * Base class to run scheduled tasks in cron extension @@ -172,12 +172,6 @@ class ConsoleSupervisor include_once $config['homedir'].'/'.ENTERPRISE_DIR.'/load_enterprise.php'; } - $time = get_system_time(); - $scheduled_tasks = db_get_all_rows_in_table('tuser_task_scheduled'); - if (!$scheduled_tasks) { - $scheduled_tasks = []; - } - // Automatic checks launched by supervisor. $this->warn('running.'); @@ -334,6 +328,13 @@ class ConsoleSupervisor $this->checkUpdates(); + /* + * Check if there're new minor updates available. + * NOTIF.UPDATEMANAGER.MINOR + */ + + $this->checkMinorRelease(); + if ($this->verbose === true) { // Release the lock. enterprise_hook('cron_supervisor_release_lock'); @@ -345,12 +346,17 @@ class ConsoleSupervisor /** * Update targets for given notification using object targets. * - * @param integer $notification_id Current notification. + * @param array $notification Current notification. + * @param boolean $update Only update db targets, no email. * * @return void */ - public function updateTargets(int $notification_id) - { + public function updateTargets( + array $notification, + bool $update=false + ) { + $notification_id = $notification['id_mensaje']; + if (is_array($this->targetUsers) === true && count($this->targetUsers) > 0 ) { @@ -365,10 +371,18 @@ class ConsoleSupervisor ); $insertion_string .= ','; - // Send mail. - if (isset($user['also_mail']) && $user['also_mail'] == 1) { - $this->warn('Mailing user: '.$user['id_user']."\n"); - // TODO: Add sendmail sequence. + if ($update === false) { + // Send mail. + if (isset($user['also_mail']) && $user['also_mail'] == 1) { + enterprise_hook( + 'send_email_user', + [ + $user['id_user'], + io_safe_output($notification['mensaje']).'

'.$notification['url'], + io_safe_output($notification['subject']), + ] + ); + } } } @@ -391,10 +405,19 @@ class ConsoleSupervisor ); $insertion_string .= ','; - // Send mail. - if (isset($group['also_mail']) && $group['also_mail'] == 1) { - $this->warn('Mailing group: '.$group['id_group']."\n"); - // TODO: Add sendmail sequence. + if ($update === false) { + // Send mail. + if (isset($group['also_mail']) && $group['also_mail'] == 1) { + $this->warn('Mailing group: '.$group['id_group']."\n"); + enterprise_hook( + 'send_email_group', + [ + $group['id_group'], + io_safe_output($notification['mensaje']).'

'.$notification['url'], + io_safe_output($notification['subject']), + ] + ); + } } } @@ -422,7 +445,7 @@ class ConsoleSupervisor public function notify( array $data, int $source_id=0, - int $max_age=86400 + int $max_age=0 ) { // Uses 'check failed' logic. if (is_array($data) === false) { @@ -475,7 +498,7 @@ class ConsoleSupervisor case 'NOTIF.NEWSLETTER.SUBSCRIPTION': case 'NOTIF.UPDATEMANAGER.OPENSETUP': case 'NOTIF.UPDATEMANAGER.UPDATE': - + case 'NOTIF.UPDATEMANAGER.MINOR': default: // NOTIF.SERVER.STATUS. // NOTIF.SERVER.STATUS.ID_SERVER. @@ -514,8 +537,7 @@ class ConsoleSupervisor ], ['id_mensaje' => $prev['id_mensaje']] ); - - $this->updateTargets($prev['id_mensaje']); + $this->updateTargets($prev, true); return; } @@ -540,7 +562,7 @@ class ConsoleSupervisor return; } - $this->updateTargets($id); + $this->updateTargets($notification); } @@ -2010,4 +2032,39 @@ class ConsoleSupervisor } + /** + * Check if there're minor updates available. + * + * @return void + */ + public function checkMinorRelease() + { + global $config; + + $check_minor_release_available = db_check_minor_relase_available(); + + if ($check_minor_release_available) { + $url = 'http://wiki.pandorafms.com/index.php?title=Pandora:Documentation_en:Anexo_Upgrade#Version_7.0NG_.28_Rolling_Release_.29'; + if ($config['language'] == 'es') { + $url = 'http://wiki.pandorafms.com/index.php?title=Pandora:Documentation_es:Actualizacion#Versi.C3.B3n_7.0NG_.28_Rolling_Release_.29'; + } + + $this->notify( + [ + 'type' => 'NOTIF.UPDATEMANAGER.MINOR', + 'title' => __('Minor release/s available'), + 'message' => __( + 'There are one or more minor releases waiting for update. .About minor release update.', + $url + ), + 'url' => $url, + ] + ); + } else { + $this->cleanNotifications('NOTIF.UPDATEMANAGER.MINOR'); + } + + } + + } diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index 3af3db3f69..e532deea15 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -2664,8 +2664,8 @@ function config_check() include_once __DIR__.'/class/ConsoleSupervisor.php'; - // Enterprise controlles supervisor using discovery cron task. - if (!license_free()) { + // Enterprise customers launch supervisor using discovery task. + if (license_free()) { $supervisor = new ConsoleSupervisor(false); $supervisor->run(); } diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index c8f46d90ae..2ac5eb1227 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -193,7 +193,7 @@ function get_notification_source_targets(int $id_source) $i = 0; foreach ($users as $user) { $ret['users'][$i]['id_user'] = $user['id_user']; - $ret['users'][$i++]['also_mail'] = $also_mail; + $ret['users'][$i++]['also_mail'] = $user['also_mail']; } } diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index f73ab0af68..e97f7e6a5b 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1278,3 +1278,11 @@ INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, ` ("Advertisement", "icono_info_mr.png", 86400, 1, 1, 0), ("Official communication", "icono_info_mr.png", 86400, 1, 1, 0), ("Sugerence", "icono_info_mr.png", 86400, 1, 1, 0); + +-- +-- Dumping data for table `tnotification_source_user` +-- +INSERT INTO `tnotification_source_user`(`id_source`,`id_user`,`enabled`,`also_mail`) VALUES + ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin",1,0); + + \ No newline at end of file From 04b2cb8665ebda46cf93b5df7a420703a187e79a Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 7 Feb 2019 18:04:14 +0100 Subject: [PATCH 062/249] Use real ids instead fake ids Former-commit-id: 2360a14d1865f918247d23b2f3181626052cad60 --- .../godmode/setup/setup_notifications.php | 20 ++++++------ .../include/functions_notifications.php | 32 ++++++------------- 2 files changed, 18 insertions(+), 34 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index f8ce35c9f8..956571aa1f 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -26,38 +26,36 @@ if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user } // AJAX actions. -$source_id = get_parameter('source_id', ''); +$source = get_parameter('source', ''); $users = get_parameter('users', ''); $elements = get_parameter('elements', []); -$id = empty($source_id) ? 0 : get_notification_source_id($source_id); $is_users = $users === 'users'; if (get_parameter('get_selection_two_ways_form', 0)) { - $info_selec = $is_users ? notifications_get_user_source_not_configured($id) : notifications_get_group_source_not_configured($id); + $info_selec = $is_users ? notifications_get_user_source_not_configured($source) : notifications_get_group_source_not_configured($source); echo notifications_print_two_ways_select( $info_selec, $users, - $source_id + $source ); return; } if (get_parameter('add_source_to_database', 0)) { - $res = $is_users ? notifications_add_users_to_source($id, $elements) : notifications_add_group_to_source($id, $elements); + $res = $is_users ? notifications_add_users_to_source($source, $elements) : notifications_add_group_to_source($source, $elements); $result = ['result' => $res]; echo json_encode($result); return; } if (get_parameter('remove_source_on_database', 0)) { - $res = $is_users ? notifications_remove_users_from_source($id, $elements) : notifications_remove_group_from_source($id, $elements); + $res = $is_users ? notifications_remove_users_from_source($source, $elements) : notifications_remove_group_from_source($source, $elements); $result = ['result' => $res]; echo json_encode($result); return; } if (get_parameter('update_config', 0)) { - $source = (int) get_parameter('source', 0); $element = (string) get_parameter('element', ''); $value = (int) get_parameter('value', 0); @@ -159,7 +157,7 @@ function add_source_dialog(users, source_id) { {"page" : "godmode/setup/setup_notifications", "get_selection_two_ways_form" : 1, "users" : users, - "source_id" : source_id + "source" : source_id }, function (data, status) { not_dialog.innerHTML = data @@ -198,7 +196,7 @@ function notifications_add_source_element_to_database(id, source_id) { {"page" : "godmode/setup/setup_notifications", "add_source_to_database" : 1, "users" : id, - "source_id" : source_id, + "source" : source_id, "elements": selected }, function (data, status) { @@ -236,13 +234,13 @@ function remove_source_elements(id, source_id) { {"page" : "godmode/setup/setup_notifications", "remove_source_on_database" : 1, "users" : id, - "source_id" : source_id, + "source" : source_id, "elements": selected }, function (data, status) { if (data.result) { // Append to other element - for (var i = selected_index.length - 1; i >= 0; i--) { + for (var i = 0; i < selected_index.length; i++) { select.remove(selected_index[i]); } } else { diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 1142f19ebe..768bd67b97 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -51,21 +51,6 @@ function get_notification_source_id(string $source) } -/** - * Converts description into a handable identifier - * - * @param string $desc Full description - * - * @return string First word in lowercase. Empty string if no word detected. - */ -function notifications_desc_to_id(string $desc) -{ - preg_match('/^[a-zA-Z]*/', $desc, $matches); - $match = $matches[0]; - return isset($match) ? $match : ''; -} - - /** * Retrieve all targets for given message. * @@ -348,7 +333,9 @@ function notifications_add_group_to_source($source_id, $groups) // Insert into database all groups passed. $res = true; foreach ($groups as $group) { - if (!isset($group)) continue; + if (!isset($group)) { + continue; + } $res = $res && db_process_sql_insert( 'tnotification_source_group', @@ -559,9 +546,8 @@ function notifications_print_ball() function notifications_print_global_source_configuration($source) { // Get some values to generate the title. - $id = notifications_desc_to_id($source['description']); $switch_values = [ - 'name' => 'enable-'.$id, + 'name' => 'enable-'.$source['id'], 'value' => $source['enabled'], 'id' => 'nt-'.$source['id'].'-enabled', 'class' => 'elem-clickable', @@ -582,19 +568,19 @@ function notifications_print_global_source_configuration($source) // Generate the html for title $html_selectors = "
"; - $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $id, $is_group_all); - $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $id, $is_group_all); + $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $source['id'], $is_group_all); + $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $source['id'], $is_group_all); $html_selectors .= '
'; // Generate the checkboxes and time select $html_checkboxes = "
"; $html_checkboxes .= ' '; - $html_checkboxes .= html_print_checkbox_extended("all-$id", 1, $is_group_all, false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-all_users"'); + $html_checkboxes .= html_print_checkbox_extended('all-'.$source['id'], 1, $is_group_all, false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-all_users"'); $html_checkboxes .= __('Notify all users'); $html_checkboxes .= '
'; - $html_checkboxes .= html_print_checkbox_extended("mail-$id", 1, $source['also_mail'], false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-also_mail"'); + $html_checkboxes .= html_print_checkbox_extended('mail-'.$source['id'], 1, $source['also_mail'], false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-also_mail"'); $html_checkboxes .= __('Also email users with notification content'); $html_checkboxes .= '
'; - $html_checkboxes .= html_print_checkbox_extended("user-$id", 1, $source['user_editable'], false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-user_editable"'); + $html_checkboxes .= html_print_checkbox_extended('user-'.$source['id'], 1, $source['user_editable'], false, '', 'class= "elem-clickable"', true, 'id="nt-'.$source['id'].'-user_editable"'); $html_checkboxes .= __('Users can modify notification preferences'); $html_checkboxes .= ' '; $html_checkboxes .= '
'; From 42b0afb884592da50ed09b85d192b2ba478ae6ed Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 7 Feb 2019 18:07:52 +0100 Subject: [PATCH 063/249] Supervisor minor fixes Former-commit-id: 84171e197df0a016a9a4b7d0e49f0412b65ee864 --- pandora_console/include/class/ConsoleSupervisor.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index fb9ca0fff7..517ed8acd3 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -387,7 +387,6 @@ class ConsoleSupervisor } $insertion_string = substr($insertion_string, 0, -1); - db_process_sql($users_sql.' VALUES '.$insertion_string); } @@ -445,7 +444,7 @@ class ConsoleSupervisor public function notify( array $data, int $source_id=0, - int $max_age=0 + int $max_age=86400 ) { // Uses 'check failed' logic. if (is_array($data) === false) { @@ -562,6 +561,9 @@ class ConsoleSupervisor return; } + // Update reference to update targets. + $notification['id_mensaje'] = $id; + $this->updateTargets($notification); } From e90d4b7256945e5364738844e676cb321383dcb7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 7 Feb 2019 18:29:20 +0100 Subject: [PATCH 064/249] Supervisor added blacklist to avoid mail twice Former-commit-id: e2f03306076d90f9abe312694ea1fa2298ee7c62 --- pandora_console/include/class/ConsoleSupervisor.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index 517ed8acd3..ad21b44345 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -356,6 +356,7 @@ class ConsoleSupervisor bool $update=false ) { $notification_id = $notification['id_mensaje']; + $blacklist = []; if (is_array($this->targetUsers) === true && count($this->targetUsers) > 0 @@ -382,6 +383,7 @@ class ConsoleSupervisor io_safe_output($notification['subject']), ] ); + array_push($blacklist, $user['id_user']); } } } @@ -407,13 +409,14 @@ class ConsoleSupervisor if ($update === false) { // Send mail. if (isset($group['also_mail']) && $group['also_mail'] == 1) { - $this->warn('Mailing group: '.$group['id_group']."\n"); enterprise_hook( 'send_email_group', [ $group['id_group'], io_safe_output($notification['mensaje']).'

'.$notification['url'], io_safe_output($notification['subject']), + null, + $blacklist, ] ); } From 80a5d0b0b926753f0a9f9344a7baa6c250736105 Mon Sep 17 00:00:00 2001 From: Fermin Date: Fri, 8 Feb 2019 10:32:04 +0100 Subject: [PATCH 065/249] Removed unused code and format some files Former-commit-id: 5f8da31efc5241dd16002565fdb89d774072b7b3 --- .../godmode/setup/setup_notifications.php | 66 +++++++-------- .../include/functions_notifications.php | 80 ++++++++++--------- 2 files changed, 74 insertions(+), 72 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 956571aa1f..d6ce67ab90 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -1,18 +1,31 @@ $res]; echo json_encode($result); return; } if (get_parameter('remove_source_on_database', 0)) { - $res = $is_users ? notifications_remove_users_from_source($source, $elements) : notifications_remove_group_from_source($source, $elements); + $res = ($is_users) ? notifications_remove_users_from_source($source, $elements) : notifications_remove_group_from_source($source, $elements); $result = ['result' => $res]; echo json_encode($result); return; @@ -65,7 +78,7 @@ if (get_parameter('update_config', 0)) { switch ($element) { // All users has other action. case 'all_users': - $res = $value ? notifications_add_group_to_source($source, [0]) : notifications_remove_group_from_source($source, [0]); + $res = ($value) ? notifications_add_group_to_source($source, [0]) : notifications_remove_group_from_source($source, [0]); break; default: @@ -89,7 +102,7 @@ $table_content->id = 'notifications-wrapper'; $table_content->class = 'databox filters'; $table_content->size['name'] = '30%'; -// Print each source configuration +// Print each source configuration. $table_content->data = array_map( function ($source) { return notifications_print_global_source_configuration($source); @@ -101,13 +114,6 @@ html_print_table($table_content); ?> '; - } - else { - if (strlen($config['search_keywords']) == 0) - $search_bar .= ''; - else - $search_bar .= ''; - } - - $search_bar .= 'data[0][11] = ui_print_help_tip(__('Blank characters are used as AND conditions'), true); + + // Search bar + $search_bar = '
'; + if (!isset($config['search_keywords'])) { + $search_bar .= ''; + } else { + if (strlen($config['search_keywords']) == 0) { + $search_bar .= ''; + } else { + $search_bar .= ''; + } + } + + $search_bar .= ''; - - //$search_bar .= 'onClick="javascript: document.quicksearch.submit()"'; - - $search_bar .= ""; - $search_bar .= '
'; - - $table->data[0]['searchbar'] = $search_bar; - } - - // Servers check - $servers = array(); - $servers["all"] = (int) db_get_value ('COUNT(id_server)','tserver'); - $servers["up"] = (int) servers_check_status (); - $servers["down"] = $servers["all"] - $servers["up"]; - if ($servers["up"] == 0) { - //All Servers down or no servers at all - $servers_check_img = html_print_image("images/header_down.png", true, array("alt" => 'cross', "class" => 'bot', 'title' => __('All systems').': '.__('Down'))); - } - elseif ($servers["down"] != 0) { - //Some servers down - $servers_check_img = html_print_image("images/header_warning.png", true, array("alt" => 'error', "class" => 'bot', 'title' => $servers["down"].' '.__('servers down'))); - } - else { - //All servers up - $servers_check_img = html_print_image("images/header_ready.png", true, array("alt" => 'ok', "class" => 'bot', 'title' => __('All systems').': '.__('Ready'))); - } - unset ($servers); // Since this is the header, we don't like to trickle down variables. - - $servers_link_open = ''; - $servers_link_close = ''; - - if ($config['show_qr_code_header'] == 0){ - $show_qr_code_header = 'display: none;'; - } - else { - $show_qr_code_header = 'display: inline;'; - } - - $table->data[0]['qr'] = - ''; - - echo ""; - ?> - - data[0]['clippy'] = - '' . - html_print_image( - "images/clippy_icon.png", - true, - array("id" => 'clippy', - "class" => 'clippy', - "alt" => __('%s assistant', get_product_name()), - 'title' => __('%s assistant', get_product_name()))) . - ''; - } - - - $table->data[0][0] = $servers_link_open . - $servers_check_img . $servers_link_close; - - - - - //======= Autorefresh code ============================= - $autorefresh_txt = ''; - $autorefresh_additional = ''; - - $ignored_params = array ('agent_config' => false, 'code' => false); - - if (!isset($_GET['sec2'])) { - $_GET['sec2'] = ''; - } - if (!isset($_GET['refr'])) { - $_GET['refr'] = null; - } - - $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '" . $config['id_user'] . "'"); - $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); - - if ($autorefresh_list !== null && array_search($_GET['sec2'], $autorefresh_list) !== false) { - $do_refresh = true; - if ($_GET['sec2'] == 'operation/agentes/pandora_networkmap') { - if ((!isset($_GET['tab'])) || ($_GET['tab'] != 'view')) { - $do_refresh = false; - } - } - if ($do_refresh) { - $autorefresh_img = html_print_image("images/header_refresh.png", true, array("class" => 'bot', "alt" => 'lightning', 'title' => __('Configure autorefresh'))); - - if ($_GET['refr']) { - $autorefresh_txt .= ' ('.date ("i:s", $config["refr"]).')'; - } - - $ignored_params['refr'] = ''; - $values = get_refresh_time_array(); - $autorefresh_additional = ''; - unset ($values); - - $autorefresh_link_open_img = - ''; - - if ($_GET['refr']) { - $autorefresh_link_open_txt = - ''; - } - else { - $autorefresh_link_open_txt = ''; - } - - $autorefresh_link_close = ''; - } - else { - $autorefresh_img = html_print_image("images/header_refresh_disabled.png", true, array("class" => 'bot autorefresh_disabled', "alt" => 'lightning', 'title' => __('Disabled autorefresh'))); - - $ignored_params['refr'] = false; - - $autorefresh_link_open_img = ''; - $autorefresh_link_open_txt = ''; - $autorefresh_link_close = ''; - } - } - else { - $autorefresh_img = html_print_image("images/header_refresh_disabled.png", true, array("class" => 'bot autorefresh_disabled', "alt" => 'lightning', 'title' => __('Disabled autorefresh'))); - - $ignored_params['refr'] = false; - - $autorefresh_link_open_img = ''; - $autorefresh_link_open_txt = ''; - $autorefresh_link_close = ''; - } - - $table->data[0][1] = $autorefresh_link_open_img . $autorefresh_img . $autorefresh_link_close; - $table->data[0][2] = $autorefresh_link_open_txt . $autorefresh_txt . $autorefresh_link_close . $autorefresh_additional; - //====================================================== - - - $check_minor_release_available = false; - $pandora_management = check_acl($config['id_user'], 0, "PM"); - - $check_minor_release_available = db_check_minor_relase_available (); - - if ($check_minor_release_available) { - if (users_is_admin($config['id_user'])) { - - if($config['language'] == 'es'){ - set_pandora_error_for_header('Hay una o mas revisiones menores en espera para ser actualizadas. '.__('Sobre actualización de revisión menor').'', 'Revisión/es menor/es disponible/s'); - } - else{ - set_pandora_error_for_header('There are one or more minor releases waiting for update. '.__('About minor release update').'', 'minor release/s available'); - } - } - } - echo ''; + // $search_bar .= 'onClick="javascript: document.quicksearch.submit()"'; + $search_bar .= ""; + $search_bar .= ''; - if ($config["alert_cnt"] > 0) { - $maintenance_link = 'javascript:'; - $maintenance_title = __("System alerts detected - Please fix as soon as possible"); - $maintenance_class = $maintenance_id = 'show_systemalert_dialog white'; - - $maintenance_link_open_txt = - ''; - $maintenance_link_open_img = - ''; - $maintenance_link_close = ''; - if (!$pandora_management) { - $maintenance_img = ''; - } - else { - $maintenance_img = $maintenance_link_open_img . - html_print_image("images/header_yellow.png", - true, array( - "title" => __('You have %d warning(s)', - $config["alert_cnt"]), - "id" => "yougotalert", - "class" => "bot")) . $maintenance_link_close; - } - } - else { - if (!$pandora_management) { - $maintenance_img = ''; - } - else { - $maintenance_img = html_print_image ("images/header_ready.png", true, array ("title" => __('There are not warnings'), "id" => "yougotalert", "class" => "bot")); - } - } - - $table->data[0][3] = $maintenance_img; - - // Main help icon - if (!$config['disable_help']) { - $table->data[0][4] = - '' . - html_print_image("images/header_help.png", true, array( - "title" => __('Main help'), - "id" => "helpmodal", - "class" => "modalpopup")) . - ''; - } - - // Logout - $table->data[0][5] = ''; - $table->data[0][5] .= html_print_image("images/header_logout.png", true, array("alt" => __('Logout'), "class" => 'bot', "title" => __('Logout'))); - $table->data[0][5] .= ''; - - // User - if (is_user_admin ($config["id_user"]) == 1) - $table->data[0][6] = html_print_image("images/header_user_admin.png" , true, array("title" => __('Edit my user'), "class" => 'bot', "alt" => 'user')); - else - $table->data[0][6] = html_print_image("images/header_user.png" , true, array("title" => __('Edit my user'), "class" => 'bot', "alt" => 'user')); - - $table->data[0][6] = '' . $table->data[0][6] . ''; - - $table->data[0][7] = ' (' . $config["id_user"] . ')'; - - // Chat messages - $table->data[0][8] = ""; - - // Messages - $msg_cnt = messages_get_count ($config["id_user"]); - if ($msg_cnt > 0) { - echo ''; - - $table->data[0][9] = ''; - $table->data[0][9] .= html_print_image ("images/header_email.png", true, array ("title" => __('You have %d unread message(s)', $msg_cnt), "id" => "yougotmail", "class" => "bot", 'style' => 'width:24px;')); - $table->data[0][9] .= ''; - } + $table->data[0]['searchbar'] = $search_bar; + } - $table->data[0]['notifications'] = notifications_print_ball(); + // Servers check + $servers = []; + $servers['all'] = (int) db_get_value('COUNT(id_server)', 'tserver'); + $servers['up'] = (int) servers_check_status(); + $servers['down'] = ($servers['all'] - $servers['up']); + if ($servers['up'] == 0) { + // All Servers down or no servers at all + $servers_check_img = html_print_image('images/header_down.png', true, ['alt' => 'cross', 'class' => 'bot', 'title' => __('All systems').': '.__('Down')]); + } else if ($servers['down'] != 0) { + // Some servers down + $servers_check_img = html_print_image('images/header_warning.png', true, ['alt' => 'error', 'class' => 'bot', 'title' => $servers['down'].' '.__('servers down')]); + } else { + // All servers up + $servers_check_img = html_print_image('images/header_ready.png', true, ['alt' => 'ok', 'class' => 'bot', 'title' => __('All systems').': '.__('Ready')]); + } - html_print_table($table); - - unset($table); - ?> - - - + unset($servers); + // Since this is the header, we don't like to trickle down variables. + $servers_link_open = ''; + $servers_link_close = ''; + + if ($config['show_qr_code_header'] == 0) { + $show_qr_code_header = 'display: none;'; + } else { + $show_qr_code_header = 'display: inline;'; + } + + $table->data[0]['qr'] = ''; + + echo "'; + ?> + + data[0]['clippy'] = ''.html_print_image( + 'images/clippy_icon.png', + true, + [ + 'id' => 'clippy', + 'class' => 'clippy', + 'alt' => __('%s assistant', get_product_name()), + 'title' => __( + '%s assistant', + get_product_name() + ), + ] + ).''; + } + + + $table->data[0][0] = $servers_link_open.$servers_check_img.$servers_link_close; + + + + + // ======= Autorefresh code ============================= + $autorefresh_txt = ''; + $autorefresh_additional = ''; + + $ignored_params = [ + 'agent_config' => false, + 'code' => false, + ]; + + if (!isset($_GET['sec2'])) { + $_GET['sec2'] = ''; + } + + if (!isset($_GET['refr'])) { + $_GET['refr'] = null; + } + + $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '".$config['id_user']."'"); + $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); + + if ($autorefresh_list !== null && array_search($_GET['sec2'], $autorefresh_list) !== false) { + $do_refresh = true; + if ($_GET['sec2'] == 'operation/agentes/pandora_networkmap') { + if ((!isset($_GET['tab'])) || ($_GET['tab'] != 'view')) { + $do_refresh = false; + } + } + + if ($do_refresh) { + $autorefresh_img = html_print_image('images/header_refresh.png', true, ['class' => 'bot', 'alt' => 'lightning', 'title' => __('Configure autorefresh')]); + + if ($_GET['refr']) { + $autorefresh_txt .= ' ('.date('i:s', $config['refr']).')'; + } + + $ignored_params['refr'] = ''; + $values = get_refresh_time_array(); + $autorefresh_additional = ''; + unset($values); + + $autorefresh_link_open_img = ''; + + if ($_GET['refr']) { + $autorefresh_link_open_txt = ''; + } else { + $autorefresh_link_open_txt = ''; + } + + $autorefresh_link_close = ''; + } else { + $autorefresh_img = html_print_image('images/header_refresh_disabled.png', true, ['class' => 'bot autorefresh_disabled', 'alt' => 'lightning', 'title' => __('Disabled autorefresh')]); + + $ignored_params['refr'] = false; + + $autorefresh_link_open_img = ''; + $autorefresh_link_open_txt = ''; + $autorefresh_link_close = ''; + } + } else { + $autorefresh_img = html_print_image('images/header_refresh_disabled.png', true, ['class' => 'bot autorefresh_disabled', 'alt' => 'lightning', 'title' => __('Disabled autorefresh')]); + + $ignored_params['refr'] = false; + + $autorefresh_link_open_img = ''; + $autorefresh_link_open_txt = ''; + $autorefresh_link_close = ''; + } + + $table->data[0][1] = $autorefresh_link_open_img.$autorefresh_img.$autorefresh_link_close; + $table->data[0][2] = $autorefresh_link_open_txt.$autorefresh_txt.$autorefresh_link_close.$autorefresh_additional; + // ====================================================== + $check_minor_release_available = false; + $pandora_management = check_acl($config['id_user'], 0, 'PM'); + + $check_minor_release_available = db_check_minor_relase_available(); + + if ($check_minor_release_available) { + if (users_is_admin($config['id_user'])) { + if ($config['language'] == 'es') { + set_pandora_error_for_header('Hay una o mas revisiones menores en espera para ser actualizadas. '.__('Sobre actualización de revisión menor').'', 'Revisión/es menor/es disponible/s'); + } else { + set_pandora_error_for_header('There are one or more minor releases waiting for update. '.__('About minor release update').'', 'minor release/s available'); + } + } + } + + echo ''; + + if ($config['alert_cnt'] > 0) { + $maintenance_link = 'javascript:'; + $maintenance_title = __('System alerts detected - Please fix as soon as possible'); + $maintenance_class = $maintenance_id = 'show_systemalert_dialog white'; + + $maintenance_link_open_txt = ''; + $maintenance_link_open_img = ''; + $maintenance_link_close = ''; + if (!$pandora_management) { + $maintenance_img = ''; + } else { + $maintenance_img = $maintenance_link_open_img.html_print_image( + 'images/header_yellow.png', + true, + [ + 'title' => __( + 'You have %d warning(s)', + $config['alert_cnt'] + ), + 'id' => 'yougotalert', + 'class' => 'bot', + ] + ).$maintenance_link_close; + } + } else { + if (!$pandora_management) { + $maintenance_img = ''; + } else { + $maintenance_img = html_print_image('images/header_ready.png', true, ['title' => __('There are not warnings'), 'id' => 'yougotalert', 'class' => 'bot']); + } + } + + $table->data[0][3] = $maintenance_img; + + // Main help icon + if (!$config['disable_help']) { + $table->data[0][4] = ''.html_print_image( + 'images/header_help.png', + true, + [ + 'title' => __('Main help'), + 'id' => 'helpmodal', + 'class' => 'modalpopup', + ] + ).''; + } + + $table->data[0]['notifications'] = notifications_print_ball(); + + // Logout + $table->data[0][5] = ''; + $table->data[0][5] .= html_print_image('images/header_logout.png', true, ['alt' => __('Logout'), 'class' => 'bot', 'title' => __('Logout')]); + $table->data[0][5] .= ''; + + // User + if (is_user_admin($config['id_user']) == 1) { + $table->data[0][6] = html_print_image('images/header_user_admin.png', true, ['title' => __('Edit my user'), 'class' => 'bot', 'alt' => 'user']); + } else { + $table->data[0][6] = html_print_image('images/header_user.png', true, ['title' => __('Edit my user'), 'class' => 'bot', 'alt' => 'user']); + } + + $table->data[0][6] = ''.$table->data[0][6].''; + + $table->data[0][7] = ' ('.$config['id_user'].')'; + + // Chat messages + $table->data[0][8] = "'; + + // Messages + $msg_cnt = messages_get_count($config['id_user']); + if ($msg_cnt > 0) { + echo ''; + + $table->data[0][9] = ''; + $table->data[0][9] .= html_print_image('images/header_email.png', true, ['title' => __('You have %d unread message(s)', $msg_cnt), 'id' => 'yougotmail', 'class' => 'bot', 'style' => 'width:24px;']); + $table->data[0][9] .= ''; + } + + html_print_table($table); + + unset($table); + ?> + + + + + 0 as "read" FROM tmensajes tm + SELECT tm.*, utimestamp_read > 0 as "read" %s FROM tmensajes tm LEFT JOIN tnotification_user nu ON tm.id_mensaje=nu.id_mensaje LEFT JOIN (tnotification_group ng INNER JOIN tusuario_perfil up ON ng.id_group=up.id_grupo AND up.id_grupo=ng.id_group - ) ON tm.id_mensaje=ng.id_mensaje + ) ON tm.id_mensaje=ng.id_mensaje + %s WHERE utimestamp_erased is null AND (up.id_usuario="%s" OR nu.id_user="%s" OR ng.id_group=0) ) t %s ORDER BY %s', + $source_fields, + $source_join, $config['id_user'], $config['id_user'], $read, diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 7f82908aab..ad3e8953ad 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -523,6 +523,11 @@ function notifications_set_user_label_status($source, $user, $label, $value) } +// ///////////////////////////////////////////////////////////////////////////// +// UI FUNCTIONS +// ///////////////////////////////////////////////////////////////////////////// + + /** * Print the notification ball to see unread messages. * @@ -533,7 +538,11 @@ function notifications_print_ball() $num_notifications = messages_get_count(); $class_status = ($num_notifications == 0) ? 'notification-ball-no-messages' : 'notification-ball-new-messages'; return sprintf( - '
+ '
%s
', $class_status, @@ -807,3 +816,58 @@ function notifications_print_user_switch($source, $user, $label) ] ); } + + +/** + * Generates the dropdown notifications menu. + * + * @return string HTML with dropdown menu. + */ +function notifications_print_dropdown() +{ + $mess = messages_get_overview('status', 'DESC', false, true); + if ($mess === false) { + $mess = []; + } + + return sprintf( + "", + array_reduce( + $mess, + function ($carry, $message) { + return $carry.notifications_print_dropdown_element($message); + }, + '' + ) + ); +} + + +/** + * Print a single notification box + * + * @param array $message_info Info of printed message. + * + * @return string HTML code of single message + */ +function notifications_print_dropdown_element($message_info) +{ + return sprintf( + "
+ +
+

+ %s +

+

+ %s +

+
+
", + html_print_image('images/'.$message_info['icon'], true), + $message_info['description'], + $message_info['mensaje'] + ); +} diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index cc6545fc87..00ac3161fb 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4929,6 +4929,59 @@ div#dialog_messages table th:last-child { background-color: #fc4444; } +.notification-wrapper { + background: white; + border: #a5a5a5 solid 1px; + z-index: 900000; + position: absolute; + width: 400px; + margin-top: -5px; +} +.notification-wrapper::before { + content: ""; + display: block; + position: absolute; + width: 0px; + height: 0; + border-color: transparent; + border-width: 12px; + border-style: solid; + bottom: 100%; + left: 78%; + left: calc(78% - 2px); + margin-left: -12px; + border-bottom-color: white; +} +.notification-item { + background: whitesmoke; + height: 100px; + margin: 7px; + border: #cccccc solid 1px; + display: flex; + flex-flow: row nowrap; + align-items: center; +} +.notification-item > * { + padding-left: 15px; +} + +.notification-info { + width: 87%; + display: flex; + flex-flow: column nowrap; +} +.notification-item img { + max-width: 100%; + max-height: 100%; +} +.notification-title { + margin: 0; +} +.notification-subtitle { + margin: 0; + color: #373737; +} + .global-config-notification-title { display: flex; flex-direction: row; From a3a1bbb778904923de620079009100e1e389a0bd Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 8 Feb 2019 17:30:13 +0100 Subject: [PATCH 071/249] added missed new field extended_info for events Former-commit-id: 8edb7cb854364259ffca27585e423464d213137a --- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 ++ pandora_console/pandoradb.sql | 1 + 2 files changed, 3 insertions(+) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index f1d1d4dd23..d02beda560 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1856,6 +1856,8 @@ ALTER TABLE `tevento` ADD COLUMN `data` double(22,5) default NULL; ALTER TABLE `tevento` ADD COLUMN `module_status` int(4) NOT NULL default '0'; +ALTER TABLE `tevento` ADD COLUMN `extended_info` tinyint(1) NOT NULL default '0'; + -- --------------------------------------------------------------------- -- Table `tevent_extended` -- --------------------------------------------------------------------- diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index 874f8b0bb6..b596dd4411 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -644,6 +644,7 @@ CREATE TABLE IF NOT EXISTS `tevento` ( `custom_data` TEXT NOT NULL, `data` double(22,5) default NULL, `module_status` int(4) NOT NULL default '0', + `extended_info` tinyint(1) NOT NULL default '0' PRIMARY KEY (`id_evento`), KEY `idx_agente` (`id_agente`), KEY `idx_agentmodule` (`id_agentmodule`), From 091f6ace96302cf25688d69845733cbaeb8cf42d Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 8 Feb 2019 17:30:47 +0100 Subject: [PATCH 072/249] minor fixes and revised code style Former-commit-id: aad587c578de99432dd759d6c82b622f6cd6c6e7 --- pandora_console/include/ajax/events.php | 130 +- pandora_console/include/functions_events.php | 1765 +++++++++++------- 2 files changed, 1207 insertions(+), 688 deletions(-) diff --git a/pandora_console/include/ajax/events.php b/pandora_console/include/ajax/events.php index 5f6f62568b..77930e3e50 100644 --- a/pandora_console/include/ajax/events.php +++ b/pandora_console/include/ajax/events.php @@ -1,16 +1,31 @@ > '; switch ($event_response['type']) { case 'command': - - if ($massive) { echo "
"; - echo $prompt.sprintf("(Event #$event_id) ".__('Executing command: %s', $command)); + echo $prompt.sprintf( + '(Event #'.$event_id.') '.__( + 'Executing command: %s', + $command + ) + ); echo '

'; echo "'; @@ -242,7 +260,11 @@ if ($dialogue_event_response) { case 'url': $command = str_replace('localhost', $_SERVER['SERVER_NAME'], $command); - echo ""; + echo ""; + break; + + default: + // Ignore. break; } } @@ -319,10 +341,10 @@ if ($get_extended_event) { $readonly = true; } - // Clean url from events and store in array + // Clean url from events and store in array. $event['clean_tags'] = events_clean_tags($event['tags']); - // If the event is not found, we abort + // If the event is not found, we abort. if (empty($event)) { ui_print_error_message('Event not found'); return false; @@ -341,34 +363,38 @@ if ($get_extended_event) { $event['timestamp_last'] = $timestamp_last; $event['event_rep'] = $event_rep; - // Check ACLs + // Check ACLs. if (is_user_admin($config['id_user'])) { - // Do nothing if you're admin, you get full access + // Do nothing if you're admin, you get full access. + $__ignored_line = 0; } else if ($config['id_user'] == $event['owner_user']) { - // Do nothing if you're the owner user, you get access + // Do nothing if you're the owner user, you get access. + $__ignored_line = 0; } else if ($event['id_grupo'] == 0) { - // If the event has access to all groups, you get access + // If the event has access to all groups, you get access. + $__ignored_line = 0; } else { - // Get your groups + // Get your groups. $groups = users_get_groups($config['id_user'], 'ER'); if (in_array($event['id_grupo'], array_keys($groups))) { - // If the event group is among the groups of the user, you get access + // If event group is among the groups of the user, you get access. + $__ignored_line = 0; } else { - // If all the access types fail, abort + // If all the access types fail, abort. echo 'Access denied'; return false; } } - // Print group_rep in a hidden field to recover it from javascript + // Print group_rep in a hidden field to recover it from javascript. html_print_input_hidden('group_rep', (int) $group_rep); if ($event === false) { return; } - // Tabs + // Tabs. $tabs = "'; - // Get criticity image + // Get criticity image. switch ($event['criticity']) { default: case 0: @@ -419,7 +457,19 @@ if ($get_extended_event) { } if (!$readonly - && ((tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids)) || (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EW', $event['clean_tags'], $childrens_ids))) + && ((tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EM', + $event['clean_tags'], + $childrens_ids + )) || (tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EW', + $event['clean_tags'], + $childrens_ids + ))) ) { $responses = events_page_responses($event, $childrens_ids); } else { @@ -427,7 +477,7 @@ if ($get_extended_event) { } $console_url = ''; - // If metaconsole switch to node to get details and custom fields + // If metaconsole switch to node to get details and custom fields. if ($meta) { $server = metaconsole_get_connection_by_id($server_id); metaconsole_connect($server); @@ -437,7 +487,8 @@ if ($get_extended_event) { $details = events_page_details($event, $server); - // Juanma (09/05/2014) Fix: Needs to reconnect to node, in previous funct node connection was lost + // Juanma (09/05/2014) Fix: Needs to reconnect to node, in previous funct + // node connection was lost. if ($meta) { $server = metaconsole_get_connection_by_id($server_id); metaconsole_connect($server); @@ -472,7 +523,7 @@ if ($get_extended_event) { }); '; - // Load the required tab + // Load the required tab. switch ($dialog_page) { case 'general': $js .= '$tabs.tabs( "option", "active", 0);'; @@ -497,6 +548,10 @@ if ($get_extended_event) { case 'custom_data': $js .= '$tabs.tabs( "option", "active", 5);'; break; + + default: + // Ignore. + break; } $js .= ' @@ -543,6 +598,10 @@ if ($get_events_details) { $img = ui_get_full_url('images/hourglass.png', false, false, false); $title = __('Event in process'); break; + + default: + // Ignore. + break; } $out .= ''; @@ -594,7 +653,8 @@ if ($table_events) { $id_agente = (int) get_parameter('id_agente', 0); $all_events_24h = (int) get_parameter('all_events_24h', 0); - // Fix: for tag functionality groups have to be all user_groups (propagate ACL funct!) + // Fix: for tag functionality groups have to be all user_groups + // (propagate ACL funct!). $groups = users_get_groups($config['id_user']); $tags_condition = tags_get_acl_tags( @@ -612,7 +672,7 @@ if ($table_events) { if ($all_events_24h) { events_print_event_table( - "utimestamp > $date_subtract_day", + 'utimestamp > '.$date_subtract_day, 200, '100%', false, @@ -621,7 +681,7 @@ if ($table_events) { ); } else { events_print_event_table( - "estado <> 1 $tags_condition", + 'estado <> 1 '.$tags_condition, 200, '100%', false, diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php index f3f3d2b0fa..8ff58d8d8b 100644 --- a/pandora_console/include/functions_events.php +++ b/pandora_console/include/functions_events.php @@ -1,17 +1,32 @@ - * Both are similars: - * db_get_all_rows_filter ('table', array ('disabled', 0)); - * db_get_all_rows_filter ('table', 'disabled = 0'); + * @param mixed $filter Filters elements. It can be an indexed array + * (keys would be the field name and value the expected + * value, and would be joined with an AND operator) or a + * string, including any SQL clause (without the WHERE + * keyword). Example: + * + * Both are similars: + * db_get_all_rows_filter ('table', ['disabled', 0]); + * db_get_all_rows_filter ('table', 'disabled = 0'); + * Both are similars: + * db_get_all_rows_filter ( + * 'table', + * [ + * 'disabled' => 0, + * 'history_data' => 0 + * ], + * 'name', + * 'OR' + * ); + * db_get_all_rows_filter ( + * 'table', + * 'disabled = 0 OR history_data = 0', 'name' + * ); + * . + * @param mixed $fields Fields of the table to retrieve. Can be an array or a + * coma separated string. All fields are retrieved by + * default. * - * Both are similars: - * db_get_all_rows_filter ('table', array ('disabled' => 0, 'history_data' => 0), 'name', 'OR'); - * db_get_all_rows_filter ('table', 'disabled = 0 OR history_data = 0', 'name'); - * - * @param mixed Fields of the table to retrieve. Can be an array or a coma - * separated string. All fields are retrieved by default - * - * @return mixed False in case of error or invalid values passed. Affected rows otherwise + * @return mixed False in case of error or invalid values passed. + * Affected rows otherwise */ function events_get_events($filter=false, $fields=false) { @@ -93,10 +120,13 @@ function events_get_events($filter=false, $fields=false) /** * Get the event with the id pass as parameter. * - * @param integer $id Event id - * @param mixed $fields The fields to show or by default all with false. + * @param integer $id Event id. + * @param mixed $fields The fields to show or by default all with false. + * @param boolean $meta Metaconsole environment or not. + * @param boolean $history Retrieve also historical data. * - * @return mixed False in case of error or invalid values passed. Event row otherwise + * @return mixed False in case of error or invalid values passed. + * Event row otherwise. */ function events_get_event($id, $fields=false, $meta=false, $history=false) { @@ -123,6 +153,20 @@ function events_get_event($id, $fields=false, $meta=false, $history=false) } +/** + * Retrieve all events ungrouped. + * + * @param string $sql_post Sql_post. + * @param integer $offset Offset. + * @param integer $pagination Pagination. + * @param boolean $meta Meta. + * @param boolean $history History. + * @param boolean $total Total. + * @param boolean $history_db History_db. + * @param string $order Order. + * + * @return mixed Array of events or false. + */ function events_get_events_no_grouped( $sql_post, $offset=0, @@ -137,7 +181,7 @@ function events_get_events_no_grouped( $table = events_get_events_table($meta, $history); - $sql = "SELECT * FROM $table te WHERE 1=1 ".$sql_post; + $sql = 'SELECT * FROM '.$table.' te WHERE 1=1 '.$sql_post; $events = db_get_all_rows_sql($sql, $history_db); @@ -145,6 +189,21 @@ function events_get_events_no_grouped( } +/** + * Return all events matching sql_post grouped. + * + * @param [type] $sql_post Sql_post. + * @param integer $offset Offset. + * @param integer $pagination Pagination. + * @param boolean $meta Meta. + * @param boolean $history History. + * @param boolean $total Total. + * @param boolean $history_db History_db. + * @param string $order Order. + * @param string $sort_field Sort_field. + * + * @return mixed Array of events or false. + */ function events_get_events_grouped( $sql_post, $offset=0, @@ -166,101 +225,39 @@ function events_get_events_grouped( $groupby_extra = ''; } - switch ($config['dbtype']) { - case 'mysql': - db_process_sql('SET group_concat_max_len = 9999999'); - $event_lj = events_get_secondary_groups_left_join($table); - if ($total) { - $sql = "SELECT COUNT(*) FROM (SELECT * - FROM $table te $event_lj - WHERE 1=1 ".$sql_post.' - GROUP BY estado, evento, id_agente, id_agentmodule'.$groupby_extra.') AS t'; - } else { - $sql = "SELECT *, MAX(id_evento) AS id_evento, - GROUP_CONCAT(DISTINCT user_comment SEPARATOR '
') AS user_comment, - GROUP_CONCAT(DISTINCT id_evento SEPARATOR ',') AS similar_ids, - COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep, - MIN(utimestamp) AS timestamp_rep_min, - (SELECT owner_user FROM $table WHERE id_evento = MAX(te.id_evento)) owner_user, - (SELECT id_usuario FROM $table WHERE id_evento = MAX(te.id_evento)) id_usuario, - (SELECT id_agente FROM $table WHERE id_evento = MAX(te.id_evento)) id_agente, - (SELECT criticity FROM $table WHERE id_evento = MAX(te.id_evento)) AS criticity, - (SELECT ack_utimestamp FROM $table WHERE id_evento = MAX(te.id_evento)) AS ack_utimestamp, - (SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = te.id_agentmodule) AS module_name - FROM $table te $event_lj - WHERE 1=1 ".$sql_post.' - GROUP BY estado, evento, id_agente, id_agentmodule'.$groupby_extra; - $sql .= ' '.events_get_sql_order($sort_field, $order, 2); - $sql .= ' LIMIT '.$offset.','.$pagination; - } - break; - - case 'postgresql': - if ($total) { - $sql = "SELECT COUNT(*) - FROM $table te - WHERE 1=1 ".$sql_post.' - GROUP BY estado, evento, id_agentmodule, id_evento, id_agente, id_usuario, id_grupo, estado, timestamp, utimestamp, event_type, id_alert_am, criticity, user_comment, tags, source, id_extra'.$groupby_extra; - } else { - $sql = "SELECT *, MAX(id_evento) AS id_evento, array_to_string(array_agg(DISTINCT user_comment), '
') AS user_comment, - array_to_string(array_agg(DISTINCT id_evento), ',') AS similar_ids, - COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep, - MIN(utimestamp) AS timestamp_rep_min, - (SELECT owner_user FROM $table WHERE id_evento = MAX(te.id_evento)) owner_user, - (SELECT id_usuario FROM $table WHERE id_evento = MAX(te.id_evento)) id_usuario, - (SELECT id_agente FROM $table WHERE id_evento = MAX(te.id_evento)) id_agente, - (SELECT criticity FROM $table WHERE id_evento = MAX(te.id_evento)) AS criticity, - (SELECT ack_utimestamp FROM $table WHERE id_evento = MAX(te.id_evento)) AS ack_utimestamp - FROM $table te - WHERE 1=1 ".$sql_post.' - GROUP BY estado, evento, id_agentmodule, id_evento, - id_agente, id_usuario, id_grupo, estado, - timestamp, utimestamp, event_type, id_alert_am, - criticity, user_comment, tags, source, id_extra, - te.critical_instructions, - te.warning_instructions, - te.unknown_instructions, - te.owner_user, - te.ack_utimestamp, - te.custom_data '.$groupby_extra.' - ORDER BY timestamp_rep ASC LIMIT '.$pagination.' OFFSET '.$offset; - } - break; - - case 'oracle': - if ($total) { - $sql = "SELECT COUNT(*) - FROM $table te - WHERE 1=1 $sql_post - GROUP BY estado, to_char(evento), id_agentmodule".$groupby_extra.') b '; - } else { - $set = []; - $set['limit'] = $pagination; - $set['offset'] = $offset; - - $sql = "SELECT ta.*, tb.event_rep, tb.timestamp_rep, tb.timestamp_rep_min, tb.user_comments, tb.similar_ids - FROM $table ta - INNER JOIN (SELECT MAX(id_evento) AS id_evento, COUNT(id_evento) AS event_rep, - MAX(utimestamp) AS timestamp_rep, MIN(utimestamp) AS timestamp_rep_min, - TAB_TO_STRING(CAST(COLLECT(TO_CHAR(user_comment) ORDER BY id_evento ASC) AS t_varchar2_tab), '
') AS user_comments, - TAB_TO_STRING(CAST(COLLECT(CAST(id_evento AS VARCHAR2(4000)) ORDER BY id_evento ASC) AS t_varchar2_tab)) AS similar_ids - FROM $table te - WHERE 1=1 $sql_post - GROUP BY estado, to_char(evento), id_agentmodule$groupby_extra) tb - ON ta.id_evento = tb.id_evento - ORDER BY tb.timestamp_rep ASC"; - $sql = oracle_recode_query($sql, $set); - } - break; + db_process_sql('SET group_concat_max_len = 9999999'); + $event_lj = events_get_secondary_groups_left_join($table); + if ($total) { + $sql = 'SELECT COUNT(*) FROM (SELECT * + FROM '.$table.' te '.$event_lj.' + WHERE 1=1 '.$sql_post.' + GROUP BY estado, evento, id_agente, id_agentmodule'.$groupby_extra.') AS t'; + } else { + $sql = "SELECT *, MAX(id_evento) AS id_evento, + GROUP_CONCAT(DISTINCT user_comment SEPARATOR '
') AS user_comment, + GROUP_CONCAT(DISTINCT id_evento SEPARATOR ',') AS similar_ids, + COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep, + MIN(utimestamp) AS timestamp_rep_min, + (SELECT owner_user FROM ".$table.' WHERE id_evento = MAX(te.id_evento)) owner_user, + (SELECT id_usuario FROM '.$table.' WHERE id_evento = MAX(te.id_evento)) id_usuario, + (SELECT id_agente FROM '.$table.' WHERE id_evento = MAX(te.id_evento)) id_agente, + (SELECT criticity FROM '.$table.' WHERE id_evento = MAX(te.id_evento)) AS criticity, + (SELECT ack_utimestamp FROM '.$table.' WHERE id_evento = MAX(te.id_evento)) AS ack_utimestamp, + (SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = te.id_agentmodule) AS module_name + FROM '.$table.' te '.$event_lj.' + WHERE 1=1 '.$sql_post.' + GROUP BY estado, evento, id_agente, id_agentmodule'.$groupby_extra; + $sql .= ' '.events_get_sql_order($sort_field, $order, 2); + $sql .= ' LIMIT '.$offset.','.$pagination; } - // Extract the events by filter (or not) from db + // Extract the events by filter (or not) from db. $events = db_get_all_rows_sql($sql, $history_db); if ($total) { return reset($events[0]); } else { - // Override the column 'user_comment' with the column 'user_comments' when oracle + // Override the column 'user_comment' with the column 'user_comments' when oracle. if (!empty($events) && $config['dbtype'] == 'oracle') { array_walk( $events, @@ -275,6 +272,15 @@ function events_get_events_grouped( } +/** + * Return count of events grouped. + * + * @param string $sql_post Sql_post. + * @param boolean $meta Meta. + * @param boolean $history History. + * + * @return integer Number of events or false if failed. + */ function events_get_total_events_grouped($sql_post, $meta=false, $history=false) { return events_get_events_grouped($sql_post, 0, 0, $meta, $history, true); @@ -287,9 +293,9 @@ function events_get_total_events_grouped($sql_post, $meta=false, $history=false) * An event is similar then the event text (evento) and the id_agentmodule are * the same. * - * @param int Event id to get similar events. - * @param bool Metaconsole mode flag - * @param bool History mode flag + * @param integer $id Event id to get similar events. + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. * * @return array A list of events ids. */ @@ -299,7 +305,14 @@ function events_get_similar_ids($id, $meta=false, $history=false) $ids = []; if ($meta) { - $event = events_meta_get_event($id, ['evento', 'id_agentmodule'], $history); + $event = events_meta_get_event( + $id, + [ + 'evento', + 'id_agentmodule', + ], + $history + ); } else { $event = events_get_event($id, ['evento', 'id_agentmodule']); } @@ -331,26 +344,33 @@ function events_get_similar_ids($id, $meta=false, $history=false) /** * Delete events in a transresponse * - * @param mixed Event ID or array of events - * @param bool Whether to delete similar events too. - * @param bool Metaconsole mode flag - * @param bool History mode flag + * @param mixed $id_event Event ID or array of events. + * @param boolean $similar Whether to delete similar events too. + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. * * @return boolean Whether or not it was successful */ -function events_delete_event($id_event, $similar=true, $meta=false, $history=false) -{ +function events_delete_event( + $id_event, + $similar=true, + $meta=false, + $history=false +) { global $config; $table_event = events_get_events_table($meta, $history); - // Cleans up the selection for all unwanted values also casts any single values as an array + // Cleans up the selection for all unwanted values also casts any single values as an array. $id_event = (array) safe_int($id_event, 1); - // We must delete all events like the selected + // We must delete all events like the selected. if ($similar) { foreach ($id_event as $id) { - $id_event = array_merge($id_event, events_get_similar_ids($id, $meta, $history)); + $id_event = array_merge( + $id_event, + events_get_similar_ids($id, $meta, $history) + ); } $id_event = array_unique($id_event); @@ -366,7 +386,7 @@ function events_delete_event($id_event, $similar=true, $meta=false, $history=fal } if (check_acl($config['id_user'], $event_group, 'EM') == 0) { - // Check ACL + // Check ACL. db_pandora_audit('ACL Violation', 'Attempted deleting event #'.$event); $errors++; } else { @@ -376,7 +396,7 @@ function events_delete_event($id_event, $similar=true, $meta=false, $history=fal $errors++; } else { db_pandora_audit('Event deleted', 'Deleted event #'.$event); - // ACL didn't fail nor did return + // ACL didn't fail nor did return. continue; } } @@ -393,25 +413,29 @@ function events_delete_event($id_event, $similar=true, $meta=false, $history=fal /** - * Change the status of one or various events + * Change the status of one or multiple events. * - * @param mixed Event ID or array of events - * @param int new status of the event - * @param bool metaconsole mode flag - * @param bool history mode flag + * @param mixed $id_event Event ID or array of events. + * @param integer $new_status New status of the event. + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. * * @return boolean Whether or not it was successful */ -function events_change_status($id_event, $new_status, $meta=false, $history=false) -{ +function events_change_status( + $id_event, + $new_status, + $meta=false, + $history=false +) { global $config; $event_table = events_get_events_table($meta, $history); - // Cleans up the selection for all unwanted values also casts any single values as an array + // Cleans up the selection for all unwanted values also casts any single values as an array. $id_event = (array) safe_int($id_event, 1); - // Update ack info if the new status is validated + // Update ack info if the new status is validated. if ($new_status == EVENT_STATUS_VALIDATED) { $ack_utimestamp = time(); $ack_user = $config['id_user']; @@ -481,14 +505,20 @@ function events_change_status($id_event, $new_status, $meta=false, $history=fals return false; } - events_comment($id_event, '', "Change status to $status_string", $meta, $history); + events_comment( + $id_event, + '', + 'Change status to '.$status_string, + $meta, + $history + ); if ($meta && !empty($alerts)) { $server = metaconsole_get_connection_by_id($server_id); metaconsole_connect($server); } - // Put the alerts in standby or not depends the new status + // Put the alerts in standby or not depends the new status. foreach ($alerts as $alert) { switch ($new_status) { case EVENT_NEW: @@ -499,6 +529,10 @@ function events_change_status($id_event, $new_status, $meta=false, $history=fals case EVENT_PROCESS: alerts_agent_module_standby($alert, 1); break; + + default: + // Ignore. + break; } } @@ -511,23 +545,31 @@ function events_change_status($id_event, $new_status, $meta=false, $history=fals /** - * Change the owner of an event if the event hasn't owner + * Change the owner of an event if the event hasn't owner. * - * @param mixed Event ID or array of events - * @param string id_user of the new owner. If is false, the current owner will be setted - * @param bool flag to force the change or not (not force is change only when it hasn't owner) - * @param bool metaconsole mode flag - * @param bool history mode flag + * @param mixed $id_event Event ID or array of events. + * @param string $new_owner Id_user of the new owner. If is false, the current + * owner will be setted. + * @param boolean $force Flag to force the change or not (not force is + * change only when it hasn't owner). + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. * - * @return boolean Whether or not it was successful + * @return boolean Whether or not it was successful. */ -function events_change_owner($id_event, $new_owner=false, $force=false, $meta=false, $history=false) -{ +function events_change_owner( + $id_event, + $new_owner=false, + $force=false, + $meta=false, + $history=false +) { global $config; $event_table = events_get_events_table($meta, $history); - // Cleans up the selection for all unwanted values also casts any single values as an array + // Cleans up the selection for all unwanted values also casts any single + // values as an array. $id_event = (array) safe_int($id_event, 1); foreach ($id_event as $k => $id) { @@ -548,20 +590,27 @@ function events_change_owner($id_event, $new_owner=false, $force=false, $meta=fa } // If no new_owner is provided, the current user will be the owner - // ** Comment this lines because if possible selected None owner in owner event. TIQUET: #2250*** + // * #2250: Comment this lines because if possible selected None owner. // if (empty($new_owner)) { // $new_owner = $config['id_user']; // } - // Only generate comment when is forced (sometimes is changed the owner when comment) + // Only generate comment when is forced (sometimes is owner changes when + // comment). if ($force) { - events_comment($id_event, '', "Change owner to $new_owner", $meta, $history); + events_comment( + $id_event, + '', + 'Change owner to '.$new_owner, + $meta, + $history + ); } $values = ['owner_user' => $new_owner]; $where = ['id_evento' => $id_event]; - // If not force, add to where if owner_user = '' + // If not force, add to where if owner_user = ''. if (!$force) { $where['owner_user'] = ''; } @@ -582,6 +631,14 @@ function events_change_owner($id_event, $new_owner=false, $force=false, $meta=fa } +/** + * Returns proper event table based on environment. + * + * @param boolean $meta Metaconsole environment or not. + * @param boolean $history Historical data or not. + * + * @return string Table name. + */ function events_get_events_table($meta, $history) { if ($meta) { @@ -601,21 +658,30 @@ function events_get_events_table($meta, $history) /** * Comment events in a transresponse * - * @param mixed Event ID or array of events - * @param string comment to be registered - * @param string action performed with the comment. Bu default just Added comment - * @param bool Flag of metaconsole mode - * @param bool Flag of history mode + * @param mixed $id_event Event ID or array of events. + * @param string $comment Comment to be registered. + * @param string $action Action performed with comment. By default just add + * a comment. + * @param boolean $meta Flag of metaconsole mode. + * @param boolean $history Flag of history mode. + * @param boolean $similars Similars. * * @return boolean Whether or not it was successful */ -function events_comment($id_event, $comment='', $action='Added comment', $meta=false, $history=false, $similars=true) -{ +function events_comment( + $id_event, + $comment='', + $action='Added comment', + $meta=false, + $history=false, + $similars=true +) { global $config; $event_table = events_get_events_table($meta, $history); - // Cleans up the selection for all unwanted values also casts any single values as an array + // Cleans up the selection for all unwanted values also casts any single + // values as an array. $id_event = (array) safe_int($id_event, 1); foreach ($id_event as $k => $id) { @@ -636,25 +702,30 @@ function events_comment($id_event, $comment='', $action='Added comment', $meta=f return false; } - // If the event hasn't owner, assign the user as owner + // If the event hasn't owner, assign the user as owner. events_change_owner($id_event); - // Get the current event comments + // Get the current event comments. $first_event = $id_event; if (is_array($id_event)) { $first_event = reset($id_event); } - $event_comments = db_get_value('user_comment', $event_table, 'id_evento', $first_event); + $event_comments = db_get_value( + 'user_comment', + $event_table, + 'id_evento', + $first_event + ); $event_comments_array = []; if ($event_comments == '') { $comments_format = 'new'; } else { - // If comments are not stored in json, the format is old + // If comments are not stored in json, the format is old. $event_comments_array = json_decode($event_comments); - if (is_null($event_comments_array)) { + if (empty($event_comments_array)) { $comments_format = 'old'; } else { $comments_format = 'new'; @@ -672,12 +743,17 @@ function events_comment($id_event, $comment='', $action='Added comment', $meta=f $event_comments = io_json_mb_encode($event_comments_array); - // Update comment - $ret = db_process_sql_update($event_table, ['user_comment' => $event_comments], ['id_evento' => implode(',', $id_event)]); + // Update comment. + $ret = db_process_sql_update( + $event_table, + ['user_comment' => $event_comments], + ['id_evento' => implode(',', $id_event)] + ); break; case 'old': - // Give old ugly format to comment. TODO: Change this method for aux table or json + // Give old ugly format to comment. TODO: Change this method for + // aux table or json. $comment = str_replace(["\r\n", "\r", "\n"], '
', $comment); if ($comment != '') { @@ -686,30 +762,26 @@ function events_comment($id_event, $comment='', $action='Added comment', $meta=f $commentbox = ''; } - // Don't translate 'by' word because if various users with different languages - // make comments in the same console will be a mess - $comment = '-- '.$action.' by '.$config['id_user'].' '.'['.date($config['date_format']).'] --
'.$commentbox.'
'; + // Don't translate 'by' word because if multiple users with + // different languages make comments in the same console + // will be a mess. + $comment = '-- '.$action.' by '.$config['id_user'].' ['.date($config['date_format']).'] --
'.$commentbox.'
'; - // Update comment - switch ($config['dbtype']) { - // Oldstyle SQL to avoid innecesary PHP foreach - case 'mysql': - $sql_validation = "UPDATE $event_table - SET user_comment = concat('".$comment."', user_comment) - WHERE id_evento in (".implode(',', $id_event).')'; + // Update comment. + $sql_validation = sprintf( + 'UPDATE %s + SET user_comment = concat("%s", user_comment) + WHERE id_evento in (%s)', + $event_table, + $comment, + implode(',', $id_event) + ); - $ret = db_process_sql($sql_validation); - break; + $ret = db_process_sql($sql_validation); + break; - case 'postgresql': - case 'oracle': - $sql_validation = "UPDATE $event_table - SET user_comment='".$comment."' || user_comment) - WHERE id_evento in (".implode(',', $id_event).')'; - - $ret = db_process_sql($sql_validation); - break; - } + default: + // Ignore. break; } @@ -724,13 +796,18 @@ function events_comment($id_event, $comment='', $action='Added comment', $meta=f /** * Get group id of an event. * - * @param integer $id_event Event id + * @param integer $id_event Event id. * * @return integer Group id of the given event. */ function events_get_group($id_event) { - return (int) db_get_value('id_grupo', 'tevento', 'id_evento', (int) $id_event); + return (int) db_get_value( + 'id_grupo', + 'tevento', + 'id_evento', + (int) $id_event + ); } @@ -743,24 +820,37 @@ function events_get_group($id_event) */ function events_get_description($id_event) { - return (string) db_get_value('evento', 'tevento', 'id_evento', (int) $id_event); + return (string) db_get_value( + 'evento', + 'tevento', + 'id_evento', + (int) $id_event + ); } /** * Insert a event in the event log system. * - * @param integer $event - * @param integer $id_group - * @param integer $id_agent - * @param integer $status - * @param string $id_user - * @param string $event_type - * @param integer $priority - * @param integer $id_agent_module - * @param integer $id_aam + * @param integer $event Event. + * @param integer $id_group Id_group. + * @param integer $id_agent Id_agent. + * @param integer $status Status. + * @param string $id_user Id_user. + * @param string $event_type Event_type. + * @param integer $priority Priority. + * @param integer $id_agent_module Id_agent_module. + * @param integer $id_aam Id_aam. + * @param string $critical_instructions Critical_instructions. + * @param string $warning_instructions Warning_instructions. + * @param string $unknown_instructions Unknown_instructions. + * @param boolean $source Source. + * @param string $tags Tags. + * @param string $custom_data Custom_data. + * @param integer $server_id Server_id. + * @param string $id_extra Id_extra. * - * @return integer event id + * @return integer Event id. */ function events_create_event( $event, @@ -791,206 +881,64 @@ function events_create_event( if (defined('METACONSOLE')) { $table_events = 'tmetaconsole_event'; - switch ($config['dbtype']) { - case 'mysql': - $sql = sprintf( - ' - INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, - timestamp, estado, utimestamp, id_usuario, - event_type, criticity, id_agentmodule, id_alert_am, - critical_instructions, warning_instructions, - unknown_instructions, source, tags, custom_data, - server_id, id_extra, data, module_status) - VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()), - "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", - "%s", "%s", %d, "%s", %d, %d)', - $id_agent, - $id_group, - $event, - $status, - $id_user, - $event_type, - $priority, - $id_agent_module, - $id_aam, - $critical_instructions, - $warning_instructions, - $unknown_instructions, - $source, - $tags, - $custom_data, - $server_id, - $id_extra, - $data, - $module_status - ); - break; - - case 'postgresql': - $sql = sprintf( - ' - INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, - timestamp, estado, utimestamp, id_usuario, - event_type, criticity, id_agentmodule, id_alert_am, - critical_instructions, warning_instructions, - unknown_instructions, source, tags, custom_data, - server_id, id_extra, data, module_status) - VALUES (%d, %d, "%s", NOW(), %d, - ceil(date_part(\'epoch\', CURRENT_TIMESTAMP)), "%s", - "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", - "%s", %d, "%s", %d, %d)', - $id_agent, - $id_group, - $event, - $status, - $id_user, - $event_type, - $priority, - $id_agent_module, - $id_aam, - $critical_instructions, - $warning_instructions, - $unknown_instructions, - $source, - $tags, - $custom_data, - $server_id, - $id_extra, - $data, - $module_status - ); - break; - - case 'oracle': - $sql = sprintf( - ' - INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, - timestamp, estado, utimestamp, id_usuario, - event_type, criticity, id_agentmodule, id_alert_am, - critical_instructions, warning_instructions, - unknown_instructions, source, tags, custom_data, - server_id, id_extra, data, module_status) - VALUES (%d, %d, "%s", CURRENT_TIMESTAMP, %d, UNIX_TIMESTAMP, - "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", - "%s", "%s", %d, "%s", %d, %d)', - $id_agent, - $id_group, - $event, - $status, - $id_user, - $event_type, - $priority, - $id_agent_module, - $id_aam, - $critical_instructions, - $warning_instructions, - $unknown_instructions, - $source, - $tags, - $custom_data, - $server_id, - $id_extra, - $data, - $module_status - ); - break; - } + $sql = sprintf( + 'INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, + timestamp, estado, utimestamp, id_usuario, + event_type, criticity, id_agentmodule, id_alert_am, + critical_instructions, warning_instructions, + unknown_instructions, source, tags, custom_data, + server_id, id_extra, data, module_status) + VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()), + "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", + "%s", "%s", %d, "%s", %d, %d)', + $id_agent, + $id_group, + $event, + $status, + $id_user, + $event_type, + $priority, + $id_agent_module, + $id_aam, + $critical_instructions, + $warning_instructions, + $unknown_instructions, + $source, + $tags, + $custom_data, + $server_id, + $id_extra, + $data, + $module_status + ); } else { - switch ($config['dbtype']) { - case 'mysql': - $sql = sprintf( - ' - INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, - timestamp, estado, utimestamp, id_usuario, - event_type, criticity, id_agentmodule, id_alert_am, - critical_instructions, warning_instructions, - unknown_instructions, source, tags, custom_data, id_extra, data, module_status) - VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()), - "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s", %d, %d)', - $id_agent, - $id_group, - $event, - $status, - $id_user, - $event_type, - $priority, - $id_agent_module, - $id_aam, - $critical_instructions, - $warning_instructions, - $unknown_instructions, - $source, - $tags, - $custom_data, - $id_extra, - $data, - $module_status - ); - break; - - case 'postgresql': - $sql = sprintf( - ' - INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, - timestamp, estado, utimestamp, id_usuario, - event_type, criticity, id_agentmodule, id_alert_am, - critical_instructions, warning_instructions, - unknown_instructions, source, tags, custom_data, id_extra, data, module_status) - VALUES (%d, %d, "%s", NOW(), %d, - ceil(date_part(\'epoch\', CURRENT_TIMESTAMP)), "%s", - "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s", %d, %d)', - $id_agent, - $id_group, - $event, - $status, - $id_user, - $event_type, - $priority, - $id_agent_module, - $id_aam, - $critical_instructions, - $warning_instructions, - $unknown_instructions, - $source, - $tags, - $custom_data, - $id_extra, - $data, - $module_status - ); - break; - - case 'oracle': - $sql = sprintf( - ' - INSERT INTO '.$table_events." (id_agente, id_grupo, evento, - timestamp, estado, utimestamp, id_usuario, - event_type, criticity, id_agentmodule, id_alert_am, - critical_instructions, warning_instructions, - unknown_instructions, source, tags, custom_data, id_extra, data, module_status) - VALUES (%d, %d, '%s', CURRENT_TIMESTAMP, %d, UNIX_TIMESTAMP, - '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)", - $id_agent, - $id_group, - $event, - $status, - $id_user, - $event_type, - $priority, - $id_agent_module, - $id_aam, - $critical_instructions, - $warning_instructions, - $unknown_instructions, - $source, - $tags, - $custom_data, - $id_extra, - $data, - $module_status - ); - break; - } + $sql = sprintf( + 'INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, + timestamp, estado, utimestamp, id_usuario, + event_type, criticity, id_agentmodule, id_alert_am, + critical_instructions, warning_instructions, + unknown_instructions, source, tags, custom_data, id_extra, data, module_status) + VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()), + "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s", %d, %d)', + $id_agent, + $id_group, + $event, + $status, + $id_user, + $event_type, + $priority, + $id_agent_module, + $id_aam, + $critical_instructions, + $warning_instructions, + $unknown_instructions, + $source, + $tags, + $custom_data, + $id_extra, + $data, + $module_status + ); } return (int) db_process_sql($sql, 'insert_id'); @@ -998,24 +946,32 @@ function events_create_event( /** - * Prints a small event table + * Prints a small event table. * - * @param string $filter SQL WHERE clause - * @param integer $limit How many events to show - * @param integer $width How wide the table should be - * @param boolean $return Prints out HTML if false - * @param int agent id if is the table of one agent. 0 otherwise + * @param string $filter SQL WHERE clause. + * @param integer $limit How many events to show. + * @param integer $width How wide the table should be. + * @param boolean $return Prints out HTML if false. + * @param integer $agent_id Agent id if is the table of one agent. + * 0 otherwise. + * @param boolean $tactical_view Be shown in tactical view or not. * - * @return string HTML with table element + * @return string HTML with table element. */ -function events_print_event_table($filter='', $limit=10, $width=440, $return=false, $agent_id=0, $tactical_view=false) -{ +function events_print_event_table( + $filter='', + $limit=10, + $width=440, + $return=false, + $agent_id=0, + $tactical_view=false +) { global $config; if ($agent_id == 0) { $agent_condition = ''; } else { - $agent_condition = " id_agente = $agent_id AND "; + $agent_condition = ' id_agente = '.$agent_id.' AND '; } if ($filter == '') { @@ -1063,7 +1019,9 @@ function events_print_event_table($filter='', $limit=10, $width=440, $return=fal $table->cellclass = []; $table->data = []; $table->align = []; - $table->style[0] = $table->style[1] = $table->style[2] = 'width:25px;'; + $table->style[0] = 'width:25px;'; + $table->style[1] = 'width:25px;'; + $table->style[2] = 'width:25px;'; if ($agent_id == 0) { $table->style[3] = 'word-break: break-all;'; } @@ -1098,7 +1056,7 @@ function events_print_event_table($filter='', $limit=10, $width=440, $return=fal } foreach ($result as $event) { - // Copy all groups of the agent and append the event group + // Copy all groups of the agent and append the event group. $check_events = $all_groups; $check_events[] = $event['id_grupo']; if (! check_acl_one_of_groups($config['id_user'], $check_events, 'ER')) { @@ -1107,7 +1065,7 @@ function events_print_event_table($filter='', $limit=10, $width=440, $return=fal $data = []; - // Colored box + // Colored box. switch ($event['estado']) { case 0: $img = 'images/star.png'; @@ -1123,6 +1081,10 @@ function events_print_event_table($filter='', $limit=10, $width=440, $return=fal $img = 'images/hourglass.png'; $title = __('Event in process'); break; + + default: + // Ignore. + break; } $data[0] = html_print_image( @@ -1167,20 +1129,25 @@ function events_print_event_table($filter='', $limit=10, $width=440, $return=fal ] ); - // Event type + // Event type. $data[2] = events_print_type_img($event['event_type'], true); - // Event text - $data[3] = ui_print_string_substr(strip_tags(io_safe_output($event['evento'])), 75, true, '7.5'); + // Event text. + $data[3] = ui_print_string_substr( + strip_tags(io_safe_output($event['evento'])), + 75, + true, + '7.5' + ); if ($agent_id == 0) { if ($event['id_agente'] > 0) { - // Agent name - // Get class name, for the link color... + // Agent name. + // Get class name, for the link color, etc. $myclass = get_priority_class($event['criticity']); - $data[4] = "".agents_get_alias($event['id_agente']).''; - // for System or SNMP generated alerts + $data[4] = "".agents_get_alias($event['id_agente']).''; + // For System or SNMP generated alerts. } else if ($event['event_type'] == 'system') { $data[4] = __('System'); } else { @@ -1188,13 +1155,21 @@ function events_print_event_table($filter='', $limit=10, $width=440, $return=fal } } - // Timestamp + // Timestamp. $data[5] = ui_print_timestamp($event['timestamp'], true, ['style' => 'font-size: 7.5pt; letter-spacing: 0.3pt;']); $class = get_priority_class($event['criticity']); - $cell_classes[3] = $cell_classes[4] = $cell_classes[5] = $class; + $cell_classes[3] = $class; + $cell_classes[4] = $class; + $cell_classes[5] = $class; + array_push($table->cellclass, $cell_classes); - // array_push ($table->rowclass, get_priority_class ($event["criticity"])); + + /* + Commented out (old). + // array_push ($table->rowclass, get_priority_class ($event["criticity"])); + */ + array_push($table->data, $data); } @@ -1234,16 +1209,19 @@ function events_print_event_table($filter='', $limit=10, $width=440, $return=fal /** - * Prints the event type image + * Prints the event type image. * - * @param string $type Event type from SQL - * @param boolean $return Whether to return or print + * @param string $type Event type from SQL. + * @param boolean $return Whether to return or print. * @param boolean $only_url Flag to return only url of image, by default false. * - * @return string HTML with img + * @return string HTML with img. */ -function events_print_type_img($type, $return=false, $only_url=false) -{ +function events_print_type_img( + $type, + $return=false, + $only_url=false +) { global $config; $output = ''; @@ -1261,13 +1239,13 @@ function events_print_type_img($type, $return=false, $only_url=false) case 'going_down_critical': case 'going_up_critical': - // This is to be backwards compatible + // This is to be backwards compatible. $icon = 'module_critical.png'; break; case 'going_up_normal': case 'going_down_normal': - // This is to be backwards compatible + // This is to be backwards compatible. $icon = 'module_ok.png'; break; @@ -1307,7 +1285,7 @@ function events_print_type_img($type, $return=false, $only_url=false) } if ($only_url) { - $output = $urlImage.'/'.'images/'.$icon; + $output = $urlImage.'/images/'.$icon; } else { $output .= html_print_image( 'images/'.$icon, @@ -1327,8 +1305,8 @@ function events_print_type_img($type, $return=false, $only_url=false) /** * Prints the event type description * - * @param string $type Event type from SQL - * @param boolean $return Whether to return or print + * @param string $type Event type from SQL. + * @param boolean $return Whether to return or print. * * @return string HTML with img */ @@ -1355,13 +1333,13 @@ function events_print_type_description($type, $return=false) case 'going_down_critical': case 'going_up_critical': - // This is to be backwards compatible + // This is to be backwards compatible. $output .= __('Going up to critical state'); break; case 'going_up_normal': case 'going_down_normal': - // This is to be backwards compatible + // This is to be backwards compatible. $output .= __('Going up to normal state'); break; @@ -1416,9 +1394,15 @@ function events_print_type_description($type, $return=false) * * The returned events will be in the time interval ($date - $period, $date] * - * @param mixed $id_group Group id to get events for. - * @param integer $period Period of time in seconds to get events. - * @param integer $date Beginning date to get events. + * @param mixed $begin Begin. + * @param mixed $result Result. + * @param mixed $id_group Group id to get events for. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_validated Filter_event_validated. + * @param boolean $filter_event_critical Filter_event_critical. + * @param boolean $filter_event_warning Filter_event_warning. + * @param boolean $filter_event_no_validated Filter_event_no_validated. * * @return array An array with all the events happened. */ @@ -1438,7 +1422,7 @@ function events_get_group_events_steps( $id_group = groups_safe_acl($config['id_user'], $id_group, 'ER'); if (empty($id_group)) { - // An empty array means the user doesn't have access + // An empty array means the user doesn't have access. return false; } @@ -1492,9 +1476,20 @@ function events_get_group_events_steps( * * The returned events will be in the time interval ($date - $period, $date] * - * @param integer $id_agent Agent id to get events. - * @param integer $period Period of time in seconds to get events. - * @param integer $date Beginning date to get events. + * @param integer $id_agent Agent id to get events. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $history History. + * @param boolean $show_summary_group Show_summary_group. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $id_group Id_group. + * @param boolean $events_group Events_group. + * @param boolean $id_agent_module Id_agent_module. + * @param boolean $events_module Events_module. + * @param boolean $id_server Id_server. * * @return array An array with all the events happened. */ @@ -1528,7 +1523,7 @@ function events_get_agent( $id_group = groups_safe_acl($config['id_user'], $id_group, 'ER'); if (empty($id_group)) { - // An empty array means the user doesn't have access + // An empty array means the user doesn't have access. return false; } } @@ -1557,6 +1552,7 @@ function events_get_agent( break; default: + // Ignore. break; } } @@ -1577,12 +1573,16 @@ function events_get_agent( case 3: $filter_event_status[$key] = ('0, 2'); default: + // Ignore. break; } } if (!$status_all) { - $sql_where .= ' AND estado IN ('.implode(', ', $filter_event_status).')'; + $sql_where .= ' AND estado IN ('.implode( + ', ', + $filter_event_status + ).')'; } } @@ -1591,10 +1591,10 @@ function events_get_agent( $type = []; foreach ($filter_event_type as $event_type) { if ($event_type != '') { - // If normal, warning, could be several (going_up_warning, going_down_warning... too complex - // for the user so for him is presented only "warning, critical and normal" + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { - $type[] = " event_type LIKE '%$event_type%' "; + $type[] = " event_type LIKE '%".$event_type."%' "; } else if ($event_type == 'not_normal') { $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; } else if ($event_type != 'all') { @@ -1607,7 +1607,7 @@ function events_get_agent( } if (!empty($filter_event_filter_search)) { - $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%"'.' OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; } if ($events_group) { @@ -1801,6 +1801,8 @@ function events_get_severity_types($severity_id) /** * Return all descriptions of event status. * + * @param boolean $report Show in report or not. + * * @return array Status description array. */ function events_get_all_status($report=false) @@ -1853,6 +1855,10 @@ function events_get_status($status_id) case 3: $status_desc = __('Only not validated'); break; + + default: + // Ignore. + break; } return $status_desc; @@ -1872,10 +1878,10 @@ function events_check_event_filter_group($id_filter) $id_group = db_get_value('id_group_filter', 'tevent_filter', 'id_filter', $id_filter); $own_info = get_user_info($config['id_user']); - // Get group list that user has access + // Get group list that user has access. $groups_user = users_get_groups($config['id_user'], 'EW', $own_info['is_admin'], true); - // Permissions in any group allow to edit "All group" filters + // Permissions in any group allow to edit "All group" filters. if ($id_group == 0 && !empty($groups_user)) { return true; } @@ -1896,9 +1902,9 @@ function events_check_event_filter_group($id_filter) /** * Get a event filter. * - * @param int Filter id to be fetched. - * @param array Extra filter. - * @param array Fields to be fetched. + * @param integer $id_filter Filter id to be fetched. + * @param array $filter Extra filter. + * @param array $fields Fields to be fetched. * * @return array A event filter matching id and filter or false. */ @@ -1920,7 +1926,9 @@ function events_get_event_filter($id_filter, $filter=false, $fields=false) /** * Get a event filters in select format. * - * @param boolean If event filters are used for manage/view operations (non admin users can see group ALL for manage) # Fix + * @param boolean $manage If event filters are used for manage/view operations + * (non admin users can see group ALL for manage) # Fix. + * * @return array A event filter matching id and filter or false. */ function events_get_event_filter_select($manage=true) @@ -1967,13 +1975,20 @@ function events_get_event_filter_select($manage=true) } -// Events pages functions to load modal window with advanced view of an event. -// Called from include/ajax/events.php +/** + * Events pages functions to load modal window with advanced view of an event. + * Called from include/ajax/events.php. + * + * @param mixed $event Event. + * @param array $childrens_ids Children_ids. + * + * @return string HTML. + */ function events_page_responses($event, $childrens_ids=[]) { global $config; // - // Responses + // Responses. // $table_responses->cellspacing = 2; $table_responses->cellpadding = 2; @@ -1986,26 +2001,43 @@ function events_page_responses($event, $childrens_ids=[]) $table_responses->class = 'alternate rounded_cells'; if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids)) { - // Owner + // Owner. $data = []; $data[0] = __('Change owner'); - // Owner change can be done to users that belong to the event group with ER permission + // Owner change can be done to users that belong to the event group + // with ER permission. $profiles_view_events = db_get_all_rows_filter('tperfil', ['event_view' => '1'], 'id_perfil'); foreach ($profiles_view_events as $k => $v) { $profiles_view_events[$k] = reset($v); } - // Juanma (05/05/2014) Fix : Propagate ACL hell! - $_user_groups = array_keys(users_get_groups($config['id_user'], 'ER', users_can_manage_group_all())); - $strict_user = db_get_value('strict_acl', 'tusuario', 'id_user', $config['id_user']); + // Juanma (05/05/2014) Fix : Propagate ACL. + $_user_groups = array_keys( + users_get_groups($config['id_user'], 'ER', users_can_manage_group_all()) + ); + $strict_user = db_get_value( + 'strict_acl', + 'tusuario', + 'id_user', + $config['id_user'] + ); if ($strict_user) { - $user_name = db_get_value('fullname', 'tusuario', 'id_user', $config['id_user']); + $user_name = db_get_value( + 'fullname', + 'tusuario', + 'id_user', + $config['id_user'] + ); $users = []; $users[0]['id_user'] = $config['id_user']; $users[0]['fullname'] = $user_name; } else { - $users = groups_get_users($_user_groups, ['id_perfil' => $profiles_view_events], true); + $users = groups_get_users( + $_user_groups, + ['id_perfil' => $profiles_view_events], + true + ); } foreach ($users as $u) { @@ -2015,24 +2047,52 @@ function events_page_responses($event, $childrens_ids=[]) if ($event['owner_user'] == '') { $owner_name = __('None'); } else { - $owner_name = db_get_value('fullname', 'tusuario', 'id_user', $event['owner_user']); + $owner_name = db_get_value( + 'fullname', + 'tusuario', + 'id_user', + $event['owner_user'] + ); $owners[$event['owner_user']] = $owner_name; } - $data[1] = html_print_select($owners, 'id_owner', $event['owner_user'], '', __('None'), -1, true); - $data[1] .= html_print_button(__('Update'), 'owner_button', false, 'event_change_owner();', 'class="sub next"', true); + $data[1] = html_print_select( + $owners, + 'id_owner', + $event['owner_user'], + '', + __('None'), + -1, + true + ); + $data[1] .= html_print_button( + __('Update'), + 'owner_button', + false, + 'event_change_owner();', + 'class="sub next"', + true + ); $table_responses->data[] = $data; } - // Status + // Status. $data = []; $data[0] = __('Change status'); $status_blocked = false; - if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids)) { - // If the user has manager acls, the status can be changed to all possibilities always + if (tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EM', + $event['clean_tags'], + $childrens_ids + ) + ) { + // If the user has manager acls, the status can be changed to all + // possibilities always. $status = [ 0 => __('New'), 2 => __('In process'), @@ -2041,7 +2101,8 @@ function events_page_responses($event, $childrens_ids=[]) } else { switch ($event['estado']) { case 0: - // If the user hasnt manager acls and the event is new. The status can be changed + // If the user hasnt manager acls and the event is new. + // The status can be changed. $status = [ 2 => __('In process'), 1 => __('Validated'), @@ -2049,48 +2110,99 @@ function events_page_responses($event, $childrens_ids=[]) break; case 1: - // If the user hasnt manager acls and the event is validated. The status cannot be changed + // If the user hasnt manager acls and the event is validated. + // The status cannot be changed. $status = [1 => __('Validated')]; $status_blocked = true; break; case 2: - // If the user hasnt manager acls and the event is in process. The status only can be changed to validated + // If the user hasnt manager acls and the event is in process. + // The status only can be changed to validated. $status = [1 => __('Validated')]; break; + + default: + // Ignored. + break; } } - // The change status option will be enabled only when is possible change the status - $data[1] = html_print_select($status, 'estado', $event['estado'], '', '', 0, true, false, false, '', $status_blocked); + // The change status option will be enabled only when is possible change + // the status. + $data[1] = html_print_select( + $status, + 'estado', + $event['estado'], + '', + '', + 0, + true, + false, + false, + '', + $status_blocked + ); if (!$status_blocked) { - $data[1] .= html_print_button(__('Update'), 'status_button', false, 'event_change_status(\''.$event['similar_ids'].'\');', 'class="sub next"', true); + $data[1] .= html_print_button( + __('Update'), + 'status_button', + false, + 'event_change_status(\''.$event['similar_ids'].'\');', + 'class="sub next"', + true + ); } $table_responses->data[] = $data; - // Comments + // Comments. $data = []; $data[0] = __('Comment'); - $data[1] = html_print_button(__('Add comment'), 'comment_button', false, '$(\'#link_comments\').trigger(\'click\');', 'class="sub next"', true); + $data[1] = html_print_button( + __('Add comment'), + 'comment_button', + false, + '$(\'#link_comments\').trigger(\'click\');', + 'class="sub next"', + true + ); $table_responses->data[] = $data; - if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids)) { - // Delete + if (tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EM', + $event['clean_tags'], + $childrens_ids + ) + ) { + // Delete. $data = []; $data[0] = __('Delete event'); $data[1] = '
'; - $data[1] .= html_print_button(__('Delete event'), 'delete_button', false, 'if(!confirm(\''.__('Are you sure?').'\')) { return false; } this.form.submit();', 'class="sub cancel"', true); + $data[1] .= html_print_button( + __('Delete event'), + 'delete_button', + false, + 'if(!confirm(\''.__('Are you sure?').'\')) { return false; } this.form.submit();', + 'class="sub cancel"', + true + ); $data[1] .= html_print_input_hidden('delete', 1, true); - $data[1] .= html_print_input_hidden('validate_ids', $event['id_evento'], true); + $data[1] .= html_print_input_hidden( + 'validate_ids', + $event['id_evento'], + true + ); $data[1] .= '
'; $table_responses->data[] = $data; } - // Custom responses + // Custom responses. $data = []; $data[0] = __('Custom responses'); @@ -2126,7 +2238,14 @@ function events_page_responses($event, $childrens_ids=[]) $server_id = 0; } - $data[1] .= html_print_button(__('Execute'), 'custom_response_button', false, 'execute_response('.$event['id_evento'].','.$server_id.')', "class='sub next'", true); + $data[1] .= html_print_button( + __('Execute'), + 'custom_response_button', + false, + 'execute_response('.$event['id_evento'].','.$server_id.')', + "class='sub next'", + true + ); } $table_responses->data[] = $data; @@ -2161,10 +2280,23 @@ function events_page_responses($event, $childrens_ids=[]) } -// Replace macros in the target of a response and return it -// If server_id > 0, is a metaconsole query -function events_get_response_target($event_id, $response_id, $server_id, $history=false) -{ +/** + * Replace macros in the target of a response and return it. + * If server_id > 0, is a metaconsole query. + * + * @param integer $event_id Event_id. + * @param integer $response_id Response_id. + * @param integer $server_id Server_id. + * @param boolean $history History. + * + * @return string Target. + */ +function events_get_response_target( + $event_id, + $response_id, + $server_id, + $history=false +) { global $config; $event_response = db_get_row('tevent_response', 'id', $response_id); @@ -2181,7 +2313,7 @@ function events_get_response_target($event_id, $response_id, $server_id, $histor $target = io_safe_output($event_response['target']); - // Substitute each macro + // Substitute each macro. if (strpos($target, '_agent_address_') !== false) { if ($meta) { $agente_table_name = 'tmetaconsole_agent'; @@ -2195,7 +2327,7 @@ function events_get_response_target($event_id, $response_id, $server_id, $histor } $ip = db_get_value_filter('direccion', $agente_table_name, $filter); - // If agent has not an ip, display N/A + // If agent has not an ip, display N/A. if ($ip === false) { $ip = __('N/A'); } @@ -2266,7 +2398,11 @@ function events_get_response_target($event_id, $response_id, $server_id, $histor } if (strpos($target, '_event_utimestamp_') !== false) { - $target = str_replace('_event_utimestamp_', $event['utimestamp'], $target); + $target = str_replace( + '_event_utimestamp_', + $event['utimestamp'], + $target + ); } if (strpos($target, '_event_date_') !== false) { @@ -2355,12 +2491,17 @@ function events_get_response_target($event_id, $response_id, $server_id, $histor } if (strpos($target, '_group_custom_id_') !== false) { - $group_custom_id = db_get_value($dbh, 'SELECT custom_id FROM tgrupo WHERE id_grupo=?', $event['id_grupo']); + $group_custom_id = db_get_value_sql( + sprintf( + 'SELECT custom_id FROM tgrupo WHERE id_grupo=%s', + $event['id_grupo'] + ) + ); $event_st = events_display_status($event['estado']); $target = str_replace('_group_custom_id_', $group_custom_id, $target); } - // Parse the event custom data + // Parse the event custom data. if (!empty($event['custom_data'])) { $custom_data = json_decode(base64_decode($event['custom_data'])); foreach ($custom_data as $key => $value) { @@ -2372,12 +2513,19 @@ function events_get_response_target($event_id, $response_id, $server_id, $histor } +/** + * Generates 'custom field' page for event viewer. + * + * @param array $event Event to be displayed. + * + * @return string HTML. + */ function events_page_custom_fields($event) { global $config; // - // Custom fields + // Custom fields. // $table->cellspacing = 2; $table->cellpadding = 2; @@ -2418,7 +2566,7 @@ function events_page_custom_fields($event) } foreach ($fields as $field) { - // Owner + // Owner. $data = []; $data[0] = $field['name']; @@ -2443,15 +2591,62 @@ function events_page_custom_fields($event) } +/** + * Retrieves extended information of given event. + * + * @param integer $id_evento Target event. + * + * @return mixed array Of extended events or false if error. + */ +function events_get_extended_events(int $id_evento) +{ + return db_get_all_rows_sql( + sprintf( + 'SELECT * FROM tevent_extended WHERE id_evento=%d', + $id_evento + ) + ); + +} + + +/** + * Generates the 'extended' page in event view. + * + * @param array $event To be displayed. + * @param string $server Server (if in metaconsole environment). + * + * @return string HTML to be displayed. + */ +function events_page_extended($event, $server='') +{ + $html = ''; + + $data = []; + $data[0] = __('Extended events'); + $data[1] = ''; + + return $html; +} + + +/** + * Generates the 'details' page in event view. + * + * @param array $event To be displayed. + * @param string $server Server (if in metaconsole environment). + * + * @return string HTML to be displayed. + */ function events_page_details($event, $server='') { global $img_sev; global $config; - // If server is provided, get the hash parameters + // If server is provided, get the hash parameters. if (!empty($server) && defined('METACONSOLE')) { $hashdata = metaconsole_get_server_hashdata($server); - $hashstring = '&'.'loginhash=auto&'.'loginhash_data='.$hashdata.'&'.'loginhash_user='.str_rot13($config['id_user']); + $hashstring = '&loginhash=auto&loginhash_data='.$hashdata.'&loginhash_user='.str_rot13($config['id_user']); $serverstring = $server['server_url'].'/'; if (metaconsole_connect($server) !== NOERR) { @@ -2463,7 +2658,7 @@ function events_page_details($event, $server='') } // - // Details + // Details. // $table_details->width = '100%'; $table_details->data = []; @@ -2474,15 +2669,20 @@ function events_page_details($event, $server='') $table_details->style[1] = 'text-align: left; height: 23px;'; $table_details->class = 'alternate rounded_cells'; - switch ($event['event_type']) { + /* + * Useless switch. + + switch ($event['event_type']) { case 'going_unknown': case 'going_up_warning': case 'going_down_warning': case 'going_up_critical': case 'going_down_critical': - + default: + // Ignore. break; - } + } + */ if ($event['id_agente'] != 0) { $agent = db_get_row('tagente', 'id_agente', $event['id_agente']); @@ -2490,7 +2690,6 @@ function events_page_details($event, $server='') $agent = []; } - $data = []; $data[0] = __('Agent details'); $data[1] = empty($agent) ? ''.__('N/A').'' : ''; $table_details->data[] = $data; @@ -2499,9 +2698,24 @@ function events_page_details($event, $server='') $data = []; $data[0] = '
'.__('Name').'
'; if (can_user_access_node()) { - $data[1] = ui_print_agent_name($event['id_agente'], true, 'agent_medium', '', false, $serverstring, $hashstring, $agent['alias']); + $data[1] = ui_print_agent_name( + $event['id_agente'], + true, + 'agent_medium', + '', + false, + $serverstring, + $hashstring, + $agent['alias'] + ); } else { - $data[1] = ui_print_truncate_text($agent['alias'], 'agent_medium', true, true, true); + $data[1] = ui_print_truncate_text( + $agent['alias'], + 'agent_medium', + true, + true, + true + ); } $table_details->data[] = $data; @@ -2522,22 +2736,35 @@ function events_page_details($event, $server='') $data = []; $data[0] = '
'.__('Last contact').'
'; - $data[1] = $agent['ultimo_contacto'] == '1970-01-01 00:00:00' ? ''.__('N/A').'' : date_w_fixed_tz($agent['ultimo_contacto']); + $data[1] = ($agent['ultimo_contacto'] == '1970-01-01 00:00:00') ? ''.__('N/A').'' : date_w_fixed_tz($agent['ultimo_contacto']); $table_details->data[] = $data; $data = []; $data[0] = '
'.__('Last remote contact').'
'; - $data[1] = $agent['ultimo_contacto_remoto'] == '1970-01-01 00:00:00' ? ''.__('N/A').'' : date_w_fixed_tz($agent['ultimo_contacto_remoto']); + $data[1] = ($agent['ultimo_contacto_remoto'] == '1970-01-01 00:00:00') ? ''.__('N/A').'' : date_w_fixed_tz($agent['ultimo_contacto_remoto']); $table_details->data[] = $data; $data = []; $data[0] = '
'.__('Custom fields').'
'; - $data[1] = html_print_button(__('View custom fields'), 'custom_button', false, '$(\'#link_custom_fields\').trigger(\'click\');', 'class="sub next"', true); + $data[1] = html_print_button( + __('View custom fields'), + 'custom_button', + false, + '$(\'#link_custom_fields\').trigger(\'click\');', + 'class="sub next"', + true + ); $table_details->data[] = $data; } if ($event['id_agentmodule'] != 0) { - $module = db_get_row_filter('tagente_modulo', ['id_agente_modulo' => $event['id_agentmodule'], 'delete_pending' => 0]); + $module = db_get_row_filter( + 'tagente_modulo', + [ + 'id_agente_modulo' => $event['id_agentmodule'], + 'delete_pending' => 0, + ] + ); } else { $module = []; } @@ -2548,20 +2775,25 @@ function events_page_details($event, $server='') $table_details->data[] = $data; if (!empty($module)) { - // Module name + // Module name. $data = []; $data[0] = '
'.__('Name').'
'; $data[1] = $module['nombre']; $table_details->data[] = $data; - // Module group + // Module group. $data = []; $data[0] = '
'.__('Module group').'
'; $id_module_group = $module['id_module_group']; if ($id_module_group == 0) { $data[1] = __('No assigned'); } else { - $module_group = db_get_value('name', 'tmodule_group', 'id_mg', $id_module_group); + $module_group = db_get_value( + 'name', + 'tmodule_group', + 'id_mg', + $id_module_group + ); $data[1] = ''; $data[1] .= $module_group; $data[1] .= ''; @@ -2569,12 +2801,21 @@ function events_page_details($event, $server='') $table_details->data[] = $data; - // ACL + // ACL. $acl_graph = false; - $strict_user = (bool) db_get_value('strict_acl', 'tusuario', 'id_user', $config['id_user']); + $strict_user = (bool) db_get_value( + 'strict_acl', + 'tusuario', + 'id_user', + $config['id_user'] + ); if (!empty($agent['id_grupo'])) { - $acl_graph = check_acl($config['id_user'], $agent['id_grupo'], 'RR'); + $acl_graph = check_acl( + $config['id_user'], + $agent['id_grupo'], + 'RR' + ); } if ($acl_graph) { @@ -2587,9 +2828,16 @@ function events_page_details($event, $server='') } $graph_type = return_graphtype($module_type); - $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); - $handle = dechex(crc32($module['id_agente_modulo'].$module['nombre'])); - $win_handle = "day_$handle"; + $url = ui_get_full_url( + 'operation/agentes/stat_win.php', + false, + false, + false + ); + $handle = dechex( + crc32($module['id_agente_modulo'].$module['nombre']) + ); + $win_handle = 'day_'.$handle; $graph_params = [ 'type' => $graph_type, @@ -2600,13 +2848,13 @@ function events_page_details($event, $server='') ]; if (defined('METACONSOLE')) { - // Set the server id + // Set the server id. $graph_params['server'] = $server['id']; } $graph_params_str = http_build_query($graph_params); - $link = "winopeng('$url?$graph_params_str','$win_handle')"; + $link = "winopeng('".$url.'?'.$graph_params_str."','".$win_handle."')"; $data[1] = ''; $data[1] .= html_print_image('images/chart_curve.png', true); @@ -2617,7 +2865,7 @@ function events_page_details($event, $server='') $data = []; $data[0] = __('Alert details'); - $data[1] = $event['id_alert_am'] == 0 ? ''.__('N/A').'' : ''; + $data[1] = ($event['id_alert_am'] == 0) ? ''.__('N/A').'' : ''; $table_details->data[] = $data; if ($event['id_alert_am'] != 0) { @@ -2708,12 +2956,19 @@ function events_page_details($event, $server='') } +/** + * Generates content for 'custom data' page in event viewer. + * + * @param array $event Event. + * + * @return string HTML. + */ function events_page_custom_data($event) { global $config; // - // Custom data + // Custom data. // if ($event['custom_data'] == '') { return ''; @@ -2745,14 +3000,26 @@ function events_page_custom_data($event) } -// Get the event name from tevento and display it in console +/** + * Get the event name from tevento and display it in console. + * + * @param string $db_name Target event name. + * + * @return string Event name. + */ function events_display_name($db_name='') { return io_safe_output(str_replace(' ', '
', $db_name)); } -// Get the image and status value of event +/** + * Get the image and status value of event. + * + * @param integer $status Status. + * + * @return string Image path. + */ function events_display_status($status) { switch ($status) { @@ -2773,15 +3040,26 @@ function events_display_status($status) 'img' => 'images/hourglass.png', 'title' => __('Event in process'), ]; + + default: + // Ignore. + break; } } -// Get the instruction of an event -// $event_type: Type of event -// $inst: Array with unknown warning and critical instructions -// $italic: Display N/A between italic html marks if instruction is not found -function events_display_instructions($event_type='', $inst, $italic=true) +/** + * Get the instruction of an event. + * + * @param string $event_type Type of event. + * @param array $inst Array with unknown warning and critical + * instructions. + * @param boolean $italic Display N/A between italic html marks if + * instruction is not found. + * + * @return string Safe output. + */ +function events_display_instructions($event_type='', $inst=[], $italic=true) { switch ($event_type) { case 'going_unknown': @@ -2818,23 +3096,39 @@ function events_display_instructions($event_type='', $inst, $italic=true) return str_replace("\n", '
', io_safe_output($inst['unknown_instructions'])); } break; + + default: + // Ignore. + break; } - $na_return = $italic ? ''.__('N/A').'' : __('N/A'); + $na_return = ($italic === true) ? ''.__('N/A').'' : __('N/A'); + return $na_return; } +/** + * Generates 'general' page for events viewer. + * + * @param array $event Event. + * + * @return string HTML. + */ function events_page_general($event) { global $img_sev; global $config; - // $group_rep = $event['similar_ids'] == -1 ? 1 : count(explode(',',$event['similar_ids'])); + /* + Commented out (old) + // $group_rep = $event['similar_ids'] == -1 ? 1 : count(explode(',',$event['similar_ids'])); + */ + global $group_rep; // - // General + // General. // $table_general->cellspacing = 2; $table_general->cellpadding = 2; @@ -2885,7 +3179,10 @@ function events_page_general($event) $data = []; $data[0] = __('Type'); - $data[1] = events_print_type_img($event['event_type'], true).' '.events_print_type_description($event['event_type'], true); + $data[1] = events_print_type_img( + $event['event_type'], + true + ).' '.events_print_type_description($event['event_type'], true); $table_general->data[] = $data; $data = []; @@ -2919,7 +3216,7 @@ function events_page_general($event) $data[1] .= ' '.$event_criticity; $table_general->data[] = $data; - // Get Status + // Get Status. $event_st = events_display_status($event['estado']); $data = []; @@ -2927,7 +3224,7 @@ function events_page_general($event) $data[1] = html_print_image($event_st['img'], true).' '.$event_st['title']; $table_general->data[] = $data; - // If event is validated, show who and when acknowleded it + // If event is validated, show who and when acknowleded it. $data = []; $data[0] = __('Acknowledged by'); @@ -2984,10 +3281,18 @@ function events_page_general($event) } +/** + * Generate 'comments' page for event viewer. + * + * @param array $event Event. + * @param array $childrens_ids Children ids. + * + * @return string HTML. + */ function events_page_comments($event, $childrens_ids=[]) { // - // Comments + // Comments. // global $config; @@ -3001,13 +3306,13 @@ function events_page_comments($event, $childrens_ids=[]) $event_comments = $event['user_comment']; $event_comments = str_replace(["\n", ' '], '
', $event_comments); - // If comments are not stored in json, the format is old + // If comments are not stored in json, the format is old. $event_comments_array = json_decode($event_comments, true); - // Show the comments more recent first + // Show the comments more recent first. $event_comments_array = array_reverse($event_comments_array); - if (is_null($event_comments_array)) { + if (empty($event_comments_array)) { $comments_format = 'old'; } else { $comments_format = 'new'; @@ -3034,7 +3339,7 @@ function events_page_comments($event, $childrens_ids=[]) case 'old': $comments_array = explode('
', $event_comments); - // Split comments and put in table + // Split comments and put in table. $col = 0; $data = []; @@ -3050,6 +3355,10 @@ function events_page_comments($event, $childrens_ids=[]) case 1: $row_text = preg_replace("/[\r\n|\r|\n]/", '
', io_safe_output(strip_tags($c))); break; + + default: + // Ignore. + break; } $data[$col] = $row_text; @@ -3071,14 +3380,33 @@ function events_page_comments($event, $childrens_ids=[]) $table_comments->data[] = $data; } break; + + default: + // Ignore. + break; } - if (((tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids)) || (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EW', $event['clean_tags'], $childrens_ids))) && $config['show_events_in_local'] == false || $config['event_replication'] == false) { + if (((tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EM', + $event['clean_tags'], + $childrens_ids + )) || (tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EW', + $event['clean_tags'], + $childrens_ids + ))) && $config['show_events_in_local'] == false || $config['event_replication'] == false + ) { $comments_form = '
'.html_print_textarea('comment', 3, 10, '', 'style="min-height: 15px; width: 100%; disabled"', true); $comments_form .= '
'.html_print_button(__('Add comment'), 'comment_button', false, 'event_comment();', 'class="sub next"', true).'

'; } else { - $comments_form = ui_print_message(__('If event replication is ongoing, it won\'t be possible to enter comments here. This option is only to allow local pandora users to see comments, but not to operate with them. The operation, when event replication is enabled, must be done only in the Metaconsole.')); + $comments_form = ui_print_message( + __('If event replication is ongoing, it won\'t be possible to enter comments here. This option is only to allow local pandora users to see comments, but not to operate with them. The operation, when event replication is enabled, must be done only in the Metaconsole.') + ); } $comments = '
'.$comments_form.html_print_table($table_comments, true).'
'; @@ -3087,6 +3415,13 @@ function events_page_comments($event, $childrens_ids=[]) } +/** + * Retrieve event tags (cleaned). + * + * @param string $tags Tags. + * + * @return array of Tags. + */ function events_clean_tags($tags) { if (empty($tags)) { @@ -3103,9 +3438,14 @@ function events_clean_tags($tags) * * The returned events will be in the time interval ($date - $period, $date] * - * @param mixed $id_group Group id to get events for. - * @param integer $period Period of time in seconds to get events. - * @param integer $date Beginning date to get events. + * @param mixed $id_group Group id to get events for. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. * * @return array An array with all the events happened. */ @@ -3121,7 +3461,7 @@ function events_get_count_events_by_agent( ) { global $config; - // date + // Date. if (!is_numeric($date)) { $date = time_w_fixed_tz($date); } @@ -3130,11 +3470,11 @@ function events_get_count_events_by_agent( $date = get_system_time(); } - // group + // Group. $id_group = groups_safe_acl($config['id_user'], $id_group, 'AR'); if (empty($id_group)) { - // An empty array means the user doesn't have access + // An empty array means the user doesn't have access. return false; } @@ -3162,6 +3502,7 @@ function events_get_count_events_by_agent( break; default: + // Ignore. break; } } @@ -3182,6 +3523,7 @@ function events_get_count_events_by_agent( case 3: $filter_event_status[$key] = ('0, 2'); default: + // Ignore. break; } } @@ -3196,10 +3538,10 @@ function events_get_count_events_by_agent( $type = []; foreach ($filter_event_type as $event_type) { if ($event_type != '') { - // If normal, warning, could be several (going_up_warning, going_down_warning... too complex - // for the user so for him is presented only "warning, critical and normal" + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { - $type[] = " event_type LIKE '%$event_type%' "; + $type[] = " event_type LIKE '%".$event_type."%' "; } else if ($event_type == 'not_normal') { $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; } else if ($event_type != 'all') { @@ -3212,7 +3554,7 @@ function events_get_count_events_by_agent( } if (!empty($filter_event_filter_search)) { - $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%"'.' OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; } $tagente = 'tagente'; @@ -3265,9 +3607,14 @@ function events_get_count_events_by_agent( * * The returned events will be in the time interval ($date - $period, $date] * - * @param mixed $id_group Group id to get events for. - * @param integer $period Period of time in seconds to get events. - * @param integer $date Beginning date to get events. + * @param array $filter Use target filter. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. * * @return array An array with all the events happened. */ @@ -3282,13 +3629,13 @@ function events_get_count_events_validated_by_user( $dbmeta=false ) { global $config; - // group + // Group. $sql_filter = ' AND 1=1 '; if (isset($filter['id_group'])) { $id_group = groups_safe_acl($config['id_user'], $filter['id_group'], 'AR'); if (empty($id_group)) { - // An empty array means the user doesn't have access + // An empty array means the user doesn't have access. return false; } @@ -3303,7 +3650,7 @@ function events_get_count_events_validated_by_user( $sql_filter .= sprintf(' AND id_agentmodule = %d ', $filter['id_agentmodule']); } - // date + // Date. if (!is_numeric($date)) { $date = time_w_fixed_tz($date); } @@ -3336,6 +3683,7 @@ function events_get_count_events_validated_by_user( break; default: + // Ignore. break; } } @@ -3356,6 +3704,7 @@ function events_get_count_events_validated_by_user( case 3: $filter_event_status[$key] = ('0, 2'); default: + // Ignore. break; } } @@ -3370,10 +3719,10 @@ function events_get_count_events_validated_by_user( $type = []; foreach ($filter_event_type as $event_type) { if ($event_type != '') { - // If normal, warning, could be several (going_up_warning, going_down_warning... too complex - // for the user so for him is presented only "warning, critical and normal" + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { - $type[] = " event_type LIKE '%$event_type%' "; + $type[] = " event_type LIKE '%".$event_type."%' "; } else if ($event_type == 'not_normal') { $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; } else if ($event_type != 'all') { @@ -3386,7 +3735,7 @@ function events_get_count_events_validated_by_user( } if (!empty($filter_event_filter_search)) { - $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%"'.' OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; } $tevento = 'tevento'; @@ -3435,9 +3784,14 @@ function events_get_count_events_validated_by_user( * * The returned events will be in the time interval ($date - $period, $date] * - * @param mixed $id_group Group id to get events for. - * @param integer $period Period of time in seconds to get events. - * @param integer $date Beginning date to get events. + * @param mixed $filter Target filter. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. * * @return array An array with all the events happened. */ @@ -3458,7 +3812,7 @@ function events_get_count_events_by_criticity( $id_group = groups_safe_acl($config['id_user'], $filter['id_group'], 'AR'); if (empty($id_group)) { - // An empty array means the user doesn't have access + // An empty array means the user doesn't have access. return false; } @@ -3505,6 +3859,7 @@ function events_get_count_events_by_criticity( break; default: + // Ignore. break; } } @@ -3524,7 +3879,10 @@ function events_get_count_events_by_criticity( case 3: $filter_event_status[$key] = ('0, 2'); + break; + default: + // Ignored. break; } } @@ -3539,10 +3897,10 @@ function events_get_count_events_by_criticity( $type = []; foreach ($filter_event_type as $event_type) { if ($event_type != '') { - // If normal, warning, could be several (going_up_warning, going_down_warning... too complex - // for the user so for him is presented only "warning, critical and normal" + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { - $type[] = " event_type LIKE '%$event_type%' "; + $type[] = " event_type LIKE '%".$event_type."%' "; } else if ($event_type == 'not_normal') { $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; } else if ($event_type != 'all') { @@ -3555,7 +3913,7 @@ function events_get_count_events_by_criticity( } if (!empty($filter_event_filter_search)) { - $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%"'.' OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; } $tevento = 'tevento'; @@ -3597,9 +3955,14 @@ function events_get_count_events_by_criticity( * * The returned events will be in the time interval ($date - $period, $date] * - * @param mixed $id_group Group id to get events for. - * @param integer $period Period of time in seconds to get events. - * @param integer $date Beginning date to get events. + * @param mixed $filter Target filter. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. * * @return array An array with all the events happened. */ @@ -3615,30 +3978,43 @@ function events_get_count_events_validated( ) { global $config; - // group + // Group. $sql_filter = ' 1=1 '; if (isset($filter['id_group'])) { - $id_group = groups_safe_acl($config['id_user'], $filter['id_group'], 'AR'); + $id_group = groups_safe_acl( + $config['id_user'], + $filter['id_group'], + 'AR' + ); if (empty($id_group)) { - // An empty array means the user doesn't have access + // An empty array means the user doesn't have access. return false; } - $sql_filter .= sprintf(' AND id_grupo IN (%s) ', implode(',', $id_group)); + $sql_filter .= sprintf( + ' AND id_grupo IN (%s) ', + implode(',', $id_group) + ); } - // agent + // Agent. if (!empty($filter['id_agent'])) { - $sql_filter .= sprintf(' AND id_agente = %d ', $filter['id_agent']); + $sql_filter .= sprintf( + ' AND id_agente = %d ', + $filter['id_agent'] + ); } - // module + // Module. if (!empty($filter['id_agentmodule'])) { - $sql_filter .= sprintf(' AND id_agentmodule = %d ', $filter['id_agentmodule']); + $sql_filter .= sprintf( + ' AND id_agentmodule = %d ', + $filter['id_agentmodule'] + ); } - // date + // Date. if (!is_numeric($date)) { $date = time_w_fixed_tz($date); } @@ -3691,6 +4067,7 @@ function events_get_count_events_validated( break; default: + // Ingore. break; } } @@ -3710,7 +4087,10 @@ function events_get_count_events_validated( case 3: $filter_event_status[$key] = ('0, 2'); + break; + default: + // Ignore. break; } } @@ -3725,10 +4105,10 @@ function events_get_count_events_validated( $type = []; foreach ($filter_event_type as $event_type) { if ($event_type != '') { - // If normal, warning, could be several (going_up_warning, going_down_warning... too complex - // for the user so for him is presented only "warning, critical and normal" + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { - $type[] = " event_type LIKE '%$event_type%' "; + $type[] = " event_type LIKE '%".$event_type."%' "; } else if ($event_type == 'not_normal') { $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; } else if ($event_type != 'all') { @@ -3741,7 +4121,7 @@ function events_get_count_events_validated( } if (!empty($filter_event_filter_search)) { - $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%"'.' OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; } $tevento = 'tevento'; @@ -3781,6 +4161,14 @@ function events_get_count_events_validated( } +/** + * Check event tags. + * + * @param array $event_data Event. + * @param array $acltags Acl tags. + * + * @return boolean True or false. + */ function events_checks_event_tags($event_data, $acltags) { global $config; @@ -3809,6 +4197,18 @@ function events_checks_event_tags($event_data, $acltags) } +/** + * Retrieves events grouped by agent. + * + * @param string $sql_post Sql_post. + * @param integer $offset Offset. + * @param integer $pagination Pagination. + * @param boolean $meta Meta. + * @param boolean $history History. + * @param boolean $total Total. + * + * @return array Data. + */ function events_get_events_grouped_by_agent( $sql_post, $offset=0, @@ -3831,23 +4231,23 @@ function events_get_events_grouped_by_agent( $event_lj = events_get_secondary_groups_left_join($table); if ($total) { - $sql = "SELECT COUNT(*) FROM (select id_agente from $table $event_lj WHERE 1=1 - $sql_post GROUP BY id_agente, event_type$groupby_extra ORDER BY id_agente ) AS t"; + $sql = 'SELECT COUNT(*) FROM (select id_agente from '.$table.' '.$event_lj.' WHERE 1=1 + '.$sql_post.' GROUP BY id_agente, event_type'.$groupby_extra.' ORDER BY id_agente ) AS t'; } else { - $sql = "select id_agente, count(*) as total$fields_extra from $table te $event_lj - WHERE id_agente > 0 $sql_post GROUP BY id_agente$groupby_extra ORDER BY id_agente LIMIT $offset,$pagination"; + $sql = 'select id_agente, count(*) as total'.$fields_extra.' from '.$table.' te '.$event_lj.' + WHERE id_agente > 0 '.$sql_post.' GROUP BY id_agente'.$groupby_extra.' ORDER BY id_agente LIMIT '.$offset.','.$pagination; } $result = []; - // Extract the events by filter (or not) from db + // Extract the events by filter (or not) from db. $events = db_get_all_rows_sql($sql); $result = []; if ($events) { foreach ($events as $event) { if ($meta) { - $sql = "select event_type from $table te $event_lj - WHERE agent_name = '".$event['agent_name']."' $sql_post ORDER BY utimestamp DESC "; + $sql = 'SELECT event_type FROM '.$table.' te '.$event_lj." + WHERE agent_name = '".$event['agent_name']."' ".$sql_post.' ORDER BY utimestamp DESC '; $resultado = db_get_row_sql($sql); $id_agente = $event['agent_name']; @@ -3858,8 +4258,8 @@ function events_get_events_grouped_by_agent( 'event_type' => $resultado['event_type'], ]; } else { - $sql = "SELECT event_type FROM $table te $event_lj - WHERE id_agente = ".$event['id_agente']." $sql_post ORDER BY utimestamp DESC "; + $sql = 'SELECT event_type FROM '.$table.' te '.$event_lj.' + WHERE id_agente = '.$event['id_agente'].' '.$sql_post.' ORDER BY utimestamp DESC '; $resultado = db_get_row_sql($sql); $id_agente = $event['id_agente']; @@ -3876,6 +4276,28 @@ function events_get_events_grouped_by_agent( } +/** + * Return SQL query to group events by agents. + * + * @param mixed $id_agent Id_agent. + * @param integer $server_id Server_id. + * @param string $event_type Event_type. + * @param integer $severity Severity. + * @param integer $status Status. + * @param string $search Search. + * @param integer $id_agent_module Id_agent_module. + * @param integer $event_view_hr Event_view_hr. + * @param boolean $id_user_ack Id_user_ack. + * @param array $tag_with Tag_with. + * @param array $tag_without Tag_without. + * @param boolean $filter_only_alert Filter_only_alert. + * @param string $date_from Date_from. + * @param string $date_to Date_to. + * @param boolean $id_user Id_user. + * @param boolean $server_id_search Server_id_search. + * + * @return string SQL. + */ function events_sql_events_grouped_agents( $id_agent, $server_id=-1, @@ -3913,17 +4335,21 @@ function events_sql_events_grouped_agents( case 3: $sql_post .= ' AND (estado = 0 OR estado = 2)'; break; + + default: + // Ignore. + break; } if ($search != '') { - $sql_post .= " AND (evento LIKE '%".io_safe_input($search)."%' OR id_evento LIKE '%$search%')"; + $sql_post .= " AND (evento LIKE '%".io_safe_input($search)."%' OR id_evento LIKE '%".$search."%')"; } if ($event_type != '') { // If normal, warning, could be several (going_up_warning, going_down_warning... too complex - // for the user so for him is presented only "warning, critical and normal" + // Shown to user only "warning, critical and normal". if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { - $sql_post .= " AND event_type LIKE '%$event_type%' "; + $sql_post .= " AND event_type LIKE '%".$event_type."%' "; } else if ($event_type == 'not_normal') { $sql_post .= " AND (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; } else if ($event_type != 'all') { @@ -3950,23 +4376,25 @@ function events_sql_events_grouped_agents( break; default: - $sql_post .= " AND criticity = $severity"; + $sql_post .= ' AND criticity = '.$severity; break; } } - // In metaconsole mode the agent search is performed by name + // In metaconsole mode the agent search is performed by name. if ($meta) { if ($id_agent != __('All')) { - $sql_post .= " AND agent_name LIKE '%$id_agent%'"; + $sql_post .= " AND agent_name LIKE '%".$id_agent."%'"; } } else { switch ($id_agent) { case 0: + // Ignore. + $__invalid_value = 1; break; case -1: - // Agent doesnt exist. No results will returned + // Agent doesnt exist. No results will returned. $sql_post .= ' AND 1 = 0'; break; @@ -3976,14 +4404,13 @@ function events_sql_events_grouped_agents( } } - if ($meta) { - // There is another filter. - } else { + // There is another filter for if ($meta). + if (!$meta) { if (!empty($text_module)) { $sql_post .= " AND id_agentmodule IN ( SELECT id_agente_modulo FROM tagente_modulo - WHERE nombre = '$text_module' + WHERE nombre = '".$text_module."' )"; } } @@ -4017,7 +4444,7 @@ function events_sql_events_grouped_agents( } } - // Search by tag + // Search by tag. if (!empty($tag_with) && (io_safe_output($tag_with) != '[]') && (io_safe_output($tag_with) != '["0"]')) { $sql_post .= ' AND ( '; $first = true; @@ -4050,7 +4477,7 @@ function events_sql_events_grouped_agents( $sql_post .= ' ) '; } - // Filter/Only alerts + // Filter/Only alerts. if (isset($filter_only_alert)) { if ($filter_only_alert == 0) { $sql_post .= " AND event_type NOT LIKE '%alert%'"; @@ -4059,7 +4486,7 @@ function events_sql_events_grouped_agents( } } - // Tags ACLS + // Tags ACLS. if ($id_group > 0 && in_array($id_group, array_keys($groups))) { $group_array = (array) $id_group; } else { @@ -4077,12 +4504,12 @@ function events_sql_events_grouped_agents( [], true ); - // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)" + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". if (($tags_acls_condition != ERR_WRONG_PARAMETERS) && ($tags_acls_condition != ERR_ACL) && ($tags_acls_condition != -110000)) { $sql_post .= $tags_acls_condition; } - // Metaconsole fitlers + // Metaconsole filters. if ($meta) { if ($server_id_search) { $sql_post .= ' AND server_id = '.$server_id_search; @@ -4116,29 +4543,40 @@ function events_sql_events_grouped_agents( } +/** + * Retrieve list of events grouped by agents. + * + * @param string $sql SQL. + * + * @return string HTML. + */ function events_list_events_grouped_agents($sql) { global $config; $table = events_get_events_table(is_metaconsole(), $history); - $sql = "select * from $table - LEFT JOIN tagent_secondary_group - ON tagent_secondary_group.id_agent = tevento.id_agente - WHERE $sql"; + $sql = sprintf( + 'SELECT * FROM %s + LEFT JOIN tagent_secondary_group + ON tagent_secondary_group.id_agent = tevento.id_agente + WHERE %s', + $table, + $sql + ); $result = db_get_all_rows_sql($sql); $group_rep = 0; $meta = is_metaconsole(); - // fields that the user has selected to show + // Fields that the user has selected to show. if ($meta) { $show_fields = events_meta_get_custom_fields_user(); } else { $show_fields = explode(',', $config['event_fields']); } - // headers + // Headers. $i = 0; $table = new stdClass(); if (!isset($table->width)) { @@ -4299,7 +4737,7 @@ function events_list_events_grouped_agents($sql) } if ($meta) { - // Get info of the all servers to use it on hash auth + // Get info of the all servers to use it on hash auth. $servers_url_hash = metaconsole_get_servers_url_hash(); $servers = metaconsole_get_servers(); } @@ -4308,7 +4746,7 @@ function events_list_events_grouped_agents($sql) $show_validate_button = false; $idx = 0; - // Arrange data. We already did ACL's in the query + // Arrange data. We already did ACL's in the query. foreach ($result as $event) { $data = []; @@ -4318,16 +4756,16 @@ function events_list_events_grouped_agents($sql) $event['server_name'] = $servers[$event['server_id']]['server_name']; } - // Clean url from events and store in array + // Clean url from events and store in array. $event['clean_tags'] = events_clean_tags($event['tags']); - // First pass along the class of this row + // First pass along the class of this row. $myclass = get_priority_class($event['criticity']); - // print status + // Print status. $estado = $event['estado']; - // Colored box + // Colored box. switch ($estado) { case EVENT_NEW: $img_st = 'images/star.png'; @@ -4343,6 +4781,10 @@ function events_list_events_grouped_agents($sql) $img_st = 'images/hourglass.png'; $title_st = __('Event in process'); break; + + default: + // Ignore. + break; } $i = 0; @@ -4350,7 +4792,7 @@ function events_list_events_grouped_agents($sql) $data[$i] = '#'.$event['id_evento']; $table->cellstyle[count($table->data)][$i] = 'background: #F3F3F3; color: #111 !important;'; - // Pass grouped values in hidden fields to use it from modal window + // Pass grouped values in hidden fields to use it from modal window. if ($group_rep) { $similar_ids = $event['similar_ids']; $timestamp_first = $event['timestamp_rep_min']; @@ -4361,17 +4803,17 @@ function events_list_events_grouped_agents($sql) $timestamp_last = $event['utimestamp']; } - // Store group data to show in extended view + // Store group data to show in extended view. $data[$i] .= html_print_input_hidden('similar_ids_'.$event['id_evento'], $similar_ids, true); $data[$i] .= html_print_input_hidden('timestamp_first_'.$event['id_evento'], $timestamp_first, true); $data[$i] .= html_print_input_hidden('timestamp_last_'.$event['id_evento'], $timestamp_last, true); $data[$i] .= html_print_input_hidden('childrens_ids', json_encode($childrens_ids), true); - // Store server id if is metaconsole. 0 otherwise + // Store server id if is metaconsole. 0 otherwise. if ($meta) { $server_id = $event['server_id']; - // If meta activated, propagate the id of the event on node (source id) + // If meta activated, propagate the id of the event on node (source id). $data[$i] .= html_print_input_hidden('source_id_'.$event['id_evento'], $event['id_source_event'], true); $table->cellclass[count($table->data)][$i] = $myclass; } else { @@ -4385,7 +4827,7 @@ function events_list_events_grouped_agents($sql) } $data[$i] .= html_print_input_hidden('event_rep_'.$event['id_evento'], $event['event_rep'], true); - // Store concat comments to show in extended view + // Store concat comments to show in extended view. $data[$i] .= html_print_input_hidden('user_comment_'.$event['id_evento'], base64_encode($event['user_comment']), true); $i++; @@ -4456,7 +4898,7 @@ function events_list_events_grouped_agents($sql) } if (in_array('evento', $show_fields)) { - // Event description + // Event description. $data[$i] = ''; if ($allow_action) { $data[$i] .= '
'; @@ -4476,7 +4918,7 @@ function events_list_events_grouped_agents($sql) $data[$i] = ''; if ($event['id_agente'] > 0) { - // Agent name + // Agent name. if ($meta) { $agent_link = ''; if (can_user_access_node()) { @@ -4497,7 +4939,7 @@ function events_list_events_grouped_agents($sql) } if (in_array('timestamp', $show_fields)) { - // Time + // Time. $data[$i] = ''; if ($group_rep == 1) { $data[$i] .= ui_print_timestamp($event['timestamp_rep'], true); @@ -4700,6 +5142,10 @@ function events_list_events_grouped_agents($sql) $data[$i] = html_print_image('images/page_white_text.png', true, ['title' => str_replace("\n", '
', io_safe_output($event['unknown_instructions']))]); } break; + + default: + // Ignore. + break; } if (!isset($data[$i])) { @@ -4729,11 +5175,11 @@ function events_list_events_grouped_agents($sql) } if ($i != 0 && $allow_action) { - // Actions + // Actions. $data[$i] = ''; if (!$readonly) { - // Validate event + // Validate event. if (($event['estado'] != 1) && (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EW', $event['clean_tags'], $childrens_ids))) { $show_validate_button = true; $data[$i] .= '
'; @@ -4745,7 +5191,7 @@ function events_list_events_grouped_agents($sql) $data[$i] .= ''; } - // Delete event + // Delete event. if ((tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids) == 1)) { if ($event['estado'] != 2) { $show_delete_button = true; @@ -4784,11 +5230,11 @@ function events_list_events_grouped_agents($sql) if (!$readonly) { if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids) == 1) { - // Checkbox - // Class 'candeleted' must be the fist class to be parsed from javascript. Dont change + // Checkbox. + // Class 'candeleted' must be the fist class to be parsed from javascript. Dont change. $data[$i] = html_print_checkbox_extended('validate_ids[]', $event['id_evento'], false, false, false, 'class="candeleted chk_val"', true); } else if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EW', $event['clean_tags'], $childrens_ids) == 1) { - // Checkbox + // Checkbox. $data[$i] = html_print_checkbox_extended('validate_ids[]', $event['id_evento'], false, false, false, 'class="chk_val"', true); } else if (isset($table->header[$i]) || true) { $data[$i] = ''; @@ -4807,6 +5253,15 @@ function events_list_events_grouped_agents($sql) } +/** + * Retrieves SQL for custom order. + * + * @param string $sort_field Field. + * @param string $sort Order. + * @param integer $group_rep Group field. + * + * @return string SQL. + */ function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep=0) { $sort_field_translated = $sort_field; @@ -4854,18 +5309,22 @@ function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep= case 'extra_id': $sort_field_translated = 'id_extra'; break; + + default: + // Ignore. + break; } $dir = ($sort == 'up') ? 'ASC' : 'DESC'; - return "ORDER BY $sort_field_translated $dir"; + return 'ORDER BY '.$sort_field_translated.' '.$dir; } /** - * SQL left join of event queries to handle secondary groups + * SQL left join of event queries to handle secondary groups. * - * @param string Table to see if is metaconsole or not + * @param string $table Table to use based on environment. * * @return string With the query. */ From d5d58e5b2bb195d0c9f6d25fd9729d35bb63ed0e Mon Sep 17 00:00:00 2001 From: Fermin Date: Fri, 8 Feb 2019 18:53:28 +0100 Subject: [PATCH 073/249] Added outter shadow to notifications messages box Former-commit-id: 1eed4b4f2ef7d58dbab73ccb2628bb0ef9ffc7ca --- pandora_console/general/header.php | 26 ++++++++++--------- .../include/functions_notifications.php | 11 ++++++-- pandora_console/include/styles/pandora.css | 13 ++++++++-- 3 files changed, 34 insertions(+), 16 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index 7e84247c50..1413cc12e1 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -386,23 +386,25 @@ config_check(); ?> function addNotifications(event) { - var elements = document.getElementsByClassName("notification-wrapper"); - if (!elements) return; - Array.prototype.forEach.call(elements, function(elem) { - toggle_element(elem); - }); + var element = document.getElementById("notification-content"); + if (!element) return; + element.style.display = "block"; attatch_to_image(); } function attatch_to_image() { - var notification_elems = document.getElementsByClassName("notification-wrapper"); - var image_attached = document.getElementById("notification-ball-header").getBoundingClientRect().left; - Array.prototype.forEach.call(notification_elems, function(elem) { - elem.style.left = image_attached - 300 + "px"; - }); + var notification_elem = document.getElementById("notification-wrapper"); + var image_attached = + document.getElementById("notification-ball-header") + .getBoundingClientRect() + .left + ; + notification_elem.style.left = image_attached - 300 + "px"; } - function toggle_element(elem) { - elem.style.display = elem.style.display === "none" ? "block" : "none"; + + function notifications_hide() { + var element = document.getElementById("notification-content"); + element.style.display = "none" } // Resize event diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index ad3e8953ad..be11a4df72 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -831,8 +831,15 @@ function notifications_print_dropdown() } return sprintf( - ""; +} + + +function install_step3() +{ + $options = ''; + if (extension_loaded('mysql')) { + $options .= ""; + } + + if (extension_loaded('mysqli')) { + $options .= ""; + } + + $error = false; + if (empty($options)) { + $error = true; + } + + echo " +
+
+ ".print_logo_status(4, 6)." +
+

Environment and database setup

+

+ This wizard will create your Pandora FMS database, + and populate it with all the data needed to run for the first time. +

+

+ You need a privileged user to create database schema, this is usually root user. + Information about root user will not be used or stored anymore. +

+

+ You can also deploy the scheme into an existing Database. + In this case you need a privileged Database user and password of that instance. +

+

+ Now, please, complete all details to configure your database and environment setup. +

+
+ Warning: This installer will overwrite and destroy your existing + Pandora FMS configuration and Database. Before continue, + please be sure that you have no valuable Pandora FMS data in your Database. +

+
"; + + if (extension_loaded('oci8')) { + echo "
For Oracle installation an existing Database with a privileged user is needed.
"; + } + + if (!$error) { + echo ""; + } + + echo ""; + echo '"; + + // the field dbgrant is only shown when the DB host is different from 127.0.0.1 or localhost + echo " + + "; + + echo " "; + + echo ""; + echo '
'; + echo 'DB Engine
'; + + if ($error) { + echo " +
+ Warning: You haven't a any DB engine with PHP. Please check the previous step to DB engine dependencies. +
"; + } else { + echo "'; + + echo '
'; + echo ' Installation in
'; + echo "'; + } + + echo "
DB User with privileges
+ + +
DB Password for this user
+ + +
DB Hostname
+ + +
DB Name (pandora by default)
+ + +
Drop Database if exists
+ +
Full path to HTTP publication directory
+ For example /var/www/pandora_console/ +
+ + +
'; + echo "URL path to Pandora FMS Console
+ For example '/pandora_console' +
+ +
+ "; + + if (!$error) { + echo "
"; + echo " + "; + echo '
'; + ?> + + '; + + echo ''; + + echo "
"; + echo "
+
+ Pandora FMS is an OpenSource Software project registered at + SourceForge +
+
"; +} + + +function install_step4() +{ + $pandora_config = 'include/config.php'; + + if ((! isset($_POST['user'])) || (! isset($_POST['dbname'])) || (! isset($_POST['host'])) + || (! isset($_POST['pass'])) || (!isset($_POST['engine'])) || (! isset($_POST['db_action'])) + ) { + $dbpassword = ''; + $dbuser = ''; + $dbhost = ''; + $dbname = ''; + $engine = ''; + $dbaction = ''; + $dbgrant = ''; + } else { + $engine = $_POST['engine']; + $dbpassword = $_POST['pass']; + $dbuser = $_POST['user']; + $dbhost = $_POST['host']; + $dbaction = $_POST['db_action']; + if (isset($_POST['dbgrant']) && $_POST['dbgrant'] != '') { + $dbgrant = $_POST['dbgrant']; + } else { + $dbgrant = $_SERVER['SERVER_ADDR']; + } + + if (isset($_POST['drop'])) { + $dbdrop = $_POST['drop']; + } else { + $dbdrop = 0; + } + + $dbname = $_POST['dbname']; + if (isset($_POST['url'])) { + $url = $_POST['url']; + } else { + $url = 'http://localhost'; + } + + if (isset($_POST['path'])) { + $path = $_POST['path']; + $path = str_replace('\\', '/', $path); + // Windows compatibility + } else { + $path = '/var/www'; + } + } + + $everything_ok = 0; + $step1 = 0; + $step2 = 0; + $step3 = 0; + $step4 = 0; + $step5 = 0; + $step6 = 0; + $step7 = 0; + + echo " +
+
+ ".print_logo_status(5, 6)." +
+

Creating database and default configuration file

+ "; + switch ($engine) { + case 'mysql': + if (! mysql_connect($dbhost, $dbuser, $dbpassword)) { + check_generic(0, 'Connection with Database'); + } else { + check_generic(1, 'Connection with Database'); + + // Drop database if needed and don't want to install over an existing DB + if ($dbdrop == 1) { + mysql_query("DROP DATABASE IF EXISTS `$dbname`"); + } + + // Create schema + if ($dbaction == 'db_new' || $dbdrop == 1) { + $step1 = mysql_query("CREATE DATABASE `$dbname`"); + check_generic($step1, "Creating database '$dbname'"); + } else { + $step1 = 1; + } + + if ($step1 == 1) { + $step2 = mysql_select_db($dbname); + check_generic($step2, "Opening database '$dbname'"); + + $step3 = parse_mysql_dump('pandoradb.sql'); + check_generic($step3, 'Creating schema'); + + $step4 = parse_mysql_dump('pandoradb_data.sql'); + check_generic($step4, 'Populating database'); + if (PHP_OS == 'FreeBSD') { + $step_freebsd = adjust_paths_for_freebsd($engine); + check_generic($step_freebsd, 'Adjusting paths in database for FreeBSD'); + } + + $random_password = random_name(8); + $host = $dbhost; + // set default granted origin to the origin of the queries + if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) { + $host = $dbgrant; + // if the granted origin is different from local machine, set the valid origin + } + + $step5 = mysql_query( + "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host + IDENTIFIED BY '".$random_password."'" + ); + mysql_query('FLUSH PRIVILEGES'); + check_generic($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
"); + + $step6 = is_writable('include'); + check_generic($step6, "Write permissions to save config file in './include'"); + + $cfgin = fopen('include/config.inc.php', 'r'); + $cfgout = fopen($pandora_config, 'w'); + $config_contents = fread($cfgin, filesize('include/config.inc.php')); + $dbtype = 'mysql'; + $config_new = ''; + $step7 = fputs($cfgout, $config_new); + $step7 = ($step7 + fputs($cfgout, $config_contents)); + if ($step7 > 0) { + $step7 = 1; + } + + fclose($cfgin); + fclose($cfgout); + chmod($pandora_config, 0600); + check_generic($step7, "Created new config file at '".$pandora_config."'"); + } + } + + if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { + $everything_ok = 1; + } + break; + + case 'mysqli': + $connection = mysqli_connect($dbhost, $dbuser, $dbpassword); + if (mysqli_connect_error() > 0) { + check_generic(0, 'Connection with Database'); + } else { + check_generic(1, 'Connection with Database'); + + // Drop database if needed and don't want to install over an existing DB + if ($dbdrop == 1) { + mysqli_query($connection, "DROP DATABASE IF EXISTS `$dbname`"); + } + + // Create schema + if ($dbaction == 'db_new' || $dbdrop == 1) { + $step1 = mysqli_query($connection, "CREATE DATABASE `$dbname`"); + check_generic($step1, "Creating database '$dbname'"); + } else { + $step1 = 1; + } + + if ($step1 == 1) { + $step2 = mysqli_select_db($connection, $dbname); + check_generic($step2, "Opening database '$dbname'"); + + $step3 = parse_mysqli_dump($connection, 'pandoradb.sql'); + check_generic($step3, 'Creating schema'); + + $step4 = parse_mysqli_dump($connection, 'pandoradb_data.sql'); + check_generic($step4, 'Populating database'); + if (PHP_OS == 'FreeBSD') { + $step_freebsd = adjust_paths_for_freebsd($engine, $connection); + check_generic($step_freebsd, 'Adjusting paths in database for FreeBSD'); + } + + $random_password = random_name(8); + $host = $dbhost; + // set default granted origin to the origin of the queries + if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) { + $host = $dbgrant; + // if the granted origin is different from local machine, set the valid origin + } + + $step5 = mysqli_query( + $connection, + "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host + IDENTIFIED BY '".$random_password."'" + ); + mysqli_query($connection, 'FLUSH PRIVILEGES'); + check_generic($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
"); + + $step6 = is_writable('include'); + check_generic($step6, "Write permissions to save config file in './include'"); + + $cfgin = fopen('include/config.inc.php', 'r'); + $cfgout = fopen($pandora_config, 'w'); + $config_contents = fread($cfgin, filesize('include/config.inc.php')); + $dbtype = 'mysql'; + $config_new = ''; + $step7 = fputs($cfgout, $config_new); + $step7 = ($step7 + fputs($cfgout, $config_contents)); + if ($step7 > 0) { + $step7 = 1; + } + + fclose($cfgin); + fclose($cfgout); + chmod($pandora_config, 0600); + check_generic($step7, "Created new config file at '".$pandora_config."'"); + } + } + + if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { + $everything_ok = 1; + } + break; + } + + echo '
'; + + if ($everything_ok == 1) { + echo "
"; + echo " + "; + echo '
'; + } else { + $info = "
There were some problems. + Installation was not completed. +

Please correct failures before trying again. + All database "; + if ($engine == 'oracle') { + $info .= 'objects '; + } else { + $info .= 'schemes '; + } + + $info .= 'created in this step have been dropped.

+
'; + echo $info; + + switch ($engine) { + case 'mysql': + if (mysql_error() != '') { + echo "
ERROR: ".mysql_error().'.
'; + } + + if ($step1 == 1) { + mysql_query("DROP DATABASE $dbname"); + } + break; + + case 'mysqli': + if (mysqli_error($connection) != '') { + echo "
ERROR: ".mysqli_error($connection).'.
'; + } + + if ($step1 == 1) { + mysqli_query($connection, "DROP DATABASE $dbname"); + } + break; + } + + echo '
'; + } + + echo '
'; + echo "
"; + echo " +
+
+ Pandora FMS is an Open Source Software project registered at + SourceForge +
+
"; +} + + +function install_step5() +{ + echo " +
+
+ ".print_logo_status(6, 6)." +
+

Installation complete

+

For security, you now must manually delete this installer + ('install.php') file before trying to access to your Pandora FMS console. +

You should also install Pandora FMS Servers before trying to monitor anything; + please read documentation on how to install it.

+

Default user is 'admin' with password 'pandora', + please change it both as soon as possible.

+

Don't forget to check http://pandorafms.com + for updates. +

Select if you want to rename 'install.php'.

+
+ + +
+


. +

+
"; + + echo "
+
+ Pandora FMS is an OpenSource Software project registered at + SourceForge +
+
"; +} From 36dd59b2502182c58e96a4095860f3cec12fae9a Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 12 Feb 2019 13:29:43 +0100 Subject: [PATCH 093/249] Added changes without delete install.php Former-commit-id: 686b0dc8e519283508f8f83ff663f6d3b79e7b80 --- pandora_console/godmode/menu.php | 3 + pandora_console/godmode/setup/setup.php | 15 +++++ .../include/functions_notifications.php | 59 +++++++++++++++++++ 3 files changed, 77 insertions(+) diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index 69ec49cfce..107cf7febd 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -269,6 +269,9 @@ if (check_acl($config['id_user'], 0, 'PM')) { $sub2['godmode/setup/setup&section=ehorus']['text'] = __('eHorus'); $sub2['godmode/setup/setup&section=ehorus']['refr'] = 0; + $sub2['godmode/setup/setup&section=notifications']['text'] = __('Notifications'); + $sub2['godmode/setup/setup&section=notifications']['refr'] = 0; + if ($config['activate_gis']) { $sub2['godmode/setup/gis']['text'] = __('Map conections GIS'); } diff --git a/pandora_console/godmode/setup/setup.php b/pandora_console/godmode/setup/setup.php index f5f229ddd5..ebfc11493f 100644 --- a/pandora_console/godmode/setup/setup.php +++ b/pandora_console/godmode/setup/setup.php @@ -107,6 +107,12 @@ $buttons['ehorus'] = [ 'text' => ''.html_print_image('images/ehorus/ehorus.png', true, ['title' => __('eHorus')]).'', ]; +// FIXME: Not definitive icon +$buttons['notifications'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/alerts_template.png', true, ['title' => __('Notifications')]).'', +]; + $help_header = ''; if (enterprise_installed()) { $subpage = setup_enterprise_add_subsection_main($section, $buttons, $help_header); @@ -143,6 +149,11 @@ switch ($section) { $buttons['ehorus']['active'] = true; $subpage = ' » '.__('eHorus'); break; + + case 'notifications': + $buttons['notifications']['active'] = true; + $subpage = ' » '.__('Notifications'); + break; } // Header @@ -183,6 +194,10 @@ switch ($section) { include_once $config['homedir'].'/godmode/setup/setup_ehorus.php'; break; + case 'notifications': + include_once $config['homedir'].'/godmode/setup/setup_notifications.php'; + break; + default: enterprise_hook('setup_enterprise_select_tab', [$section]); break; diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index cebbc1f5b5..9af36f4c00 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -156,6 +156,65 @@ function check_notification_readable(int $id_message) } +/** + * Returns the target users and groups assigned to be notified on + * desired source. + * + * @param integer $id_source + * + * @return array [users] and [groups] with the targets. + */ +function get_notification_source_targets(int $id_source) +{ + $ret = []; + + $users = db_get_all_rows_sql( + sprintf( + 'SELECT + id_user, + IF(ns.user_editable = 1,nsu.also_mail,ns.also_mail) AS also_mail + FROM tnotification_source_user nsu + INNER JOIN tnotification_source ns + ON ns.id=nsu.id_source + WHERE ns.id = %d + AND ((ns.enabled is NULL OR ns.enabled != 0) + OR (nsu.enabled is NULL OR nsu.enabled != 0))', + $id_source + ) + ); + + if ($users !== false) { + $i = 0; + foreach ($users as $user) { + $ret['users'][$i]['id_user'] = $user['id_user']; + $ret['users'][$i++]['also_mail'] = $user['also_mail']; + } + } + + $groups = db_get_all_rows_sql( + sprintf( + 'SELECT id_group,ns.also_mail + FROM tnotification_source_group nsg + INNER JOIN tnotification_source ns + ON ns.id=nsg.id_source + WHERE ns.id = %d + AND (ns.enabled is NULL OR ns.enabled != 0)', + $id_source + ) + ); + + if ($groups !== false) { + $i = 0; + foreach ($groups as $group) { + $ret['groups'][$i]['id_group'] = $group['id_group']; + $ret['groups'][$i++]['also_mail'] = $group['also_mail']; + } + } + + return $ret; +} + + /** * Return all info from tnotification_source * From 27da41c7dabc362652b832bd895d7f5dcbca27dc Mon Sep 17 00:00:00 2001 From: manuel Date: Tue, 12 Feb 2019 14:39:01 +0100 Subject: [PATCH 094/249] WIP Host&devices Former-commit-id: cc18e55a30f72c606bb5b5736a5fa771987e0a45 --- pandora_console/godmode/menu.php | 7 + pandora_console/godmode/servers/discovery.php | 67 ++ .../godmode/wizards/HostDevices.class.php | 835 ++++++++++++++++++ .../godmode/wizards/Wizard.interface.php | 16 + .../godmode/wizards/hostDevices.png | Bin 0 -> 5251 bytes pandora_console/godmode/wizards/index.php | 7 + 6 files changed, 932 insertions(+) create mode 100755 pandora_console/godmode/servers/discovery.php create mode 100755 pandora_console/godmode/wizards/HostDevices.class.php create mode 100755 pandora_console/godmode/wizards/Wizard.interface.php create mode 100755 pandora_console/godmode/wizards/hostDevices.png create mode 100755 pandora_console/godmode/wizards/index.php diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index 69ec49cfce..7722463c65 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -200,11 +200,18 @@ if (check_acl($config['id_user'], 0, 'AW') || check_acl($config['id_user'], 0, ' $menu_godmode['gservers']['id'] = 'god-servers'; $sub = []; + if (check_acl($config['id_user'], 0, 'PM')) { + $sub['godmode/servers/discovery']['text'] = __('Discover'); + $sub['godmode/servers/discovery']['id'] = 'Discover'; + } + if (check_acl($config['id_user'], 0, 'AW')) { $sub['godmode/servers/modificar_server']['text'] = __('Manage servers'); $sub['godmode/servers/modificar_server']['id'] = 'Manage servers'; } + + // This subtabs are only for Pandora Admin if (check_acl($config['id_user'], 0, 'PM')) { enterprise_hook('ha_cluster'); diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php new file mode 100755 index 0000000000..557b7bf5b3 --- /dev/null +++ b/pandora_console/godmode/servers/discovery.php @@ -0,0 +1,67 @@ +run(); + // TODO: Here we'll controlle if return is a valid recon task id. + exit(); +} + +if ($classname_selected === null) { + // Load classes and print selector. + echo '
    '; + foreach ($classes as $classpath) { + $classname = basename($classpath, '.class.php'); + $obj = new $classname(); + $wiz_data = $obj->load(); + + hd($wiz_data); + ?> +
  • + + <?php echo $classname; ?> +
    +
    +
  • + + '; +} diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php new file mode 100755 index 0000000000..b41788f344 --- /dev/null +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -0,0 +1,835 @@ +id = null; + $this->msg = $msg; + $this->icon = $icon; + $this->label = $label; + $this->page = $page; + $this->url = ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=hd' + ); + + return $this; + } + + + /** + * Undocumented function + * + * @return void + */ + public function run() + { + global $config; + $mode = get_parameter('mode', null); + + if ($mode === null) { + echo 'Importar csv'; + echo 'Escanear red'; + return; + } + + if ($mode == 'importcsv') { + return $this->runCSV(); + } + + if ($mode == 'netscan') { + return $this->runNetScan(); + } + + return null; + } + + + /** + * Checks if environment is ready, + * returns array + * icon: icon to be displayed + * label: label to be displayed + * + * @return array With data. + **/ + public function load() + { + return [ + 'icon' => $this->icon, + 'label' => $this->label, + 'url' => $this->url, + ]; + } + + + // extra methods + + + /** + * Undocumented function + * + * @return void + */ + public function runCSV() + { + global $config; + echo 'formulario csv'; + if (isset($this->page) === false || $this->page === 0) { + $this->page = 0; + + $test = get_parameter('test', null); + + // Check user answers. + if ($test !== null) { + // $this->process_page_0($respuestas_usuario) + $this->page++; + header( + 'Location: '.$this->url.'&page='.$this->page + ); + } else { + // Mostrar pagina 0. + echo 'Aqui vamos a empezar a construir el formulario.'; + ?> +
    + +
    + page == 1) { + // Code... + $this->page++; + return; + header('Location: index.php?class=HostDevices&page='.$this->page); + } else if ($this->page == 2) { + // Code... + $this->page++; + header('Location: index.php?class=HostDevices&page='.$this->page); + } else if ($this->page == 3) { + // Code... + $this->page++; + header('Location: /XXX/discovery/index.php?class=HostDevices&page='.$this->page); + } + + // Page 4, last. + return [ + 'result' => $this->result, + 'id' => $this->id, + 'msg' => $this->msg, + ]; + + } + + + /** + * Undocumented function + * + * @return void + */ + public function runNetScan() + { + global $config; + + echo 'formulario netscan'; + check_login(); + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + return; + } + + include_once $config['homedir'].'/include/functions_users.php'; + + $user_groups = users_get_groups(false, 'AW', true, false, null, 'id_grupo'); + $user_groups = array_keys($user_groups); + + if (is_ajax()) { + $get_explanation = (bool) get_parameter('get_explanation', 0); + + if ($get_explanation) { + $id = (int) get_parameter('id', 0); + + $explanation = db_get_value('description', 'trecon_script', 'id_recon_script', $id); + + echo io_safe_output($explanation); + + return; + } + + $get_recon_script_macros = get_parameter('get_recon_script_macros'); + if ($get_recon_script_macros) { + $id_recon_script = (int) get_parameter('id'); + $id_recon_task = (int) get_parameter('id_rt'); + + if (!empty($id_recon_task) && empty($id_recon_script)) { + $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); + } else if (!empty($id_recon_task)) { + $recon_task_id_rs = (int) db_get_value('id_recon_script', 'trecon_task', 'id_rt', $id_recon_task); + + if ($id_recon_script == $recon_task_id_rs) { + $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); + } else { + $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); + } + } else if (!empty($id_recon_script)) { + $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); + } else { + $recon_script_macros = []; + } + + $macros = []; + $macros['base64'] = base64_encode($recon_script_macros); + $macros['array'] = json_decode($recon_script_macros, true); + + echo io_json_mb_encode($macros); + return; + } + + return; + } + + // Edit mode. + if (isset($_GET['update']) || (isset($_GET['upd']))) { + $update_recon = true; + if (isset($_GET['upd'])) { + if ($_GET['upd'] != 'update') { + $update_recon = false; + } else { + $id_rt = get_parameter('upd'); + } + } + + if ($update_recon) { + if (!isset($id_rt)) { + $id_rt = (int) get_parameter_get('update'); + } + + $row = db_get_row('trecon_task', 'id_rt', $id_rt); + $name = $row['name']; + $network = $row['subnet']; + $id_recon_server = $row['id_recon_server']; + $description = $row['description']; + $interval = $row['interval_sweep']; + $id_group = $row['id_group']; + $create_incident = $row['create_incident']; + $id_network_profile = $row['id_network_profile']; + $id_os = $row['id_os']; + $recon_ports = $row['recon_ports']; + $snmp_community = $row['snmp_community']; + $snmp_version = $row['snmp_version']; + $snmp3_auth_user = $row['snmp_auth_user']; + $snmp3_auth_pass = $row['snmp_auth_pass']; + $snmp3_privacy_method = $row['snmp_privacy_method']; + $snmp3_privacy_pass = $row['snmp_privacy_pass']; + $snmp3_auth_method = $row['snmp_auth_method']; + $snmp3_security_level = $row['snmp_security_level']; + $id_recon_script = $row['id_recon_script']; + $field1 = $row['field1']; + $field2 = $row['field2']; + $field3 = $row['field3']; + $field4 = $row['field4']; + if ($id_recon_script == 0) { + $mode = 'network_sweep'; + } else { + $mode = 'recon_script'; + } + + $os_detect = $row['os_detect']; + $resolve_names = $row['resolve_names']; + $os_detect = $row['os_detect']; + $parent_detection = $row['parent_detection']; + $parent_recursion = $row['parent_recursion']; + $macros = $row['macros']; + $alias_as_name = $row['alias_as_name']; + $snmp_enabled = $row['snmp_enabled']; + $vlan_enabled = $row['vlan_enabled']; + + $name_script = db_get_value( + 'name', + 'trecon_script', + 'id_recon_script', + $id_recon_script + ); + + if (! in_array($id_group, $user_groups)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Recon Task Management' + ); + include 'general/noaccess.php'; + return; + } + } + } else if (isset($_GET['create']) || isset($_GET['crt'])) { + $create_recon = true; + if (isset($_GET['crt'])) { + if ($_GET['crt'] != 'Create') { + $create_recon = false; + } + } + + if ($create_recon) { + $id_rt = -1; + $name = get_parameter('name'); + $network = get_parameter('network'); + $description = get_parameter('description'); + $id_recon_server = 0; + $interval = 0; + $id_group = 0; + $create_incident = 1; + $snmp_community = 'public'; + $snmp3_auth_user = ''; + $snmp3_auth_pass = ''; + $snmp_version = 1; + $snmp3_privacy_method = ''; + $snmp3_privacy_pass = ''; + $snmp3_auth_method = ''; + $snmp3_security_level = ''; + $id_network_profile = 0; + $id_os = -1; + // Any + $recon_ports = ''; + // Any + $field1 = ''; + $field2 = ''; + $field3 = ''; + $field4 = ''; + $id_recon_script = 0; + $mode = 'network_sweep'; + $os_detect = 0; + $resolve_names = 0; + $parent_detection = 1; + $parent_recursion = 5; + $macros = ''; + $alias_as_name = 0; + $snmp_enabled = 0; + $vlan_enabled = 0; + } + + $modify = false; + if (($name != '') || ($network != '')) { + $modify = true; + } + } + + $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; + if ($is_windows) { + echo '
    '; + echo __('Warning').': '.__('By default, in Windows, %s only support Standard network sweep, not custom scripts', get_product_name()); + echo '
    '; + } + + $table = new stdClass(); + $table->id = 'table_recon'; + $table->width = '100%'; + $table->cellspacing = 4; + $table->cellpadding = 4; + $table->class = 'databox filters'; + + $table->rowclass[3] = 'network_sweep'; + $table->rowclass[5] = 'network_sweep'; + $table->rowclass[7] = 'network_sweep'; + $table->rowclass[8] = 'network_sweep'; + $table->rowclass[11] = 'network_sweep'; + $table->rowclass[12] = 'network_sweep'; + $table->rowclass[18] = 'network_sweep'; + $table->rowclass[19] = 'network_sweep'; + $table->rowclass[20] = 'network_sweep'; + $table->rowclass[21] = 'network_sweep'; + $table->rowclass[22] = 'network_sweep'; + $table->rowclass[23] = 'network_sweep'; + $table->rowclass[24] = 'network_sweep'; + $table->rowclass[25] = 'network_sweep recon_v3'; + $table->rowclass[26] = 'network_sweep recon_v3'; + $table->rowclass[27] = 'network_sweep recon_v3'; + $table->rowclass[28] = 'network_sweep recon_v3'; + $table->rowclass[29] = 'network_sweep recon_v3'; + $table->rowclass[30] = 'network_sweep recon_v3'; + + $table->rowclass[6] = 'recon_script'; + $table->rowclass[13] = 'recon_script'; + $table->rowclass[14] = 'recon_script'; + $table->rowclass[15] = 'recon_script'; + $table->rowclass[16] = 'recon_script'; + $table->rowclass[17] = 'recon_script'; + // Name. + $table->data[0][0] = ''.__('Task name').''; + $table->data[0][1] = html_print_input_text('name', $name, '', 25, 0, true); + + // Recon server. + $table->data[1][0] = ''.__('Recon server').ui_print_help_tip( + __('You must select a Recon Server for the Task, otherwise the Recon Task will never run'), + true + ); + + $sql = 'SELECT id_server, name + FROM tserver + WHERE server_type = 3 + ORDER BY name'; + $table->data[1][1] = html_print_select_from_sql($sql, 'id_recon_server', $id_recon_server, '', '', '', true); + + $fields['network_sweep'] = __('Network sweep'); + if (!$is_windows) { + $fields['recon_script'] = __('Custom script'); + } + + $table->data[2][0] = ''.__('Mode').''; + $table->data[2][1] = html_print_select($fields, 'mode', $mode, '', '', 0, true); + + // Network. + $table->data[3][0] = ''.__('Network').''; + $table->data[3][0] .= ui_print_help_tip(__('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'), true); + $table->data[3][1] = html_print_input_text('network', $network, '', 25, 0, true); + + // Interval. + $interv_manual = 0; + if ((int) $interval == 0) { + $interv_manual = 1; + } + + $table->data[4][0] = ''.__('Interval'); + $table->data[4][0] .= ui_print_help_tip(__('Manual interval means that it will be executed only On-demand'), true); + + $values = [ + 0 => __('Defined'), + 1 => __('Manual'), + ]; + $table->data[4][1] = html_print_select($values, 'interval_manual_defined', $interv_manual, '', '', '', true); + + $table->data[4][1] .= ''; + $table->data[4][1] .= html_print_extended_select_for_time('interval', $interval, '', '', '0', false, true, false, false); + $table->data[4][1] .= ui_print_help_tip(__('The minimum recomended interval for Recon Task is 5 minutes'), true); + $table->data[4][1] .= ''; + + // Module template. + $table->data[5][0] = ''.__('Module template').''; + + $sql = 'SELECT id_np, name + FROM tnetwork_profile + ORDER BY name'; + $table->data[5][1] = html_print_select_from_sql($sql, 'id_network_profile', $id_network_profile, '', __('None'), 0, true); + + // Recon script. + $data[1] = ''; + $table->data[6][0] = ''.__('Recon script').''; + + $sql = "SELECT id_recon_script, name + FROM trecon_script + WHERE name <> 'IPAM Recon' + ORDER BY name"; + if ($name_script != 'IPAM Recon') { + $table->data[6][1] = html_print_select_from_sql($sql, 'id_recon_script', $id_recon_script, '', '', '', true); + $table->data[6][1] .= "'; + $table->data[6][1] .= $data[1] .= html_print_input_hidden('macros', base64_encode($macros), true); + } else { + $table->data[6][1] = 'IPAM Recon'; + } + + // OS. + $table->data[7][0] = ''.__('OS').''; + + $sql = 'SELECT id_os, name + FROM tconfig_os + ORDER BY name'; + $table->data[7][1] = html_print_select_from_sql($sql, 'id_os', $id_os, '', __('Any'), -1, true); + + // Recon ports. + $table->data[8][0] = ''.__('Ports').''; + $table->data[8][1] = html_print_input_text('recon_ports', $recon_ports, '', 25, 0, true); + $table->data[8][1] .= ui_print_help_tip( + __('Ports defined like: 80 or 80,443,512 or even 0-1024 (Like Nmap command line format). If dont want to do a sweep using portscan, left it in blank'), + true + ); + + // Group. + $table->data[9][0] = ''.__('Group'); + $groups = users_get_groups(false, 'PM', false); + $table->data[9][1] = html_print_select_groups(false, 'PM', false, 'id_group', $id_group, '', '', 0, true); + + // Incident. + $values = [ + 0 => __('No'), + 1 => __('Yes'), + ]; + $table->data[10][0] = ''.__('Incident'); + $table->data[10][1] = html_print_select( + $values, + 'create_incident', + $create_incident, + '', + '', + '', + true + ).' '.ui_print_help_tip(__('Choose if the discovery of a new system creates an incident or not.'), true); + + // snmp_enabled. + $table->data[11][0] = ''.__('SNMP enabled'); + $table->data[11][1] = html_print_checkbox('snmp_enabled', 1, $snmp_enabled, true); + + // SNMP default community. + $table->data[12][0] = ''.__('SNMP Default community'); + $table->data[12][0] .= ui_print_help_tip(__('You can specify several values, separated by commas, for example: public,mysecret,1234'), true); + $table->data[12][1] = html_print_input_text('snmp_community', $snmp_community, '', 35, 0, true); + + // SNMP version. + $snmp_versions['1'] = 'v. 1'; + $snmp_versions['2'] = 'v. 2'; + $snmp_versions['2c'] = 'v. 2c'; + $snmp_versions['3'] = 'v. 3'; + $table->data[24][0] = ''._('SNMP version'); + $table->data[24][1] = html_print_select($snmp_versions, 'snmp_version', $snmp_version, '', '', 0, true); + + $table->data[25][0] = ''.__('Auth user'); + $table->data[25][1] = html_print_input_text( + 'snmp_auth_user', + $snmp3_auth_user, + '', + 15, + 60, + true, + '', + false, + '', + '' + ); + $table->data[26][0] = ''.__('Auth password').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); + $table->data[26][1] = html_print_input_password( + 'snmp_auth_pass', + $snmp3_auth_pass, + '', + 15, + 60, + true, + '', + false, + '' + ); + $table->data[26][1] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_mmen', true); + + $table->data[27][0] = ''.__('Privacy method'); + $table->data[27][1] = html_print_select(['DES' => __('DES'), 'AES' => __('AES')], 'snmp_privacy_method', $snmp3_privacy_method, '', '', '', true, false, false, '', ''); + $table->data[28][0] = ''.__('Privacy pass').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); + $table->data[28][1] = html_print_input_password( + 'snmp_privacy_pass', + $snmp3_privacy_pass, + '', + 15, + 60, + true, + '', + false, + '' + ); + $table->data[29][0] = ''.__('Auth method'); + $table->data[29][1] = html_print_select(['MD5' => __('MD5'), 'SHA' => __('SHA')], 'snmp_auth_method', $snmp3_auth_method, '', '', '', true, false, false, '', ''); + $table->data[30][0] = ''.__('Security level'); + $table->data[30][1] = html_print_select( + [ + 'noAuthNoPriv' => __('Not auth and not privacy method'), + 'authNoPriv' => __('Auth and not privacy method'), + 'authPriv' => __('Auth and privacy method'), + ], + 'snmp_security_level', + $snmp3_security_level, + '', + '', + '', + true, + false, + false, + '', + '' + ); + + // Explanation. + $explanation = db_get_value('description', 'trecon_script', 'id_recon_script', $id_recon_script); + + $table->data[13][0] = ''.__('Explanation').''; + $table->data[13][1] = "'.html_print_textarea('explanation', 4, 60, $explanation, 'style="width: 388px;"', true); + + // A hidden "model row" to clone it from javascript to add fields dynamicaly. + $data = []; + $data[0] = 'macro_desc'; + $data[0] .= ui_print_help_tip('macro_help', true); + $data[1] = html_print_input_text('macro_name', 'macro_value', '', 100, 255, true); + $table->colspan['macro_field'][1] = 3; + $table->rowstyle['macro_field'] = 'display:none'; + $table->data['macro_field'] = $data; + + // If there are $macros, we create the form fields. + if (!empty($macros)) { + $macros = json_decode($macros, true); + + foreach ($macros as $k => $m) { + $data = []; + $data[0] = ''.$m['desc'].''; + if (!empty($m['help'])) { + $data[0] .= ui_print_help_tip($m['help'], true); + } + + if ($m['hide']) { + $data[1] = html_print_input_password($m['macro'], $m['value'], '', 100, 255, true); + } else { + $data[1] = html_print_input_text($m['macro'], $m['value'], '', 100, 255, true); + } + + $table->colspan['macro'.$m['macro']][1] = 3; + $table->rowclass['macro'.$m['macro']] = 'macro_field'; + + $table->data['macro'.$m['macro']] = $data; + } + } + + // Comments. + $table->data[18][0] = ''.__('Comments'); + $table->data[18][1] = html_print_input_text('description', $description, '', 45, 0, true); + + // OS detection. + $table->data[19][0] = ''.__('OS detection'); + $table->data[19][1] = html_print_checkbox('os_detect', 1, $os_detect, true); + + // Name resolution. + $table->data[20][0] = ''.__('Name resolution'); + $table->data[20][1] = html_print_checkbox('resolve_names', 1, $resolve_names, true); + + // Parent detection. + $table->data[21][0] = ''.__('Parent detection'); + $table->data[21][1] = html_print_checkbox('parent_detection', 1, $parent_detection, true); + + // Parent recursion. + $table->data[22][0] = ''.__('Parent recursion'); + $table->data[22][1] = html_print_input_text('parent_recursion', $parent_recursion, '', 5, 0, true).ui_print_help_tip(__('Maximum number of parent hosts that will be created if parent detection is enabled.'), true); + + // Is vlan_enabled. + $table->data[23][0] = ''.__('Vlan enabled'); + $table->data[23][1] = html_print_checkbox('vlan_enabled', 1, $vlan_enabled, true); + + // Alias as name + // NOTE: The 7.0NG Recon Server will not generate random names, since IP + // address collisions could have other consequences. + // $table->data[22][0] = "".__('Alias as Name'); + // $table->data[22][1] = html_print_checkbox ('alias_as_name', 1, $alias_as_name, true); + // Different Form url if it's a create or if it's a update form. + echo '
    '; + html_print_table($table); + echo '
    '; + + if ($id_rt != -1) { + if ($name_script != 'IPAM Recon') { + html_print_submit_button(__('Update'), 'crt', false, 'class="sub upd"'); + } + } else { + html_print_submit_button(__('Add'), 'crt', false, 'class="sub wand"'); + } + + echo '
    '; + + echo '
    '; + + ui_require_javascript_file('pandora_modules'); + ?> + + $this->result, + 'id' => $this->id, + 'msg' => $this->msg, + ]; + */ + + } + + +} diff --git a/pandora_console/godmode/wizards/Wizard.interface.php b/pandora_console/godmode/wizards/Wizard.interface.php new file mode 100755 index 0000000000..6d1ac73783 --- /dev/null +++ b/pandora_console/godmode/wizards/Wizard.interface.php @@ -0,0 +1,16 @@ +cv-ny18iMfovj7YD0gdX7qp$L z$L6I*IRF66s`^+_-}}>gn*D3=Xxfii3d+Z&C)3d;r(YKNAcVx)JbzgN5gOTamEKKL z+6_TW@Ktekb{=*~sHw*AcNnf4YL4=>Mn$58%kOeCy|2YXV-%Kw<|?A~(Xoqt>?teh z8-A|xpjOB;;I@j(K%-Wl*5LVr)B4%tM!(Wog$Q^|ET~n@NMR8YMaiSA&Id~zK*V9w0|fvW0e_ZthaX7{V;fbp;2AcfxxDl$#Ecqu63Tl9IP@Q!1(&sJM0L8yac_6o{( zcH+WgPQf^_+k?R65_|#Ops~QT)=) zEPW`M`Tv{Ze}zOSi?=%a)C9GIGV(m(%bEqwtx~KpdUk%nqV!;_9Cc$__!3G+O6p?R z#M%(f5O3G<8&6H4s;eILZ5@{a6+AtwJPxwv-uP|PngJCBT6!7WDs%N8ii(JonAN#! z4F)n@rVZW>Cvs_ntt-aor!8BzpKCu%7#|R<7Yl$5;uma9Z(-Yy)fN}P7N zaNV4*P*PJos^0$1#sUZliRC??h5wj&!R~ct zGUN_1HTH@K6{rXdR`$=G8-&as6g+P?4C2JM%+Z;hJ<e;Xo>m7V^<=R4U4D0u-K^ddqpDz)a-;v`tX5`;T_ADv6rt*6-q~ohgY#zZvbOs zVwg7jH(IzRsbf`Mxh+OA{XO(0l|jyxAd}P!3kzv!X+fObOQ4-jBq!7I+S=~%DZe?9 zXdEbT3Dv#h+dvl=Zqg8XER(6dyxgBn8*DXPWbjA>6%pKIiNoQrSm_Qol36ER1@(?; zpu*>p63txQHsM{|_VH=I-R^f~p(IMA_zW*Uzq+R8;u|Y(?}GgNB`a5fI4DQUp!BxcT1-p~tlZ;@IxpjX5X4#ed>vQXs}=jN*EKgkUpRd>#lMod zu{OFp*i()zCC?dgrv;YblCS}ZGNEmO)z#HyR6*1~!BTs!zE^7AF$F7ITU)cRvX%^q zGYi~-s=ADoL1bmkFK(Ecb8>RlCu^2||5ov0X@7y|42irWzA;gyp55OnZRm?ersS!s zsR0!WN=i01HvCS$BO$NMG(LwkSM-!ePd#pUJYJ4@u6%F6EUZkcpKC6XYU25^2l`;g}lyi^hX7@TqOG~Rl;FxV}z@chq)~kV`XJU7LGb)`R zYxA=@2k)e=_J5a?p0Q?L8Ck?5ncJ^8+_=EptuzhUDCRS!_l9J(rHQD}1UdrlMf!+vx9bUBknH)N=y(iqbLzbuP%dLjFz!x_p z4k#Jt4OTz+OZtWmS_oO&S7*EzZZ@`SZJf=ZC*#FxMtZHln1hDX#Z&5;w|*(#(0vm>R>GY5LEV)ApY_B7~Azwf#-hw-g&YWt6NBBc;n{CNwgveqNo5^ z92K521=544+F!yXJQiCIsVPe}61y>+AvqpN7z*|@J$U2s=uLeYca zfxs*GLDMJ7A(I?+CP7ViA2i|+uZ^xlL7>F?GHxOMp%~t7%_z*?G^hiH4|wTO-Tmd6 z>DM?O_zm2Gk~yxoAcP74Y|ELbK(BS8)93iB9;BuTZ9A9?+LK>2LNt_S(a%TZDfMy< z$Bwf?z2qhx^Vo%#X(ZV@%82!>+m;cnW8J@1&VRfPVNpp@t;(yoLRo-4;gXjYonvR; zf1AaIQYb?Iy)riDq^?dFF6aZ=-Ia+{>dEw!J=Q+h!N+`;#yfm^dGMzcAi;&2gI3^J#5yi7u%lXr;T z;RUY@<)D|rY?H%k&|NLQ3T(U^{xZUsSzPXD0UP-(eYg8ra7yjS#62`4wv|Wi9kl=gRWS z%#+T2zuTT``S1U2N3wwPK8;d@JiB|^;*1EmIW!AL%|EY(t#za7Jf_yHBr#Z?$HcDF zB(^GlxT06(M`;;&ZLGe(fU~KmeFG5^T`yJg$Rgw6Ox-z!Y`|vMH0-k|uUUWHnhMaG zb=JH1E-}#ZaO0GSV4?6?eOX#PKl%6IeX;t^_c}3QX<}XDdVB2y`JNn3#UbhEvlB!I zQcaldkl&K82H*zQbQ1ZK)9s?EgTFT)j@ogKS{(OhE*MF5jhLuZ@rks?E4-$}yz=iLA1~zh;>`cUSN5FmyVKCqjAbc&Qhi$La~c(xRvWsG^RhWJih3 zuoefA$0swqz?}Z)$?<3JuO#t&ufIPy2OIVB@RY16=|u1~)m9MEYIWzET^^Sm=5Rvr zM}z$n@8S&&z6fiGtw8V;FBvkFrBJW(-a+4R3BB{i5%jJk<>NahJLW-j#jq#guIMB} zAqXr9`F((GkehH)>k-7QRLLmxGnD5XR^~jwJ-2?42Mn*^bzx_@t$>$vFD0&-xm# zmg?_l-7T>nwjtp9b0}rtFp9+sM`Z*kFpa0iRNLm%oy7qVKu%ZDYL0hkIkQmO)f) zWNG53^x0=K-c?UJgMDDa(W2aqhq%>uVPL?^X`{)!lfkvUYCVtSOcem&MlHRetsyn% zR^j1&irUe{1jSFj?_=V})Ff*%KW}fDL*kI5Y>J?|ML#nOOO2>^fKvPs|K1)11OR}- z*{?+oA$92>P?aEnF&Jiee`(Es{ke#+1bYFdPP#~}U#V~fO+qij`b0C2HF z4rxUaoT|02Fz_dB>m}qM?col?Ky&@y%QC}~67U4-F?Eg8wm+rTPzT8O({_mq5c>!X zEJ3NAf~{f?-)M=04i0Me#j9*2A}CXc>S26y!z}Efrx{?=rOl zp|cuOk!yFlxNP=1hxq68KwieJUXm2&v&jRxVhLZx%z(DYB^F5zA~E!BEm}j%*^JHof^bVM_$kdn}Mj>^WuE&CJ+ZR;0HiK2b_gQCv$-- zEuO-Qeh-}t4BPxUp^2nPr-N!-XX4J$dS+^5B{=<4xur?fX!E%7v{dQo9X0ngM9T}z zcHy<1&m*5nrlx&v+bNSbk!+R`NWJ)Aq3Es@>mjB~>yb~%=GHVwLVrrUKvdSruDnof=5!GS}PQjh9T4lQ5oL=Myq@9ufJqfmh4?>})t} z)+dfwWoBw-dpdRMX)Y8&g^xk-m^!gq%^xlQ&Iy3w0qCao1&&X3Q>1MWav;WzELMOE z_OvZQz-cHWW8DY89X~WBe@uXjBVaNsEZ5uFuym$p$9w)bid}Jg%%@Z!?XgeCH#7(U zqPp|fOlI3{!P6)?740cDDppO#(3;+8!ZpuZTEV!})Iy|D33Y)im@;aIy z-+{S$Dwi){5~*M}G2-S@B=274Xc!y!a#5yb`2DQoZPtwOdU2jMhOdspk}&kUwl{Bn5m*7212Nj!Xh<9sX4 z%hh}OUeoT{&Bo;T0z-cMB8gE$Hom>}G0hS|8nc|=DEFz>Pu;{NB?$i^$TB!Pzn5Kp zRBESt2m6r3&Y%j=*}7&?OqBajF^6uu#b?8~>{wLSCz`1RYtN&bId5@I%@cbuc3>7O ztIU|in6G)QyDZcun<=?KYL__MXyhndEYJ(9e=gK;xIY(otJkhCJESzX`e=*prdqn6 z%VfL3!&TuL{59Kf#@?A_F9-MVQ7I9z8a>VKr>8=rOwK=z^;Y{F4SXDJOfpfm-}cEI z{$}V*zN}7PzjGsuj81`GQJkoVk%>XtUVapNvDBM-jO7zv|3!7Im&;dZfl8G{Xi(&y zZ7Q~7T{%@Wp7lssrTEdl*?S=o_uYkS(P=U!*p-Lz-jpY!M_xk+!>IC8&pP(=a zIqky*q{%46<5Op1DH77dSwTeq83Yp$m+w6JtMwPF?MCy zMMbL~IMLYW`>S3r_{cRPm)l=eE#=-xb7t&_x-08e?UGpLcPKrJtSi{iN`FLLW-Jq`j;%SskT-z=H~RSsN+-n4EaK+%0K9G?^s!JE>IuP`*Sn(E zEMkd<0fNWt<{D1*A44GRU%v!EvUT}Y+|T+G*ihNload(); From 325f5e87755b6e8f69817acd3b054aa369ef1960 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 12 Feb 2019 15:27:14 +0100 Subject: [PATCH 095/249] Added onclik con notification toasts Former-commit-id: 7d0c7a7cc9dacc0e52c7f362a3301ed87a7205d3 --- pandora_console/general/header.php | 58 ++++++++++++++----- .../godmode/setup/setup_notifications.php | 24 ++++++++ .../include/functions_messages.php | 26 ++++++++- 3 files changed, 93 insertions(+), 15 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index 03ccfc4dfc..a6c1630ceb 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -197,7 +197,6 @@ config_check(); if (!isset($_GET['refr'])) { $_GET['refr'] = null; } - $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '".$config['id_user']."'"); $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); @@ -398,8 +397,37 @@ config_check(); } function click_on_notification_toast(event) { - // TODO action. - document.getElementById(event.target.id).remove(); + var match = /notification-toast-id-([0-9]+)/.exec(event.target.id); + if (!match) { + console.error( + "Cannot handle toast click event. Id not valid: ", + event.target.id + ); + return; + } + jQuery.post ("ajax.php", + { + "page" : "godmode/setup/setup_notifications", + "mark_notification_as_read" : 1, + "message": match[1] + }, + function (data, status) { + console.log(data.url) + if (!data.result) { + console.error("Cannot redirect to URL."); + return; + } + window.location.replace(data.url); + document.getElementById(event.target.id).remove(); + }, + "json" + ) + .fail(function(xhr, textStatus, errorThrown){ + console.error( + "Failed onclik event on toast. Error: ", + xhr.responseText + ); + }); } function print_toast(title, subtitle, severity, id, onclick) { @@ -471,17 +499,19 @@ config_check(); ball_wrapper.innerHTML = new_ball; // Add the new toasts. - data.new_notifications.forEach(function(ele) { - toast_wrapper.appendChild( - print_toast( - ele.description, - ele.mensaje, - ele.criticity, - 'notification-toast-id-' + ele.id_mensaje, - 'click_on_notification_toast(event)' - ) - ); - }); + if (Array.isArray(data.new_notifications)) { + data.new_notifications.forEach(function(ele) { + toast_wrapper.appendChild( + print_toast( + ele.description, + ele.mensaje, + ele.criticity, + 'notification-toast-id-' + ele.id_mensaje, + 'click_on_notification_toast(event)' + ) + ); + }); + } }, "json" ) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index ad40926220..3d7c04fb44 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -125,6 +125,30 @@ if (get_parameter('check_new_notifications', 0)) { return; } +if (get_parameter('mark_notification_as_read', 0)) { + hd("asdfe", true); + $message = (int) get_parameter('message', 0); + messages_process_read($message); + // TODO check read. + $url = messages_get_url($message); + hd("asdfe 2" . $url, true); + // Return false if cannot get the URL. + if ($url === false) { + echo json_encode(['result' => false]); + return; + } + hd("asdfe 03", true); + + // If there is new messages, get the info. + echo json_encode( + [ + 'result' => true, + 'url' => $url, + ] + ); + return; +} + // Notification table. It is just a wrapper. $table_content = new StdClass(); $table_content->data = []; diff --git a/pandora_console/include/functions_messages.php b/pandora_console/include/functions_messages.php index 1ecb6dd186..f633866f65 100644 --- a/pandora_console/include/functions_messages.php +++ b/pandora_console/include/functions_messages.php @@ -215,7 +215,6 @@ function messages_process_read( bool $read=true ) { global $config; - // Check if user has grants to read the message. if (check_notification_readable($message_id) === false) { return false; @@ -560,3 +559,28 @@ function messages_get_overview_sent( $order ); } + + +/** + * Get the URL of a message. If field in db is null, it returs a link to + * messages view. + * + * @param integer $message_id Message id to get URL. + * + * @return mixed False if fails. A string with URL otherwise. + */ +function messages_get_url($message_id) +{ + $messages = messages_get_message($message_id); + if ($messages === false) { + return false; + } + + // Return URL stored if is set in database. + if (isset($messages['url'])) { + return $messages['url']; + } + + // Return the message direction. + return ui_get_full_url('index.php?sec=message_list&sec2=operation/messages/message_edit&read_message=1&id_message='.$message_id); +} From 3c3d9daa0967114738f9c992d61b75908d0e206e Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 12 Feb 2019 15:29:28 +0100 Subject: [PATCH 096/249] Removed unwanted traces Former-commit-id: 23e41d90e1ee5d94758c050de942b6f8fb779613 --- pandora_console/general/header.php | 1 - 1 file changed, 1 deletion(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index a6c1630ceb..e9b1133bfe 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -412,7 +412,6 @@ config_check(); "message": match[1] }, function (data, status) { - console.log(data.url) if (!data.result) { console.error("Cannot redirect to URL."); return; From 35ea03ddf62f31183e90b5d3a18cf1669d9f6201 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 12 Feb 2019 15:36:41 +0100 Subject: [PATCH 097/249] Fixed notifications global configuration. Do not disable the multiple selects. Former-commit-id: c5148e3adad63300c2b938a78eb46974cceff761 --- .../include/functions_notifications.php | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 9af36f4c00..3135fbfa16 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -684,8 +684,16 @@ function notifications_print_global_source_configuration($source) // Generate the html for title. $html_selectors = "
    "; - $html_selectors .= notifications_print_source_select_box(notifications_get_user_sources_for_select($source['id']), 'users', $source['id'], $is_group_all); - $html_selectors .= notifications_print_source_select_box($source_groups, 'groups', $source['id'], $is_group_all); + $html_selectors .= notifications_print_source_select_box( + notifications_get_user_sources_for_select($source['id']), + 'users', + $source['id'] + ); + $html_selectors .= notifications_print_source_select_box( + $source_groups, + 'groups', + $source['id'] + ); $html_selectors .= '
    '; // Generate the checkboxes and time select. $html_checkboxes = "
    "; @@ -733,18 +741,16 @@ function notifications_print_global_source_configuration($source) /** * Print select boxes of notified users or groups * - * @param array $info_selec All info required for build the selector. - * @param string $id One of users|groups. - * @param string $source_id Id of source. - * @param boolean $disabled Disable the selectors. + * @param array $info_selec All info required for build the selector. + * @param string $id One of users|groups. + * @param string $source_id Id of source. * * @return string HTML with the generated selector */ function notifications_print_source_select_box( $info_selec, $id, - $source_id, - $disabled + $source_id ) { $title = ($id === 'users') ? __('Notified users') : __('Notified groups'); $add_title = ($id === 'users') ? __('Add users') : __('Add groups'); @@ -774,10 +780,7 @@ function notifications_print_source_select_box( '', '', true, - true, - true, - '', - $disabled + true ), html_print_image( 'images/input_add.png', From 105341e5539ca3002f549bf1e7d41e2234c9b671 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 12 Feb 2019 16:01:24 +0100 Subject: [PATCH 098/249] Removed unwanted traces (again) Former-commit-id: c6453610177b1894bc9d65c8297cd4f8ee01092d --- pandora_console/godmode/setup/setup_notifications.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 3d7c04fb44..489c5666d3 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -126,18 +126,15 @@ if (get_parameter('check_new_notifications', 0)) { } if (get_parameter('mark_notification_as_read', 0)) { - hd("asdfe", true); $message = (int) get_parameter('message', 0); messages_process_read($message); // TODO check read. $url = messages_get_url($message); - hd("asdfe 2" . $url, true); // Return false if cannot get the URL. if ($url === false) { echo json_encode(['result' => false]); return; } - hd("asdfe 03", true); // If there is new messages, get the info. echo json_encode( From cc2b2709f9f10b024ee8738e38ea4641a037c0ed Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 12 Feb 2019 16:25:59 +0100 Subject: [PATCH 099/249] Show the notifications with AJAX Former-commit-id: 73f407d13d3805dce879c1431311a4aaec00c152 --- pandora_console/general/header.php | 43 ++++++++++++++++--- .../godmode/setup/setup_notifications.php | 5 +++ .../include/functions_notifications.php | 17 ++++---- pandora_console/include/styles/pandora.css | 2 + 4 files changed, 52 insertions(+), 15 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index e9b1133bfe..e82f7da221 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -363,6 +363,9 @@ config_check(); + + + - - \ No newline at end of file diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 489c5666d3..c6b6ef7d47 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -146,6 +146,11 @@ if (get_parameter('mark_notification_as_read', 0)) { return; } +if (get_parameter('get_notifications_dropdown', 0)) { + echo notifications_print_dropdown(); + return; +} + // Notification table. It is just a wrapper. $table_content = new StdClass(); $table_content->data = []; diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 3135fbfa16..de0dc46fe9 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -160,7 +160,7 @@ function check_notification_readable(int $id_message) * Returns the target users and groups assigned to be notified on * desired source. * - * @param integer $id_source + * @param integer $id_source Source identificator. * * @return array [users] and [groups] with the targets. */ @@ -635,16 +635,18 @@ function notifications_get_counters() */ function notifications_print_ball($num_notifications, $last_id) { - $class_status = ($num_notifications == 0) ? 'notification-ball-no-messages' : 'notification-ball-new-messages'; + $no_notifications = (int) $num_notifications === 0; + $class_status = ($no_notifications) ? 'notification-ball-no-messages' : 'notification-ball-new-messages'; return sprintf( '
    %s
    ', + ($no_notifications) ? '' : 'onclick="addNotifications(event)"', $class_status, $last_id, $num_notifications @@ -935,16 +937,15 @@ function notifications_print_dropdown() } return sprintf( - " + ", array_reduce( $mess, function ($carry, $message) { diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 0c2fb2e3fe..d479d53268 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4287,10 +4287,12 @@ div#dialog_messages table th:last-child { display: flex; justify-content: center; align-items: center; + cursor: pointer; } .notification-ball-no-messages { background-color: #82b92e; + cursor: inherit; } .notification-ball-new-messages { background-color: #fc4444; From 48724fe033abd191bc27c3c0f92d5a16ed71ebb0 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 12 Feb 2019 16:46:21 +0100 Subject: [PATCH 100/249] Added onclick to notification-item's Former-commit-id: 2e4833686b08b104b11ba9023f6eca38e0ed6bd9 --- pandora_console/general/header.php | 2 +- pandora_console/include/functions_notifications.php | 7 ++++++- pandora_console/include/styles/pandora.css | 3 +++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index e82f7da221..2fd30a73c6 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -423,7 +423,7 @@ config_check(); } function click_on_notification_toast(event) { - var match = /notification-toast-id-([0-9]+)/.exec(event.target.id); + var match = /notification-.*-id-([0-9]+)/.exec(event.target.id); if (!match) { console.error( "Cannot handle toast click event. Id not valid: ", diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index de0dc46fe9..746a3c7ed7 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -967,7 +967,11 @@ function notifications_print_dropdown() function notifications_print_dropdown_element($message_info) { return sprintf( - "
    + "

    @@ -978,6 +982,7 @@ function notifications_print_dropdown_element($message_info)

    ", + $message_info['id_mensaje'], html_print_image('images/'.$message_info['icon'], true), $message_info['description'], $message_info['mensaje'] diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index d479d53268..477fbced3b 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4305,6 +4305,8 @@ div#dialog_messages table th:last-child { position: absolute; width: 400px; margin-top: -5px; + max-height: 78%; + overflow: auto; } #notification-wrapper::before { content: ""; @@ -4341,6 +4343,7 @@ div#dialog_messages table th:last-child { } .notification-item > * { padding-left: 15px; + pointer-events: none; } .notification-info { From 93edda07ee60ccb66dd94593001548af3440f530 Mon Sep 17 00:00:00 2001 From: Daniel Barbero Date: Wed, 13 Feb 2019 07:55:21 +0100 Subject: [PATCH 101/249] fixed errors Former-commit-id: 167c9a725e5dbd4f4ae1db0b6fb6c573a364c122 --- pandora_console/include/functions_html.php | 1 - .../include/functions_reporting_html.php | 403 ++++++++++++++---- 2 files changed, 313 insertions(+), 91 deletions(-) diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 2079c8fbc4..24da558335 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -1851,7 +1851,6 @@ function html_get_predefined_table($model='transparent', $columns=4) * $table->titleclass - Title class * $table->styleTable - Table style * $table->caption - Table title - * $table->pdf_report - Table repeat title conteiner. * @param bool Whether to return an output string or echo now * * @return string HTML code if return parameter is true. diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index d6e20c2105..931d3be94b 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -295,13 +295,7 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) break; case 'sql_graph_vbar': - reporting_html_sql_graph($table, $item); - break; - case 'sql_graph_hbar': - reporting_html_sql_graph($table, $item); - break; - case 'sql_graph_pie': reporting_html_sql_graph($table, $item); break; @@ -1424,7 +1418,16 @@ function reporting_html_inventory($table, $item) } -function reporting_html_agent_module($table, $item, $pdf=0) +/** + * Print in html the agent / module report + * showing the status of these modules. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * + * @return void + */ +function reporting_html_agent_module($table, $item) { $table->colspan['agent_module']['cell'] = 3; $table->cellstyle['agent_module']['cell'] = 'text-align: center;'; @@ -1625,26 +1628,29 @@ function reporting_html_agent_module($table, $item, $pdf=0) $table->data['agent_module']['cell'] = $table_data; } - - if ($pdf !== 0) { - $table->title = $item['title']; - $table->titleclass = 'title_table_pdf'; - $table->titlestyle = 'text-align:left;'; - $return_pdf .= html_print_table( - $table, - true - ); - return $return_pdf; - } } -function reporting_html_exception($table, $item) +/** + * Function to print to HTML Exception report. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * + * @return html + */ +function reporting_html_exception($table, $item, $pdf=0) { + $return_pdf = ''; if (!empty($item['failed'])) { - $table->colspan['group_report']['cell'] = 3; - $table->cellstyle['group_report']['cell'] = 'text-align: center;'; - $table->data['group_report']['cell'] = $item['failed']; + if ($pdf !== 0) { + $return_pdf .= $item['failed']; + } else { + $table->colspan['group_report']['cell'] = 3; + $table->cellstyle['group_report']['cell'] = 'text-align: center;'; + $table->data['group_report']['cell'] = $item['failed']; + } } else { $table1 = new stdClass(); $table1->width = '99%'; @@ -1679,18 +1685,30 @@ function reporting_html_exception($table, $item) $table1->data[] = $row; } - $table->colspan['data']['cell'] = 3; - $table->cellstyle['data']['cell'] = 'text-align: center;'; - $table->data['data']['cell'] = html_print_table($table1, true); + if ($pdf !== 0) { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table($table1, true); + } else { + $table->colspan['data']['cell'] = 3; + $table->cellstyle['data']['cell'] = 'text-align: center;'; + $table->data['data']['cell'] = html_print_table($table1, true); + } if (!empty($item['chart'])) { - $table->colspan['chart_pie']['cell'] = 3; - $table->cellstyle['chart_pie']['cell'] = 'text-align: center;'; - $table->data['chart_pie']['cell'] = $item['chart']['pie']; + if ($pdf !== 0) { + $return_pdf .= $item['chart']['pie']; + $return_pdf .= $item['chart']['hbar']; + } else { + $table->colspan['chart_pie']['cell'] = 3; + $table->cellstyle['chart_pie']['cell'] = 'text-align: center;'; + $table->data['chart_pie']['cell'] = $item['chart']['pie']; - $table->colspan['chart_hbar']['cell'] = 3; - $table->cellstyle['chart_hbar']['cell'] = 'text-align: center;'; - $table->data['chart_hbar']['cell'] = $item['chart']['hbar']; + $table->colspan['chart_hbar']['cell'] = 3; + $table->cellstyle['chart_hbar']['cell'] = 'text-align: center;'; + $table->data['chart_hbar']['cell'] = $item['chart']['hbar']; + } } if (!empty($item['resume'])) { @@ -1719,11 +1737,22 @@ function reporting_html_exception($table, $item) 'max' => $item['resume']['max']['formated_value'], ]; - $table->colspan['resume']['cell'] = 3; - $table->cellstyle['resume']['cell'] = 'text-align: center;'; - $table->data['resume']['cell'] = html_print_table($table1, true); + if ($pdf !== 0) { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table($table1, true); + } else { + $table->colspan['resume']['cell'] = 3; + $table->cellstyle['resume']['cell'] = 'text-align: center;'; + $table->data['resume']['cell'] = html_print_table($table1, true); + } } } + + if ($pdf !== 0) { + return $return_pdf; + } } @@ -1970,7 +1999,16 @@ function reporting_html_event_report_agent($table, $item, $pdf=0) } -function reporting_html_historical_data($table, $item) +/** + * Function to print to HTML historical data report. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * + * @return html + */ +function reporting_html_historical_data($table, $item, $pdf=0) { global $config; @@ -1997,13 +2035,40 @@ function reporting_html_historical_data($table, $item) $table1->data[] = $row; } - $table->colspan['database_serialized']['cell'] = 3; - $table->cellstyle['database_serialized']['cell'] = 'text-align: center;'; - $table->data['database_serialized']['cell'] = html_print_table($table1, true); + if ($pdf === 0) { + $table->colspan['database_serialized']['cell'] = 3; + $table->cellstyle['database_serialized']['cell'] = 'text-align: center;'; + $table->data['database_serialized']['cell'] = html_print_table( + $table1, + true + ); + } else { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + return html_print_table( + $table1, + true + ); + } } -function reporting_html_database_serialized($table, $item) +/** + * It displays an item in the table format report from + * the data stored within the table named 'tagente_datos_stringin' + * the Pandora FMS Database. + * For it, the agent should serialize the data separating + * them with a line-separating character and another + * which separates the fields. All lines should contain all fields. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * + * @return html + */ +function reporting_html_database_serialized($table, $item, $pdf=0) { $table1 = new stdClass(); $table1->width = '100%'; @@ -2023,40 +2088,92 @@ function reporting_html_database_serialized($table, $item) } } - $table->colspan['database_serialized']['cell'] = 3; - $table->cellstyle['database_serialized']['cell'] = 'text-align: center;'; - $table->data['database_serialized']['cell'] = html_print_table($table1, true); + if ($pdf === 0) { + $table->colspan['database_serialized']['cell'] = 3; + $table->cellstyle['database_serialized']['cell'] = 'text-align: center;'; + $table->data['database_serialized']['cell'] = html_print_table( + $table1, + true + ); + } else { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + return html_print_table( + $table1, + true + ); + } } -function reporting_html_group_configuration($table, $item) +/** + * Shows the data of a group and the agents that are part of them. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * + * @return html + */ +function reporting_html_group_configuration($table, $item, $pdf=0) { - $table1 = new stdClass(); - $table1->width = '100%'; - $table1->head = []; - $table1->data = []; $cell = ''; foreach ($item['data'] as $agent) { - $table2 = new stdClass(); - $table2->width = '100%'; - $table2->data = []; - reporting_html_agent_configuration($table2, ['data' => $agent]); - - $cell .= html_print_table($table2, true); + if ($pdf === 0) { + $table2 = new stdClass(); + $table2->width = '100%'; + $table2->data = []; + reporting_html_agent_configuration( + $table2, + ['data' => $agent], + $pdf + ); + $cell .= html_print_table( + $table2, + true + ); + } else { + $cell .= reporting_html_agent_configuration( + false, + ['data' => $agent], + $pdf, + $item['title'] + ); + } } - $table->colspan['group_configuration']['cell'] = 3; - $table->cellstyle['group_configuration']['cell'] = 'text-align: center;'; - $table->data['group_configuration']['cell'] = $cell; + if ($pdf === 0) { + $table->colspan['group_configuration']['cell'] = 3; + $table->cellstyle['group_configuration']['cell'] = 'text-align: center;'; + $table->data['group_configuration']['cell'] = $cell; + } else { + return $cell; + } } -function reporting_html_network_interfaces_report($table, $item, $pdf=false) +/** + * This type of report element will generate the interface graphs + * of all those devices that belong to the selected group. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * + * @return html + */ +function reporting_html_network_interfaces_report($table, $item, $pdf=0) { + $return_pdf = ''; if (!empty($item['failed'])) { - $table->colspan['interfaces']['cell'] = 3; - $table->cellstyle['interfaces']['cell'] = 'text-align: left;'; - $table->data['interfaces']['cell'] = $item['failed']; + if ($pdf === 0) { + $table->colspan['interfaces']['cell'] = 3; + $table->cellstyle['interfaces']['cell'] = 'text-align: left;'; + $table->data['interfaces']['cell'] = $item['failed']; + } else { + $return_pdf .= $item['failed']; + } } else { foreach ($item['data'] as $agent) { $table_agent = new StdCLass(); @@ -2069,9 +2186,6 @@ function reporting_html_network_interfaces_report($table, $item, $pdf=false) $table_agent->style[0] = 'text-align: center'; $table_agent->data['interfaces'] = ''; - if ($pdf) { - $return_pdf .= __('Agent').' '.$agent['agent']; - } foreach ($agent['interfaces'] as $interface) { $table_interface = new StdClass(); @@ -2103,22 +2217,35 @@ function reporting_html_network_interfaces_report($table, $item, $pdf=false) $table_interface->cellstyle['graph'][0] = 'text-align: center;'; } - if ($pdf) { - $table_interface->class = 'table-beauty'; - $return_pdf .= html_print_table($table_interface, true); + if ($pdf !== 0) { + $table_interface->title = $item['title'].' '.__('Agents').': '.$agent['agent']; + $table_interface->titleclass = 'title_table_pdf'; + $table_interface->titlestyle = 'text-align:left;'; + $table_interface->styleTable = 'page-break-inside:avoid;'; + + $return_pdf .= html_print_table( + $table_interface, + true + ); } - $table_agent->data['interfaces'] .= html_print_table($table_interface, true); + $table_agent->data['interfaces'] .= html_print_table( + $table_interface, + true + ); $table_agent->colspan[$interface_name][0] = 3; } $id = uniqid(); $table->colspan[$id][0] = 3; - $table->data[$id] = html_print_table($table_agent, true); + $table->data[$id] = html_print_table( + $table_agent, + true + ); } } - if ($pdf) { + if ($pdf !== 0) { return $return_pdf; } } @@ -2207,6 +2334,19 @@ function reporting_html_alert_report($table, $item, $pdf=0) } +/** + * This type of report element allows custom graphs to be defined + * for use in reports. + * These graphs will be created using SQL code entered by the user. + * This SQL code should always return a variable called "label" + * for the text labels or name of the elements to be displayed + * and a field called "value" to store the numerical value to be represented. + * + * @param object $table Parameters table. + * @param array $item Items data. + * + * @return void + */ function reporting_html_sql_graph($table, $item) { $table->colspan['chart']['cell'] = 3; @@ -2261,10 +2401,23 @@ function reporting_html_prediction_date($table, $item, $mini) } -function reporting_html_agent_configuration(&$table, $item) -{ - $table->colspan['agent']['cell'] = 3; - $table->cellstyle['agent']['cell'] = 'text-align: left;'; +/** + * Shows the data of agents and modules. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * @param string $title Show title pdf. + * + * @return html + */ +function reporting_html_agent_configuration( + $table, + $item, + $pdf=0, + $title='' +) { + $return_pdf = ''; $table1 = new stdClass(); $table1->width = '99%'; @@ -2276,6 +2429,7 @@ function reporting_html_agent_configuration(&$table, $item) $table1->head['description'] = __('Description'); $table1->head['status'] = __('Status'); $table1->data = []; + $row = []; $row['name'] = $item['data']['name']; $row['group'] = $item['data']['group_icon']; @@ -2289,13 +2443,32 @@ function reporting_html_agent_configuration(&$table, $item) } $table1->data[] = $row; - $table->data['agent']['cell'] = html_print_table($table1, true); - $table->colspan['modules']['cell'] = 3; - $table->cellstyle['modules']['cell'] = 'text-align: left;'; + if ($pdf === 0) { + $table->colspan['agent']['cell'] = 3; + $table->cellstyle['agent']['cell'] = 'text-align: left;'; + $table->data['agent']['cell'] = html_print_table( + $table1, + true + ); + } else { + $return_pdf .= html_print_table( + $table1, + true + ); + } + + if ($pdf === 0) { + $table->colspan['modules']['cell'] = 3; + $table->cellstyle['modules']['cell'] = 'text-align: left;'; + } if (empty($item['data']['modules'])) { - $table->data['modules']['cell'] = __('Empty modules'); + if ($pdf === 0) { + $table->data['modules']['cell'] = __('Empty modules'); + } else { + $return_pdf .= __('Empty modules'); + } } else { $table1->width = '99%'; $table1->head = []; @@ -2339,7 +2512,25 @@ function reporting_html_agent_configuration(&$table, $item) $table1->data[] = $row; } - $table->data['modules']['cell'] = html_print_table($table1, true); + if ($pdf === 0) { + $table->data['modules']['cell'] = html_print_table($table1, true); + } else { + if ($title !== '') { + $item['title'] = $title; + } + + $table1->title = $item['title'].' '.__('Agent').': '.$item['data']['name']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table( + $table1, + true + ); + } + } + + if ($pdf !== 0) { + return $return_pdf; } } @@ -2421,9 +2612,10 @@ function reporting_html_value(&$table, $item, $mini, $only_value=false, $check_e * Show a brief analysis in which the variation of the value * of the indicated module is indicated. * - * @param string $table - * @param array $item - * @param integer $pdf + * @param string $table Reference table in pdf a false. + * @param array $item Parameters for item pdf. + * @param boolean $pdf Send pdf. + * * @return html */ function reporting_html_increment($table, $item, $pdf=0) @@ -2437,7 +2629,7 @@ function reporting_html_increment($table, $item, $pdf=0) $table->colspan['error']['cell'] = 3; $table->data['error']['cell'] = $item['data']['message']; } else { - $return_pdf = $item['data']['message']; + $return_pdf .= $item['data']['message']; } } else { $table1 = new stdClass(); @@ -3061,11 +3253,25 @@ function reporting_html_general($table, $item, $pdf=0) } -function reporting_html_sql(&$table, $item) +/** + * Function to print to HTML query sql. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * + * @return html + */ +function reporting_html_sql($table, $item, $pdf=0) { + $return_pdf = ''; if (!$item['correct']) { - $table->colspan['error']['cell'] = 3; - $table->data['error']['cell'] = $item['error']; + if ($pdf === 0) { + $table->colspan['error']['cell'] = 3; + $table->data['error']['cell'] = $item['error']; + } else { + $return_pdf .= $item['error']; + } } else { $first = true; @@ -3074,10 +3280,10 @@ function reporting_html_sql(&$table, $item) $table2->width = '100%'; foreach ($item['data'] as $row) { - if ($first) { + if ($first === true) { $first = false; - // Print the header + // Print the header. foreach ($row as $key => $value) { $table2->head[] = $key; } @@ -3086,9 +3292,26 @@ function reporting_html_sql(&$table, $item) $table2->data[] = $row; } - $table->colspan['data']['cell'] = 3; - $table->cellstyle['data']['cell'] = 'text-align: center;'; - $table->data['data']['cell'] = html_print_table($table2, true); + if ($pdf === 0) { + $table->colspan['data']['cell'] = 3; + $table->cellstyle['data']['cell'] = 'text-align: center;'; + $table->data['data']['cell'] = html_print_table( + $table2, + true + ); + } else { + $table2->title = $item['title']; + $table2->titleclass = 'title_table_pdf'; + $table2->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table( + $table2, + true + ); + } + } + + if ($pdf !== 0) { + return $return_pdf; } } From fe50d6caff48b01a14f5556bb61746c87ed3dd10 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 13 Feb 2019 11:09:15 +0100 Subject: [PATCH 102/249] Open toasts and messages into new window Former-commit-id: ff3d565247225032219d4bbb5fa903bdae7730e8 --- pandora_console/general/header.php | 44 +++++++++++++------ .../godmode/setup/setup_notifications.php | 25 ++++++++--- .../include/functions_notifications.php | 7 ++- pandora_console/include/styles/pandora.css | 4 ++ 4 files changed, 58 insertions(+), 22 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index 2fd30a73c6..a60118e9a8 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -417,13 +417,26 @@ config_check(); notification_elem.style.left = image_attached - 300 + "px"; } + function notifications_clean_ui(action, self_id) { + switch(action) { + case 'item': + // Recalculate the notification ball. + check_new_notifications(); + break; + case 'toast': + // Only remove the toast element. + document.getElementById(self_id).remove(); + break; + } + } + function notifications_hide() { var element = document.getElementById("notification-content"); element.style.display = "none" } function click_on_notification_toast(event) { - var match = /notification-.*-id-([0-9]+)/.exec(event.target.id); + var match = /notification-(.*)-id-([0-9]+)/.exec(event.target.id); if (!match) { console.error( "Cannot handle toast click event. Id not valid: ", @@ -435,15 +448,14 @@ config_check(); { "page" : "godmode/setup/setup_notifications", "mark_notification_as_read" : 1, - "message": match[1] + "message": match[2] }, function (data, status) { if (!data.result) { console.error("Cannot redirect to URL."); return; } - window.location.replace(data.url); - document.getElementById(event.target.id).remove(); + notifications_clean_ui(match[1], event.target.id); }, "json" ) @@ -455,28 +467,34 @@ config_check(); }); } - function print_toast(title, subtitle, severity, id, onclick) { + function print_toast(title, subtitle, severity, url, id, onclick) { // TODO severity. severity = ''; // Start the toast. - var toast = document.createElement('div'); - toast.className = 'snackbar ' + severity; + var toast = document.createElement('a'); toast.setAttribute('onclick', onclick); - toast.id = id; + toast.setAttribute('href', url); + toast.setAttribute('target', '_blank'); // Fill toast. + var toast_div = document.createElement('div'); + toast_div.className = 'snackbar ' + severity; + toast_div.id = id; var toast_title = document.createElement('h3'); var toast_text = document.createElement('p'); toast_title.innerHTML = title; toast_text.innerHTML = subtitle; - toast.appendChild(toast_title); - toast.appendChild(toast_text); + toast_div.appendChild(toast_title); + toast_div.appendChild(toast_text); + toast.appendChild(toast_div); + + console.log(toast); // Show and program the hide event. - toast.className = toast.className + ' show'; + toast_div.className = toast_div.className + ' show'; setTimeout(function(){ - toast.className = toast.className.replace("show", ""); + toast_div.className = toast_div.className.replace("show", ""); }, 8000); return toast; @@ -528,7 +546,6 @@ config_check(); not_drop.removeChild(not_drop.firstChild); } - // Add the new toasts. if (Array.isArray(data.new_notifications)) { data.new_notifications.forEach(function(ele) { @@ -537,6 +554,7 @@ config_check(); ele.description, ele.mensaje, ele.criticity, + ele.full_url, 'notification-toast-id-' + ele.id_mensaje, 'click_on_notification_toast(event)' ) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index c6b6ef7d47..14a29c4bb2 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -102,6 +102,18 @@ if (get_parameter('check_new_notifications', 0)) { return; } + $messages = messages_get_overview( + 'timestamp', + 'ASC', + false, + true, + 0, + ['id_mensaje' => '>'.$last_id_ui] + ); + if ($messages === false) { + $messages = []; + } + // If there is new messages, get the info. echo json_encode( [ @@ -112,13 +124,12 @@ if (get_parameter('check_new_notifications', 0)) { $counters['last_id'] ) ), - 'new_notifications' => messages_get_overview( - 'timestamp', - 'ASC', - false, - true, - 0, - ['id_mensaje' => '>'.$last_id_ui] + 'new_notifications' => array_map( + function ($elem) { + $elem['full_url'] = messages_get_url($elem['id_mensaje']); + return $elem; + }, + $messages ), ] ); diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 746a3c7ed7..6dfcc0615e 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -967,10 +967,12 @@ function notifications_print_dropdown() function notifications_print_dropdown_element($message_info) { return sprintf( - "
    @@ -981,8 +983,9 @@ function notifications_print_dropdown_element($message_info) %s

    -
    ", + ", $message_info['id_mensaje'], + messages_get_url($message_info['id_mensaje']), html_print_image('images/'.$message_info['icon'], true), $message_info['description'], $message_info['mensaje'] diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 477fbced3b..3e6bac9543 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4346,6 +4346,10 @@ div#dialog_messages table th:last-child { pointer-events: none; } +.notification-item:hover { + text-decoration: none; +} + .notification-info { width: 87%; display: flex; From 8be28b5fedd7245f1590a63f52f45d1bf9877e62 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 13 Feb 2019 11:47:33 +0100 Subject: [PATCH 103/249] Removed some header icons (it will be substituted by notifications) Former-commit-id: 29929ee6f9785cf892b3a0afe7779531d5615e6c --- pandora_console/general/header.php | 102 ++--------------------------- 1 file changed, 4 insertions(+), 98 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index a60118e9a8..5cf10bc749 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -57,7 +57,7 @@ config_check(); $table->cellspacing = 0; $table->head = []; $table->data = []; - $table->style[0] = $table->style['clippy'] = $table->style[1] = $table->style[3] = $table->style[4] = $table->style[5] = $table->style[6] = $table->style[8] = $table->style[9] = $table->style['qr'] = $table->style['notifications'] = 'width: 22px; text-align:center; height: 22px; padding-right: 9px;padding-left: 9px;'; + $table->style['clippy'] = $table->style[1] = $table->style[4] = $table->style[5] = $table->style[6] = $table->style[8] = $table->style[9] = $table->style['qr'] = $table->style['notifications'] = 'width: 22px; text-align:center; height: 22px; padding-right: 9px;padding-left: 9px;'; $table->style[7] = 'width: 20px; padding-right: 9px;'; $table->style['searchbar'] = 'width: 180px; min-width: 180px;'; $table->style[11] = 'padding-left: 10px; padding-right: 5px;width: 16px;'; @@ -110,27 +110,6 @@ config_check(); $table->data[0]['searchbar'] = $search_bar; } - // Servers check - $servers = []; - $servers['all'] = (int) db_get_value('COUNT(id_server)', 'tserver'); - $servers['up'] = (int) servers_check_status(); - $servers['down'] = ($servers['all'] - $servers['up']); - if ($servers['up'] == 0) { - // All Servers down or no servers at all - $servers_check_img = html_print_image('images/header_down.png', true, ['alt' => 'cross', 'class' => 'bot', 'title' => __('All systems').': '.__('Down')]); - } else if ($servers['down'] != 0) { - // Some servers down - $servers_check_img = html_print_image('images/header_warning.png', true, ['alt' => 'error', 'class' => 'bot', 'title' => $servers['down'].' '.__('servers down')]); - } else { - // All servers up - $servers_check_img = html_print_image('images/header_ready.png', true, ['alt' => 'ok', 'class' => 'bot', 'title' => __('All systems').': '.__('Ready')]); - } - - unset($servers); - // Since this is the header, we don't like to trickle down variables. - $servers_link_open = ''; - $servers_link_close = ''; - if ($config['show_qr_code_header'] == 0) { $show_qr_code_header = 'display: none;'; } else { @@ -175,12 +154,6 @@ config_check(); ).''; } - - $table->data[0][0] = $servers_link_open.$servers_check_img.$servers_link_close; - - - - // ======= Autorefresh code ============================= $autorefresh_txt = ''; $autorefresh_additional = ''; @@ -255,42 +228,6 @@ config_check(); // ====================================================== $pandora_management = check_acl($config['id_user'], 0, 'PM'); - echo ''; - - if ($config['alert_cnt'] > 0) { - $maintenance_link = 'javascript:'; - $maintenance_title = __('System alerts detected - Please fix as soon as possible'); - $maintenance_class = $maintenance_id = 'show_systemalert_dialog white'; - - $maintenance_link_open_txt = ''; - $maintenance_link_open_img = ''; - $maintenance_link_close = ''; - if (!$pandora_management) { - $maintenance_img = ''; - } else { - $maintenance_img = $maintenance_link_open_img.html_print_image( - 'images/header_yellow.png', - true, - [ - 'title' => __( - 'You have %d warning(s)', - $config['alert_cnt'] - ), - 'id' => 'yougotalert', - 'class' => 'bot', - ] - ).$maintenance_link_close; - } - } else { - if (!$pandora_management) { - $maintenance_img = ''; - } else { - $maintenance_img = html_print_image('images/header_ready.png', true, ['title' => __('There are not warnings'), 'id' => 'yougotalert', 'class' => 'bot']); - } - } - - $table->data[0][3] = $maintenance_img; - // Main help icon if (!$config['disable_help']) { $table->data[0][4] = ''.html_print_image( @@ -333,16 +270,6 @@ config_check(); $table->data[0][8] .= ''; $table->data[0][8] .= ''; - // Messages - $msg_cnt = messages_get_count($config['id_user']); - if ($msg_cnt > 0) { - echo ''; - - $table->data[0][9] = ''; - $table->data[0][9] .= html_print_image('images/header_email.png', true, ['title' => __('You have %d unread message(s)', $msg_cnt), 'id' => 'yougotmail', 'class' => 'bot', 'style' => 'width:24px;']); - $table->data[0][9] .= ''; - } - html_print_table($table); unset($table); @@ -644,33 +571,12 @@ config_check(); $("#ui_close_dialog_titlebar").click(function () { $("#agent_access").css("display",""); }); - - function blinkmail(){ - $("#yougotmail").delay(100).fadeTo(300,0.2).delay(100).fadeTo(300,1, blinkmail); - } - function blinkalert(){ - $("#yougotalert").delay(100).fadeTo(300,0.2).delay(100).fadeTo(300,1, blinkalert); - } + function blinkpubli(){ $(".publienterprise").delay(100).fadeTo(300,0.2).delay(100).fadeTo(300,1, blinkpubli); } - 0) { - ?> - blinkmail(); - - - - 0) { - ?> - blinkalert(); - - blinkpubli(); + + blinkpubli(); Date: Wed, 13 Feb 2019 12:44:30 +0100 Subject: [PATCH 104/249] Fixed arrow on notifications area Former-commit-id: 6771d282bf7a6b5b9ddd0baec8a0a887f741d931 --- pandora_console/include/functions_notifications.php | 12 +++++++----- pandora_console/include/styles/pandora.css | 6 ++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 6dfcc0615e..cb23c3cdfd 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -938,12 +938,14 @@ function notifications_print_dropdown() return sprintf( "
    - %s +
    + %s
    -
    +
    +
    ", array_reduce( diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 3e6bac9543..14ddf74326 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4305,8 +4305,6 @@ div#dialog_messages table th:last-child { position: absolute; width: 400px; margin-top: -5px; - max-height: 78%; - overflow: auto; } #notification-wrapper::before { content: ""; @@ -4323,6 +4321,10 @@ div#dialog_messages table th:last-child { margin-left: -12px; border-bottom-color: white; } +#notification-wrapper-inner { + max-height: 400px; + overflow: auto; +} #notification-wrapper-shadow { height: 100%; width: 100%; From 0ecf2bb9c46157089758400746917751bc0d95fd Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 13 Feb 2019 14:43:55 +0100 Subject: [PATCH 105/249] Added pandora db messages purgue Former-commit-id: 23d1f55ac6b7d6d5470fa25860b9bbb1575875df --- pandora_console/godmode/setup/performance.php | 12 ++++++++++++ pandora_console/include/functions_config.php | 8 ++++++++ pandora_server/util/pandora_db.pl | 8 ++++++++ 3 files changed, 28 insertions(+) diff --git a/pandora_console/godmode/setup/performance.php b/pandora_console/godmode/setup/performance.php index b8a397531e..a426c44cc2 100644 --- a/pandora_console/godmode/setup/performance.php +++ b/pandora_console/godmode/setup/performance.php @@ -82,6 +82,18 @@ if (enterprise_installed()) { $table->data[12][1] = html_print_input_text('inventory_purge', $config['inventory_purge'], '', 5, 5, true); } +$table->data[] = [ + __('Max. days before delete old messages'), + html_print_input_text( + 'delete_old_messages', + $config['delete_old_messages'], + '', + 5, + 5, + true + ), +]; + $table_other = new stdClass(); $table_other->width = '100%'; $table_other->class = 'databox filters'; diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index e532deea15..d55eda62e5 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -748,6 +748,10 @@ function config_update_config() } } + if (!config_update_value('delete_old_messages', get_parameter('delete_old_messages'))) { + $error_update[] = __('Max. days before delete old messages'); + } + if (!config_update_value('max_graph_container', get_parameter('max_graph_container'))) { $error_update[] = __('Graph container - Max. Items'); } @@ -1535,6 +1539,10 @@ function config_process_config() } } + if (!isset($config['delete_old_messages'])) { + config_update_value('delete_old_messages', 21); + } + if (!isset($config['max_graph_container'])) { config_update_value('max_graph_container', 10); } diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index d1ff8d455f..ee3ab0d1fa 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -437,6 +437,13 @@ sub pandora_purgedb ($$) { # Delete old tgraph_source data db_do ($dbh,"DELETE FROM tgraph_source WHERE id_graph NOT IN (SELECT id_graph FROM tgraph)"); + + # Delete old messages + log_message ('PURGE', "Deleting old messages."); + if ($conf->{'_delete_old_messages'} > 0) { + my $message_limit = time() - 86400 * $conf->{'_delete_old_messages'}; + db_do ($dbh, "DELETE FROM tmensajes WHERE timestamp < ?", $message_limit); + } } ############################################################################### @@ -656,6 +663,7 @@ sub pandora_load_config_pdb ($) { $conf->{'_history_db_delay'} = get_db_value ($dbh, "SELECT value FROM tconfig WHERE token = 'history_db_delay'"); $conf->{'_days_delete_unknown'} = get_db_value ($dbh, "SELECT value FROM tconfig WHERE token = 'days_delete_unknown'"); $conf->{'_inventory_purge'} = get_db_value ($dbh, "SELECT value FROM tconfig WHERE token = 'inventory_purge'"); + $conf->{'_delete_old_messages'} = get_db_value ($dbh, "SELECT value FROM tconfig WHERE token = 'delete_old_messages'"); $conf->{'_enterprise_installed'} = get_db_value ($dbh, "SELECT value FROM tconfig WHERE token = 'enterprise_installed'"); $conf->{'_metaconsole'} = get_db_value ($dbh, "SELECT value FROM tconfig WHERE token = 'metaconsole'"); $conf->{'_metaconsole_events_history'} = get_db_value ($dbh, "SELECT value FROM tconfig WHERE token = 'metaconsole_events_history'"); From ed63ef47fa69bc55d32f2820d56337d0d9acff34 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 13 Feb 2019 14:56:10 +0100 Subject: [PATCH 106/249] Moved ReconServer to DiscoveryServer Former-commit-id: 5e18aa75d669f6b45d3b4e2648f31473fd206091 --- .../general/firts_task/recon_view.php | 2 +- .../godmode/servers/manage_recontask_form.php | 6 +- .../godmode/wizards/HostDevices.class.php | 10 +- .../include/class/ConsoleSupervisor.php | 99 +++++----- pandora_console/include/constants.php | 2 +- pandora_console/include/functions_events.php | 2 +- pandora_console/include/functions_servers.php | 16 +- .../help/en/help_reconscript_definition.php | 2 +- .../include/help/en/help_recontask.php | 4 +- .../include/help/ja/help_recontask.php | 2 +- .../operation/servers/recon_view.php | 2 +- pandora_server/bin/pandora_server | 4 +- pandora_server/lib/PandoraFMS/Core.pm | 2 +- .../{ReconServer.pm => DiscoveryServer.pm} | 65 ++++-- pandora_server/lib/PandoraFMS/Recon/Base.pm | 187 ++++++++++++++++++ pandora_server/lib/PandoraFMS/Tools.pm | 4 +- 16 files changed, 320 insertions(+), 89 deletions(-) rename pandora_server/lib/PandoraFMS/{ReconServer.pm => DiscoveryServer.pm} (92%) diff --git a/pandora_console/general/firts_task/recon_view.php b/pandora_console/general/firts_task/recon_view.php index 026d0f5673..1d81c13e98 100755 --- a/pandora_console/general/firts_task/recon_view.php +++ b/pandora_console/general/firts_task/recon_view.php @@ -19,7 +19,7 @@ ui_require_css_file('firts_task');
    - __('Recon server')]); ?> + __('Discovery server')]); ?>

    diff --git a/pandora_console/godmode/servers/manage_recontask_form.php b/pandora_console/godmode/servers/manage_recontask_form.php index c47416afd7..cbbcde8ec7 100644 --- a/pandora_console/godmode/servers/manage_recontask_form.php +++ b/pandora_console/godmode/servers/manage_recontask_form.php @@ -248,9 +248,9 @@ $table->rowclass[17] = 'recon_script'; $table->data[0][0] = ''.__('Task name').''; $table->data[0][1] = html_print_input_text('name', $name, '', 25, 0, true); -// Recon server -$table->data[1][0] = ''.__('Recon server').ui_print_help_tip( - __('You must select a Recon Server for the Task, otherwise the Recon Task will never run'), +// Discovery server +$table->data[1][0] = ''.__('Discovery server').ui_print_help_tip( + __('You must select a Discovery Server to run the Task, otherwise the Recon Task will never run'), true ); diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index b41788f344..3921eac025 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -402,9 +402,9 @@ class HostDevices implements Wizard $table->data[0][0] = ''.__('Task name').''; $table->data[0][1] = html_print_input_text('name', $name, '', 25, 0, true); - // Recon server. - $table->data[1][0] = ''.__('Recon server').ui_print_help_tip( - __('You must select a Recon Server for the Task, otherwise the Recon Task will never run'), + // Discovery server. + $table->data[1][0] = ''.__('Discovery server').ui_print_help_tip( + __('You must select a Discovery Server for the Task, otherwise the Recon Task will never run'), true ); @@ -818,8 +818,8 @@ function get_explanation_recon_script (id) { } - 900 - ) { - $previous[$key]['modules'] = 0; - } - - $modules_queued = ($queue['queued_modules'] - $previous[$key]['modules']); - - // 50 Modules queued since last check. Or more than 1500 queued. - if ($modules_queued > $MAX_GROWN - || $queue['queued_modules'] > $MAX_QUEUE - ) { - $msg = 'Queue has grown %d modules. Total %d'; - if ($modules_queued <= 0) { - $msg = 'Queue is decreasing in %d modules. But there are %d queued.'; - $modules_queued *= -1; + // Compare queue increments in a not over 900 seconds. + if (empty($previous[$key]['modules']) + || ($time - $previous[$key]['utime']) > 900 + ) { + $previous[$key]['modules'] = 0; } - $this->notify( - [ - 'type' => 'NOTIF.SERVER.QUEUE.'.$key, - 'title' => __( - '%s (%s) performance is being lacked.', - servers_get_server_string_name($type), - $queue['name'] - ), - 'message' => __( - $msg, - $modules_queued, - $queue['queued_modules'] - ), - 'url' => ui_get_full_url( - 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60' - ), - ] - ); - } else { - $this->cleanNotifications('NOTIF.SERVER.QUEUE.'.$key); + $modules_queued = ($queue['queued_modules'] - $previous[$key]['modules']); + + // 50 Modules queued since last check. Or more than 1500 queued. + if ($modules_queued > $MAX_GROWN + || $queue['queued_modules'] > $MAX_QUEUE + ) { + $msg = 'Queue has grown %d modules. Total %d'; + if ($modules_queued <= 0) { + $msg = 'Queue is decreasing in %d modules. But there are %d queued.'; + $modules_queued *= -1; + } + + $this->notify( + [ + 'type' => 'NOTIF.SERVER.QUEUE.'.$key, + 'title' => __( + '%s (%s) performance is being lacked.', + servers_get_server_string_name($type), + $queue['name'] + ), + 'message' => __( + $msg, + $modules_queued, + $queue['queued_modules'] + ), + 'url' => ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60' + ), + ] + ); + } else { + $this->cleanNotifications('NOTIF.SERVER.QUEUE.'.$key); + } + + $new[$key]['modules'] = $queue['queued_modules']; + $new[$key]['utime'] = $time; } - $new[$key]['modules'] = $queue['queued_modules']; - $new[$key]['utime'] = $time; - } + // Update file content. + file_put_contents($idx_file, json_encode($new)); + } else { + // No queue data, ignore. + unlink($idx_file); - file_put_contents($idx_file, json_encode($new)); + // Clean notifications. + $this->cleanNotifications('NOTIF.SERVER.QUEUE.%'); + } } diff --git a/pandora_console/include/constants.php b/pandora_console/include/constants.php index cd1b907c0a..b472f98ad8 100644 --- a/pandora_console/include/constants.php +++ b/pandora_console/include/constants.php @@ -366,7 +366,7 @@ define('PASSSWORD_POLICIES_EXPIRED', 2); define('SERVER_TYPE_DATA', 0); define('SERVER_TYPE_NETWORK', 1); define('SERVER_TYPE_SNMP', 2); -define('SERVER_TYPE_RECON', 3); +define('SERVER_TYPE_DISCOVERY', 3); define('SERVER_TYPE_PLUGIN', 4); define('SERVER_TYPE_PREDICTION', 5); define('SERVER_TYPE_WMI', 6); diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php index f3f3d2b0fa..a2ca914b37 100644 --- a/pandora_console/include/functions_events.php +++ b/pandora_console/include/functions_events.php @@ -1378,7 +1378,7 @@ function events_print_type_description($type, $return=false) break; case 'recon_host_detected'; - $output .= __('Recon server detected a new host'); + $output .= __('Discovery server detected a new host'); break; case 'new_agent'; diff --git a/pandora_console/include/functions_servers.php b/pandora_console/include/functions_servers.php index 249704fe13..ba6659ddc1 100644 --- a/pandora_console/include/functions_servers.php +++ b/pandora_console/include/functions_servers.php @@ -26,6 +26,8 @@ * ============================================================================ */ +require_once __DIR__.'/constants.php'; + /** * Get a server. @@ -203,7 +205,7 @@ function servers_get_performance() case SERVER_TYPE_EXPORT: case SERVER_TYPE_INVENTORY: case SERVER_TYPE_EVENT: - case SERVER_TYPE_RECON: + case SERVER_TYPE_DISCOVERY: case SERVER_TYPE_SYSLOG: break; } @@ -424,8 +426,8 @@ function servers_get_info($id_server=-1) $id_modulo = 0; break; - case SERVER_TYPE_RECON: - $server['img'] = html_print_image('images/recon.png', true, ['title' => __('Recon server')]); + case SERVER_TYPE_DISCOVERY: + $server['img'] = html_print_image('images/recon.png', true, ['title' => __('Discovery server')]); $server['type'] = 'recon'; $id_modulo = 0; break; @@ -598,11 +600,11 @@ function servers_get_info($id_server=-1) $server['lag'] = 0; $server['module_lag'] = 0; } - // Recon server - else if ($server['server_type'] == SERVER_TYPE_RECON) { + // Discovery server + else if ($server['server_type'] == SERVER_TYPE_DISCOVERY) { $server['name'] = ''.$server['name'].''; - // Total jobs running on this recon server + // Total jobs running on this Discovery server $server['modules'] = db_get_sql( 'SELECT COUNT(id_rt) FROM trecon_task @@ -978,7 +980,7 @@ function servers_get_server_string_name(int $server) case SERVER_TYPE_EVENT: return __('Event server'); - case SERVER_TYPE_RECON: + case SERVER_TYPE_DISCOVERY: return __('Discovery server'); case SERVER_TYPE_SYSLOG: diff --git a/pandora_console/include/help/en/help_reconscript_definition.php b/pandora_console/include/help/en/help_reconscript_definition.php index 3259b34dd2..f7562acbfc 100644 --- a/pandora_console/include/help/en/help_reconscript_definition.php +++ b/pandora_console/include/help/en/help_reconscript_definition.php @@ -7,7 +7,7 @@

    The "ReconScripts" allows to work with more flexible capabilities. The recon scripts are developped in an individual way with completely specific targets, such as the network plugins or the agent plugins. Each ReconScript is different and has one purpose.

    -

    Its basic idea consist on "detect" things in the system it recognizes and automatically log in one monitoring (network, plugin or wmi) so in a completely customized way we could automatically log in requests in an Oracle database, new virtual host in a VmWare that is managed with VirtualCenter or we also can detect new requests in an WebLogic application Server. It is possible to do an script or application that does the task that are wanted and schedule its execution through the Recon Server.

    +

    Its basic idea consist on "detect" things in the system it recognizes and automatically log in one monitoring (network, plugin or wmi) so in a completely customized way we could automatically log in requests in an Oracle database, new virtual host in a VmWare that is managed with VirtualCenter or we also can detect new requests in an WebLogic application Server. It is possible to do an script or application that does the task that are wanted and schedule its execution through the Discovery Server.

    A field with importance is:

    diff --git a/pandora_console/include/help/en/help_recontask.php b/pandora_console/include/help/en/help_recontask.php index 0223d66e5b..b56a0a85c6 100644 --- a/pandora_console/include/help/en/help_recontask.php +++ b/pandora_console/include/help/en/help_recontask.php @@ -11,9 +11,9 @@ If you choose to edit or create a new task of network recon, then you should fil Name of the discovery task. It's only a descriptive value to could distinguish the task in case it would have several of them with different values of filter or template.

    -Recon server
    +Discovery server
    -Recon Server assigned to the task. If you have several Recon Servers, then you have to select here which of them you want to do the recon task.

    +Discovery Server assigned to the task. If you have several Discovery Servers, then you have to select here which of them you want to do the recon task.

    Mode
    diff --git a/pandora_console/include/help/ja/help_recontask.php b/pandora_console/include/help/ja/help_recontask.php index 790c2cdb48..182b249653 100644 --- a/pandora_console/include/help/ja/help_recontask.php +++ b/pandora_console/include/help/ja/help_recontask.php @@ -12,7 +12,7 @@ 検出タスクの名前です。フィルターやテンプレートとは異なり、タスクを区別しやすい説明を入れるだけです。

    -自動検出サーバ(Recon server)
    +自動検出サーバ(Discovery server)
    タスクを割り当てる自動検出サーバです。複数の自動検出サーバがある場合は、自動検出タスクをどのサーバで実行するかを選択します。

    diff --git a/pandora_console/operation/servers/recon_view.php b/pandora_console/operation/servers/recon_view.php index d91b838e8b..84a057d69c 100644 --- a/pandora_console/operation/servers/recon_view.php +++ b/pandora_console/operation/servers/recon_view.php @@ -30,7 +30,7 @@ $servers = db_get_all_rows_sql('SELECT * FROM tserver WHERE server_type = 3'); if ($servers === false) { $servers = []; ui_print_page_header(__('Recon View'), 'images/op_recon.png', false, '', false); - ui_print_error_message(__('Recon Server is disabled')); + ui_print_error_message(__('Discovery Server is disabled')); return; } else { $recon_task = db_get_all_rows_sql('SELECT * FROM trecon_task'); diff --git a/pandora_server/bin/pandora_server b/pandora_server/bin/pandora_server index a5e8be893d..53265cb0a0 100755 --- a/pandora_server/bin/pandora_server +++ b/pandora_server/bin/pandora_server @@ -33,7 +33,7 @@ use PandoraFMS::Core; use PandoraFMS::DataServer; use PandoraFMS::NetworkServer; use PandoraFMS::SNMPServer; -use PandoraFMS::ReconServer; +use PandoraFMS::DiscoveryServer; use PandoraFMS::WMIServer; use PandoraFMS::PluginServer; use PandoraFMS::PredictionServer; @@ -123,7 +123,7 @@ sub pandora_startup () { pandora_reset_server (\%Config, $DBH); push (@Servers, new PandoraFMS::DataServer (\%Config, $DBH)); push (@Servers, new PandoraFMS::NetworkServer (\%Config, $DBH)); - push (@Servers, new PandoraFMS::ReconServer (\%Config, $DBH)); + push (@Servers, new PandoraFMS::DiscoveryServer (\%Config, $DBH)); push (@Servers, new PandoraFMS::SNMPServer (\%Config, $DBH)); push (@Servers, new PandoraFMS::WMIServer (\%Config, $DBH)); push (@Servers, new PandoraFMS::PluginServer (\%Config, $DBH)); diff --git a/pandora_server/lib/PandoraFMS/Core.pm b/pandora_server/lib/PandoraFMS/Core.pm index 3bfd1e1a7d..ff82d69c53 100644 --- a/pandora_server/lib/PandoraFMS/Core.pm +++ b/pandora_server/lib/PandoraFMS/Core.pm @@ -4514,7 +4514,7 @@ sub pandora_server_statistics ($$) { $server->{"lag"} = 0; $server->{"module_lag"} = 0; # Recon server - } elsif ($server->{"server_type"} == RECONSERVER) { + } elsif ($server->{"server_type"} == DISCOVERYSERVER) { # Total jobs running on this recon server $server->{"modules"} = get_db_value ($dbh, "SELECT COUNT(id_rt) FROM trecon_task WHERE id_recon_server = ?", $server->{"id_server"}); diff --git a/pandora_server/lib/PandoraFMS/ReconServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm similarity index 92% rename from pandora_server/lib/PandoraFMS/ReconServer.pm rename to pandora_server/lib/PandoraFMS/DiscoveryServer.pm index 277e3a3ec8..7b6fa7c0ea 100644 --- a/pandora_server/lib/PandoraFMS/ReconServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -1,6 +1,6 @@ -package PandoraFMS::ReconServer; +package PandoraFMS::DiscoveryServer; ########################################################################## -# Pandora FMS Recon Server. +# Pandora FMS Discovery Server. # Pandora FMS. the Flexible Monitoring System. http://www.pandorafms.org ########################################################################## # Copyright (c) 2005-2009 Artica Soluciones Tecnologicas S.L @@ -57,16 +57,16 @@ use constant OS_ROUTER => 17; use constant OS_SWITCH => 18; ######################################################################################## -# Recon Server class constructor. +# Discovery Server class constructor. ######################################################################################## sub new ($$$$$$) { my ($class, $config, $dbh) = @_; - return undef unless $config->{'reconserver'} == 1; + return undef unless $config->{'reconserver'} == 1 || $config->{'discoveryserver'} == 1; if (! -e $config->{'nmap'}) { - logger ($config, ' [E] ' . $config->{'nmap'} . " needed by " . $config->{'rb_product_name'} . " Recon Server not found.", 1); - print_message ($config, ' [E] ' . $config->{'nmap'} . " needed by " . $config->{'rb_product_name'} . " Recon Server not found.", 1); + logger ($config, ' [E] ' . $config->{'nmap'} . " needed by " . $config->{'rb_product_name'} . " Discovery Server not found.", 1); + print_message ($config, ' [E] ' . $config->{'nmap'} . " needed by " . $config->{'rb_product_name'} . " Discovery Server not found.", 1); return undef; } @@ -78,14 +78,14 @@ sub new ($$$$$$) { # Restart automatic recon tasks. db_do ($dbh, 'UPDATE trecon_task SET utimestamp = 0 WHERE id_recon_server = ? AND status <> -1 AND interval_sweep > 0', - get_server_id ($dbh, $config->{'servername'}, RECONSERVER)); + get_server_id ($dbh, $config->{'servername'}, DISCOVERYSERVER)); # Reset (but do not restart) manual recon tasks. db_do ($dbh, 'UPDATE trecon_task SET status = -1 WHERE id_recon_server = ? AND status <> -1 AND interval_sweep = 0', - get_server_id ($dbh, $config->{'servername'}, RECONSERVER)); + get_server_id ($dbh, $config->{'servername'}, DISCOVERYSERVER)); # Call the constructor of the parent class - my $self = $class->SUPER::new($config, RECONSERVER, \&PandoraFMS::ReconServer::data_producer, \&PandoraFMS::ReconServer::data_consumer, $dbh); + my $self = $class->SUPER::new($config, DISCOVERYSERVER, \&PandoraFMS::DiscoveryServer::data_producer, \&PandoraFMS::DiscoveryServer::data_consumer, $dbh); bless $self, $class; return $self; @@ -98,7 +98,7 @@ sub run ($) { my $self = shift; my $pa_config = $self->getConfig (); - print_message ($pa_config, " [*] Starting " . $pa_config->{'rb_product_name'} . " Recon Server.", 1); + print_message ($pa_config, " [*] Starting " . $pa_config->{'rb_product_name'} . " Discovery Server.", 1); $self->setNumThreads ($pa_config->{'recon_threads'}); $self->SUPER::run (\@TaskQueue, \%PendingTasks, $Sem, $TaskSem); } @@ -121,9 +121,10 @@ sub data_producer ($) { # Status -1 means "done". my @rows = get_db_rows ($dbh, 'SELECT * FROM trecon_task - WHERE id_recon_server = ? - AND disabled = 0 - AND utimestamp = 0 OR (status = -1 AND interval_sweep > 0 AND (utimestamp + interval_sweep) < UNIX_TIMESTAMP())', $server_id); + WHERE id_recon_server = ? + AND disabled = 0 + AND ((utimestamp = 0 AND interval_sweep != 0 OR status = 1) + OR (status = -1 AND interval_sweep > 0 AND (utimestamp + interval_sweep) < UNIX_TIMESTAMP()))', $server_id); foreach my $row (@rows) { # Update task status @@ -154,12 +155,13 @@ sub data_consumer ($$) { logger($pa_config, 'Starting recon task for net ' . $task->{'subnet'} . '.', 10); } - # Call nmap - my $nmap_args = '-nsP -PE --max-retries '.$pa_config->{'icmp_checks'}.' --host-timeout '.$pa_config->{'networktimeout'}.'s -T'.$pa_config->{'recon_timing_template'}; - my $np = new PandoraFMS::NmapParser; eval { my @subnets = split(/,/, safe_output($task->{'subnet'})); my @communities = split(/,/, safe_output($task->{'snmp_community'})); + my @auth_strings = (); + if(defined($task->{'auth_strings'})) { + @auth_strings = split(/,/, safe_output($task->{'auth_strings'})); + } my $recon = new PandoraFMS::Recon::Base( communities => \@communities, @@ -186,6 +188,8 @@ sub data_consumer ($$) { subnets => \@subnets, task_id => $task->{'id_rt'}, vlan_cache_enabled => $task->{'vlan_enabled'}, + wmi_enabled => $task->{'wmi_enabled'}, + auth_strings_array => \@auth_strings, %{$pa_config} ); @@ -748,6 +752,35 @@ sub PandoraFMS::Recon::Base::set_parent($$$) { db_do($self->{'dbh'}, 'UPDATE tagente SET id_parent=? WHERE id_agente=?', $agent_parent->{'id_agente'}, $agent->{'id_agente'}); } +########################################################################## +# Create a WMI module for the given agent. +########################################################################## +sub PandoraFMS::Recon::Base::wmi_module { + my ($self, $agent_id, $target, $wmi_query, $wmi_auth, $column, + $module_name, $module_description, $module_type, $unit) = @_; + + # Check whether the module already exists. + my $module_id = get_agent_module_id($self->{'dbh'}, $module_name, $agent_id); + return if ($module_id > 0); + + my ($user, $pass) = ($wmi_auth ne '') ? split('%', $wmi_auth) : (undef, undef); + my %module = ( + 'descripcion' => safe_input($module_description), + 'id_agente' => $agent_id, + 'id_modulo' => 6, + 'id_tipo_modulo' => get_module_id($self->{'dbh'}, $module_type), + 'ip_target' => $target, + 'nombre' => safe_input($module_name), + 'plugin_pass' => defined($pass) ? $pass : '', + 'plugin_user' => defined($user) ? $user : '', + 'snmp_oid' => $wmi_query, + 'tcp_port' => $column, + 'unit' => defined($unit) ? $unit : '' + ); + + pandora_create_module_from_hash($self->{'pa_config'}, \%module, $self->{'dbh'}); +} + ########################################################################## # Update recon task status. ########################################################################## diff --git a/pandora_server/lib/PandoraFMS/Recon/Base.pm b/pandora_server/lib/PandoraFMS/Recon/Base.pm index a214d6ba4b..8d24ebf311 100644 --- a/pandora_server/lib/PandoraFMS/Recon/Base.pm +++ b/pandora_server/lib/PandoraFMS/Recon/Base.pm @@ -123,6 +123,12 @@ sub new { # Globally enable/disable SNMP scans. snmp_enabled => 1, + # Globally enable/disable WMI scans. + wmi_enabled => 0, + auth_strings_array => [], + wmi_timeout => 3, + timeout_cmd => '', + # Switch to switch connections. Used to properly connect hosts # that are connected to a switch wich is in turn connected to another switch, # since the hosts will show up in the latter's switch AFT too. @@ -217,6 +223,19 @@ sub new { } } + # Prepare auth array. + # WMI could be launched with '-N' - no pass - argument. + if ($self->{'wmi_enabled'} == 1){ + if (defined($self->{'auth_strings_str'})) { + @{$self->{'auth_strings_array'}} = split(',', $self->{'auth_strings_str'}); + } + + # Timeout available only in linux environments. + if ($^O =~ /lin/i && defined($self->{'plugin_exec'}) && defined($self->{'wmi_timeout'})) { + $self->{'timeout_cmd'} = $self->{'plugin_exec'}.' '.$self->{'wmi_timeout'}.' '; + } + } + # Remove all snmp related values if disabled if (!$self->{'snmp_enabled'}) { $self->{'communities'} = []; @@ -1312,6 +1331,9 @@ sub scan_subnet($) { $progress += $step; $self->snmp_discovery($host); + + # Add wmi scan if enabled. + $self->wmi_scan($host) if ($self->{'wmi_enabled'} == 1); } } # ping scan. @@ -1330,6 +1352,9 @@ sub scan_subnet($) { next if ($self->ping($host) == 0); $self->snmp_discovery($host); + + # Add wmi scan if enabled. + $self->wmi_scan($host) if ($self->{'wmi_enabled'} == 1); } } } @@ -1579,6 +1604,168 @@ sub traceroute_connectivity($$) { } } +########################################################################## +# Returns the credentials with which the host responds to WMI queries or +# undef if it does not respond to WMI. +########################################################################## +sub responds_to_wmi { + my ($self, $target) = @_; + + foreach my $auth (@{$self->{'auth_strings_array'}}) { + my @output; + if ($auth ne '') { + @output = `$self->{'timeout_cmd'}$self->{'wmi_client'} -U $auth //$target "SELECT * FROM Win32_ComputerSystem" 2>&1`; + } else { + @output = `$self->{'timeout_cmd'}$self->{'wmi_client'} -N //$target "SELECT * FROM Win32_ComputerSystem" 2>&1`; + } + + foreach my $line (@output) { + chomp($line); + return $auth if ($line =~ m/^CLASS: Win32_ComputerSystem$/); + } + } + + return undef; +} + +########################################################################## +# Add wmi modules to the given host. +########################################################################## +sub wmi_scan { + my ($self, $target) = @_; + + $self->call('message', "[".$target."] Checking WMI.", 5); + + my $auth = $self->responds_to_wmi($target); + return unless defined($auth); + + $self->call('message', "[".$target."] WMI available.", 10); + # Create the agent if it does not exist. + my $agent_id = $self->call('create_agent', $target); + next unless defined($agent_id); + + # CPU. + my @cpus = $self->wmi_get_value_array($target, $auth, 'SELECT DeviceId FROM Win32_Processor', 0); + foreach my $cpu (@cpus) { + $self->call( + 'wmi_module', + ( + $agent_id, + $target, + "SELECT LoadPercentage FROM Win32_Processor WHERE DeviceId='$cpu'", + $auth, + 1, + "CPU Load $cpu", + "Load for $cpu (%)", + 'generic_data' + ) + ); + } + + # Memory. + my $mem = $self->wmi_get_value($target, $auth, 'SELECT FreePhysicalMemory FROM Win32_OperatingSystem', 0); + if (defined($mem)) { + $self->call('wmi_module', + ( + $agent_id, + $target, + "SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem", + $auth, + 0, + 'FreeMemory', + 'Free memory', + 'generic_data', + 'KB' + ) + ); + } + + # Disk. + my @units = $self->wmi_get_value_array($target, $auth, 'SELECT DeviceID FROM Win32_LogicalDisk', 0); + foreach my $unit (@units) { + $self->call( + 'wmi_module', + ( + $agent_id, + $target, + "SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID='$unit'", + $auth, + 1, + "FreeDisk $unit", + 'Available disk space in kilobytes', + 'generic_data', + 'KB' + ) + ); + } +} + +########################################################################## +# Extra: WMI imported methods. DO NOT EXPORT TO AVOID DOUBLE DEF. +########################################################################## + +########################################################################## +# Performs a wmi get requests and returns the response as an array. +########################################################################## +sub wmi_get { + my ($self, $target, $auth, $query) = @_; + + my @output; + if (defined($auth) && $auth ne '') { + @output = `$self->{'timeout_cmd'}"$self->{'wmi_client'}" -U $auth //$target "$query" 2>&1`; + }else { + @output = `$self->{'timeout_cmd'}"$self->{'wmi_client'}" -N //$target "$query" 2>&1`; + } + + # Something went wrong. + return () if ($? != 0); + + return @output; +} + +########################################################################## +# Performs a WMI request and returns the requested column of the first row. +# Returns undef on error. +########################################################################## +sub wmi_get_value { + my ($self, $target, $auth, $query, $column) = @_; + my @result; + + my @output = $self->wmi_get($target, $auth, $query); + return undef unless defined($output[2]); + + my $line = $output[2]; + chomp($line); + my @columns = split(/\|/, $line); + return undef unless defined($columns[$column]); + + return $columns[$column]; +} + +########################################################################## +# Performs a WMI request and returns row values for the requested column +# in an array. +########################################################################## +sub wmi_get_value_array { + my ($self, $target, $auth, $query, $column) = @_; + my @result; + + my @output = $self->wmi_get($target, $auth, $query); + foreach (my $i = 2; defined($output[$i]); $i++) { + my $line = $output[$i]; + chomp($line); + my @columns = split(/\|/, $line); + next unless defined($columns[$column]); + push(@result, $columns[$column]); + } + + return @result; +} + +########################################################################## +# END: WMI imported methods. +########################################################################## + 1; __END__ diff --git a/pandora_server/lib/PandoraFMS/Tools.pm b/pandora_server/lib/PandoraFMS/Tools.pm index 1146e8ce92..aababebd69 100755 --- a/pandora_server/lib/PandoraFMS/Tools.pm +++ b/pandora_server/lib/PandoraFMS/Tools.pm @@ -51,7 +51,7 @@ our @EXPORT = qw( DATASERVER NETWORKSERVER SNMPCONSOLE - RECONSERVER + DISCOVERYSERVER PLUGINSERVER PREDICTIONSERVER WMISERVER @@ -134,7 +134,7 @@ our @EXPORT = qw( use constant DATASERVER => 0; use constant NETWORKSERVER => 1; use constant SNMPCONSOLE => 2; -use constant RECONSERVER => 3; +use constant DISCOVERYSERVER => 3; use constant PLUGINSERVER => 4; use constant PREDICTIONSERVER => 5; use constant WMISERVER => 6; From 74e16b656b19947224edd700963c2bb612b92477 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 13 Feb 2019 15:03:59 +0100 Subject: [PATCH 107/249] Disable max postpone select Former-commit-id: 43460b3304b70d6d0248ace672d51c2b48c3d22c --- pandora_console/include/functions_notifications.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index cb23c3cdfd..16a82898c4 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -713,6 +713,7 @@ function notifications_print_global_source_configuration($source) // Generate the select with the time. $html_select_pospone = __('Users can postpone notifications up to'); + // FIXMEit should not be disabled. $html_select_pospone .= html_print_select( [ SECONDS_5MINUTES => __('5 minutes'), @@ -732,7 +733,8 @@ function notifications_print_global_source_configuration($source) true, false, true, - 'elem-changeable' + 'elem-changeable', + true, ); // Return all html. From 9951aadab34471321da98891f4d228d3ad12b451 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 13 Feb 2019 15:04:53 +0100 Subject: [PATCH 108/249] Fixed typo Former-commit-id: 469f46c34caefcb6b810e99f88a9223434959182 --- pandora_console/include/functions_notifications.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 16a82898c4..7f4b40c98b 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -734,7 +734,7 @@ function notifications_print_global_source_configuration($source) false, true, 'elem-changeable', - true, + true ); // Return all html. From 10a37c313c4f31b72e319bebfcc3b9f705e696dc Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 13 Feb 2019 15:05:21 +0100 Subject: [PATCH 109/249] DB schema update native WMI scan Former-commit-id: 995fce571f2f37c5cbe891f726fa979cbb8ef183 --- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 ++ pandora_console/pandoradb.sql | 2 ++ 2 files changed, 4 insertions(+) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 58bb5d8e5e..c9784987fd 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1406,6 +1406,8 @@ ALTER TABLE twidget_dashboard MODIFY options LONGTEXT NOT NULL default ""; ALTER TABLE trecon_task ADD `alias_as_name` int(2) unsigned default '0'; ALTER TABLE trecon_task ADD `snmp_enabled` int(2) unsigned default '0'; ALTER TABLE trecon_task ADD `vlan_enabled` int(2) unsigned default '0'; +ALTER TABLE trecon_task ADD `wmi_enabled` tinyint(1) unsigned DEFAULT '0'; +ALTER TABLE trecon_task ADD `auth_strings` text; -- --------------------------------------------------------------------- -- Table `twidget` AND Table `twidget_dashboard` diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index 5af9d38c55..a8d9b5c129 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -769,6 +769,8 @@ CREATE TABLE IF NOT EXISTS `trecon_task` ( `snmp_privacy_method` varchar(25) NOT NULL default '', `snmp_privacy_pass` varchar(255) NOT NULL default '', `snmp_security_level` varchar(25) NOT NULL default '', + `wmi_enabled` tinyint(1) unsigned DEFAULT '0', + `auth_strings` text, PRIMARY KEY (`id_rt`), KEY `recon_task_daemon` (`id_recon_server`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; From 453c639c53c6c49a0225d3cf5cc61f27db22609a Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 13 Feb 2019 15:54:40 +0100 Subject: [PATCH 110/249] optimized. events_has_extended_info Former-commit-id: 805b80f1a9e09425b0e5710906886ae39e791753 --- pandora_console/include/functions_events.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php index 71780ed4e5..8ffabc5ad4 100644 --- a/pandora_console/include/functions_events.php +++ b/pandora_console/include/functions_events.php @@ -2622,10 +2622,9 @@ function events_has_extended_info(int $id_event) { return (bool) db_get_value_sql( sprintf( - ' - SELECT count(*) as "n" - FROM tevent_extended WHERE id_evento=%d - ', + 'SELECT count(*) FROM ( + SELECT * as "n" + FROM tevent_extended WHERE id_evento=%d LIMIT 1) t', $id_event ) ); From 7f4353c4bc3d5b03d43b2a28d793ca51b929c6fc Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 13 Feb 2019 15:55:03 +0100 Subject: [PATCH 111/249] optimized. events_has_extended_info Former-commit-id: 2435badcea24fd5777bde358658409bf947a2d4b --- pandora_console/include/functions_events.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php index 8ffabc5ad4..dcdd4a6bf3 100644 --- a/pandora_console/include/functions_events.php +++ b/pandora_console/include/functions_events.php @@ -2622,8 +2622,8 @@ function events_has_extended_info(int $id_event) { return (bool) db_get_value_sql( sprintf( - 'SELECT count(*) FROM ( - SELECT * as "n" + 'SELECT count(*) as "n" FROM ( + SELECT * FROM tevent_extended WHERE id_evento=%d LIMIT 1) t', $id_event ) From f75a292b34c9a15114de3b43861ca8a63041ea51 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 13 Feb 2019 16:40:37 +0100 Subject: [PATCH 112/249] minor fixes/updates in notifications UI Former-commit-id: d4f5b7db1b5a6f0a023e33c4b8cd55db7765b11a --- pandora_console/general/header.php | 5 ++--- pandora_console/include/functions_notifications.php | 6 +++--- pandora_console/include/styles/pandora.css | 4 +++- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index 5cf10bc749..e35d401502 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -170,6 +170,7 @@ config_check(); if (!isset($_GET['refr'])) { $_GET['refr'] = null; } + $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '".$config['id_user']."'"); $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); @@ -416,8 +417,6 @@ config_check(); toast_div.appendChild(toast_text); toast.appendChild(toast_div); - console.log(toast); - // Show and program the hide event. toast_div.className = toast_div.className + ' show'; setTimeout(function(){ @@ -478,7 +477,7 @@ config_check(); data.new_notifications.forEach(function(ele) { toast_wrapper.appendChild( print_toast( - ele.description, + ele.subject, ele.mensaje, ele.criticity, ele.full_url, diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 7f4b40c98b..0e35b7ea37 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -978,7 +978,7 @@ function notifications_print_dropdown_element($message_info) href='%s' target='_blank' > - + %s

    %s @@ -991,7 +991,7 @@ function notifications_print_dropdown_element($message_info) $message_info['id_mensaje'], messages_get_url($message_info['id_mensaje']), html_print_image('images/'.$message_info['icon'], true), - $message_info['description'], - $message_info['mensaje'] + $message_info['subject'], + str_replace([io_safe_input('
    ')], ' ', $message_info['mensaje']) ); } diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 14ddf74326..d915d19508 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4292,7 +4292,7 @@ div#dialog_messages table th:last-child { .notification-ball-no-messages { background-color: #82b92e; - cursor: inherit; + cursor: pointer; } .notification-ball-new-messages { background-color: #fc4444; @@ -4342,6 +4342,7 @@ div#dialog_messages table th:last-child { display: flex; flex-flow: row nowrap; align-items: center; + padding: 5px; } .notification-item > * { padding-left: 15px; @@ -4754,6 +4755,7 @@ input:checked + .p-slider:before { border-radius: 4px; visibility: hidden; pointer-events: all; + transition: visibility 0s 1s; } .snackbar.show { From 5b4cadf1382dc98558f70386d9d218f3867170f0 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 13 Feb 2019 17:16:12 +0100 Subject: [PATCH 113/249] minor style fix Former-commit-id: ca2dcf89672832b7796c9b9cc555d36d9db503ec --- pandora_console/include/styles/pandora.css | 1 - 1 file changed, 1 deletion(-) diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index d915d19508..f3fdca5874 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -4755,7 +4755,6 @@ input:checked + .p-slider:before { border-radius: 4px; visibility: hidden; pointer-events: all; - transition: visibility 0s 1s; } .snackbar.show { From f91635c67cd0f07dba6086256bf0d2f4c6d17697 Mon Sep 17 00:00:00 2001 From: Daniel Barbero Date: Thu, 14 Feb 2019 07:46:19 +0100 Subject: [PATCH 114/249] fixed errors in pdf reports Former-commit-id: fbc3598ab2dfd11cc2bfa850ba49b3e35481218d --- .../include/functions_reporting.php | 24 +++++++++++++++++++ .../include/functions_reporting_html.php | 16 ++++++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index 2e2e2e6bd4..1aa9ecf618 100755 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -11334,3 +11334,27 @@ function reporting_translate_sla_status_for_graph($status) ]; return $sts[$status]; } + + +/** + * Print header to report pdf and add page break + * + * @param string $title Title of report. + * @param string $description Description of report. + * + * @return html Return table of header. + */ +function reporting_header_table_for_pdf(string $title='', string $description='') +{ + $result_pdf .= ''; + $result_pdf .= ''; + $result_pdf .= ''; + $result_pdf .= '
    '; + $result_pdf .= $title; + $result_pdf .= ''; + $result_pdf .= '
    '; + $result_pdf .= $description; + $result_pdf .= '
    '; + + return $result_pdf; +} diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index 84c4e0d7ba..2c29258d05 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -2940,7 +2940,17 @@ function reporting_html_availability(&$table, $item) } -function reporting_html_availability_graph(&$table, $item, $pdf=0) +/** + * The availability report shows in detail the reached + * status of a module in a given time interval. + * + * @param string $table Reference table in pdf a false. + * @param array $item Parameters for item pdf. + * @param boolean $pdf Send pdf. + * + * @return html + */ +function reporting_html_availability_graph($table, $item, $pdf=0) { global $config; $metaconsole_on = is_metaconsole(); @@ -2999,7 +3009,7 @@ function reporting_html_availability_graph(&$table, $item, $pdf=0) } if ($item['type'] == 'availability_graph') { - // table_legend_graphs; + // Table_legend_graphs. $table2 = new stdClass(); $table2->width = '99%'; $table2->data = []; @@ -3040,7 +3050,7 @@ function reporting_html_availability_graph(&$table, $item, $pdf=0) $table->colspan['legend']['cell'] = 2; $table->data['legend']['cell'] = html_print_table($table2, true); - if ($pdf) { + if ($pdf !== 0) { return $tables_chart.'
    '.html_print_table($table2, true); } } From 57991495e4441395943cfd8df9619a35c884b65b Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 14 Feb 2019 10:30:01 +0100 Subject: [PATCH 115/249] Use the CSV extension to import CSV on host and devices Former-commit-id: ed95b09992ee681e35e7f934b8a8ac70c83bc8be --- pandora_console/godmode/servers/discovery.php | 13 +++- .../godmode/wizards/HostDevices.class.php | 66 +++++++------------ .../include/functions_extensions.php | 3 +- 3 files changed, 37 insertions(+), 45 deletions(-) diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 557b7bf5b3..0e52d0dc1f 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -1,8 +1,19 @@ url.'&mode=importcsv" alt="importcsv">Importar csv'; + if (extensions_is_enabled_extension('csv_import')) { + echo 'Importar csv'; + } + echo 'Escanear red'; return; } @@ -116,50 +119,27 @@ class HostDevices implements Wizard public function runCSV() { global $config; - echo 'formulario csv'; - if (isset($this->page) === false || $this->page === 0) { - $this->page = 0; - - $test = get_parameter('test', null); - - // Check user answers. - if ($test !== null) { - // $this->process_page_0($respuestas_usuario) - $this->page++; - header( - 'Location: '.$this->url.'&page='.$this->page - ); - } else { - // Mostrar pagina 0. - echo 'Aqui vamos a empezar a construir el formulario.'; - ?> -
    - -
    - page == 1) { - // Code... - $this->page++; + if (!check_acl($config['id_user'], 0, 'AW') + ) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access db status' + ); + include 'general/noaccess.php'; return; - header('Location: index.php?class=HostDevices&page='.$this->page); - } else if ($this->page == 2) { - // Code... - $this->page++; - header('Location: index.php?class=HostDevices&page='.$this->page); - } else if ($this->page == 3) { - // Code... - $this->page++; - header('Location: /XXX/discovery/index.php?class=HostDevices&page='.$this->page); } - // Page 4, last. - return [ - 'result' => $this->result, - 'id' => $this->id, - 'msg' => $this->msg, - ]; + if (!extensions_is_enabled_extension('csv_import')) { + ui_print_error_message( + [ + 'message' => __('Extension CSV Import is not enabled.'), + 'no_close' => true, + ] + ); + return; + } + include_once $config['homedir'].'/enterprise/extensions/csv_import/main.php'; } @@ -818,8 +798,8 @@ function get_explanation_recon_script (id) { } - Date: Thu, 14 Feb 2019 10:56:25 +0100 Subject: [PATCH 116/249] WIP H&D Former-commit-id: c3b0b6f56ff0591f8c5839d61144bbb72ddd7033 --- .../godmode/wizards/HostDevices.class.php | 174 ++++++++------- .../godmode/wizards/Wizard.interface.php | 16 -- .../godmode/wizards/Wizard.main.php | 198 ++++++++++++++++++ .../godmode/wizards/hostDevices.png | Bin 5251 -> 0 bytes 4 files changed, 300 insertions(+), 88 deletions(-) delete mode 100755 pandora_console/godmode/wizards/Wizard.interface.php create mode 100644 pandora_console/godmode/wizards/Wizard.main.php delete mode 100755 pandora_console/godmode/wizards/hostDevices.png diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 3921eac025..20bd304014 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -1,11 +1,11 @@ data[11][0] = ''.__('SNMP enabled'); $table->data[11][1] = html_print_checkbox('snmp_enabled', 1, $snmp_enabled, true); @@ -673,99 +708,99 @@ class HostDevices implements Wizard echo ''; ui_require_javascript_file('pandora_modules'); - ?> - - `; + echo $a; + return [ 'result' => $this->result, 'id' => $this->id, 'msg' => $this->msg, - ]; - */ - + ]; } diff --git a/pandora_console/godmode/wizards/Wizard.interface.php b/pandora_console/godmode/wizards/Wizard.interface.php deleted file mode 100755 index 6d1ac73783..0000000000 --- a/pandora_console/godmode/wizards/Wizard.interface.php +++ /dev/null @@ -1,16 +0,0 @@ -'; + + $ouput .= '
      '; + + foreach ($inputs as $input) { + $output .= '
    • '; + $output .= '
    • '; + } + + $output .= '
    '; + $output .= ''; + $output .= $js; + + return $output; + + } + + +} diff --git a/pandora_console/godmode/wizards/hostDevices.png b/pandora_console/godmode/wizards/hostDevices.png deleted file mode 100755 index bccf7ba092cc19b100a33675437046561258f65d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5251 zcmb`L=Tj3vyTtcv-ny18iMfovj7YD0gdX7qp$L z$L6I*IRF66s`^+_-}}>gn*D3=Xxfii3d+Z&C)3d;r(YKNAcVx)JbzgN5gOTamEKKL z+6_TW@Ktekb{=*~sHw*AcNnf4YL4=>Mn$58%kOeCy|2YXV-%Kw<|?A~(Xoqt>?teh z8-A|xpjOB;;I@j(K%-Wl*5LVr)B4%tM!(Wog$Q^|ET~n@NMR8YMaiSA&Id~zK*V9w0|fvW0e_ZthaX7{V;fbp;2AcfxxDl$#Ecqu63Tl9IP@Q!1(&sJM0L8yac_6o{( zcH+WgPQf^_+k?R65_|#Ops~QT)=) zEPW`M`Tv{Ze}zOSi?=%a)C9GIGV(m(%bEqwtx~KpdUk%nqV!;_9Cc$__!3G+O6p?R z#M%(f5O3G<8&6H4s;eILZ5@{a6+AtwJPxwv-uP|PngJCBT6!7WDs%N8ii(JonAN#! z4F)n@rVZW>Cvs_ntt-aor!8BzpKCu%7#|R<7Yl$5;uma9Z(-Yy)fN}P7N zaNV4*P*PJos^0$1#sUZliRC??h5wj&!R~ct zGUN_1HTH@K6{rXdR`$=G8-&as6g+P?4C2JM%+Z;hJ<e;Xo>m7V^<=R4U4D0u-K^ddqpDz)a-;v`tX5`;T_ADv6rt*6-q~ohgY#zZvbOs zVwg7jH(IzRsbf`Mxh+OA{XO(0l|jyxAd}P!3kzv!X+fObOQ4-jBq!7I+S=~%DZe?9 zXdEbT3Dv#h+dvl=Zqg8XER(6dyxgBn8*DXPWbjA>6%pKIiNoQrSm_Qol36ER1@(?; zpu*>p63txQHsM{|_VH=I-R^f~p(IMA_zW*Uzq+R8;u|Y(?}GgNB`a5fI4DQUp!BxcT1-p~tlZ;@IxpjX5X4#ed>vQXs}=jN*EKgkUpRd>#lMod zu{OFp*i()zCC?dgrv;YblCS}ZGNEmO)z#HyR6*1~!BTs!zE^7AF$F7ITU)cRvX%^q zGYi~-s=ADoL1bmkFK(Ecb8>RlCu^2||5ov0X@7y|42irWzA;gyp55OnZRm?ersS!s zsR0!WN=i01HvCS$BO$NMG(LwkSM-!ePd#pUJYJ4@u6%F6EUZkcpKC6XYU25^2l`;g}lyi^hX7@TqOG~Rl;FxV}z@chq)~kV`XJU7LGb)`R zYxA=@2k)e=_J5a?p0Q?L8Ck?5ncJ^8+_=EptuzhUDCRS!_l9J(rHQD}1UdrlMf!+vx9bUBknH)N=y(iqbLzbuP%dLjFz!x_p z4k#Jt4OTz+OZtWmS_oO&S7*EzZZ@`SZJf=ZC*#FxMtZHln1hDX#Z&5;w|*(#(0vm>R>GY5LEV)ApY_B7~Azwf#-hw-g&YWt6NBBc;n{CNwgveqNo5^ z92K521=544+F!yXJQiCIsVPe}61y>+AvqpN7z*|@J$U2s=uLeYca zfxs*GLDMJ7A(I?+CP7ViA2i|+uZ^xlL7>F?GHxOMp%~t7%_z*?G^hiH4|wTO-Tmd6 z>DM?O_zm2Gk~yxoAcP74Y|ELbK(BS8)93iB9;BuTZ9A9?+LK>2LNt_S(a%TZDfMy< z$Bwf?z2qhx^Vo%#X(ZV@%82!>+m;cnW8J@1&VRfPVNpp@t;(yoLRo-4;gXjYonvR; zf1AaIQYb?Iy)riDq^?dFF6aZ=-Ia+{>dEw!J=Q+h!N+`;#yfm^dGMzcAi;&2gI3^J#5yi7u%lXr;T z;RUY@<)D|rY?H%k&|NLQ3T(U^{xZUsSzPXD0UP-(eYg8ra7yjS#62`4wv|Wi9kl=gRWS z%#+T2zuTT``S1U2N3wwPK8;d@JiB|^;*1EmIW!AL%|EY(t#za7Jf_yHBr#Z?$HcDF zB(^GlxT06(M`;;&ZLGe(fU~KmeFG5^T`yJg$Rgw6Ox-z!Y`|vMH0-k|uUUWHnhMaG zb=JH1E-}#ZaO0GSV4?6?eOX#PKl%6IeX;t^_c}3QX<}XDdVB2y`JNn3#UbhEvlB!I zQcaldkl&K82H*zQbQ1ZK)9s?EgTFT)j@ogKS{(OhE*MF5jhLuZ@rks?E4-$}yz=iLA1~zh;>`cUSN5FmyVKCqjAbc&Qhi$La~c(xRvWsG^RhWJih3 zuoefA$0swqz?}Z)$?<3JuO#t&ufIPy2OIVB@RY16=|u1~)m9MEYIWzET^^Sm=5Rvr zM}z$n@8S&&z6fiGtw8V;FBvkFrBJW(-a+4R3BB{i5%jJk<>NahJLW-j#jq#guIMB} zAqXr9`F((GkehH)>k-7QRLLmxGnD5XR^~jwJ-2?42Mn*^bzx_@t$>$vFD0&-xm# zmg?_l-7T>nwjtp9b0}rtFp9+sM`Z*kFpa0iRNLm%oy7qVKu%ZDYL0hkIkQmO)f) zWNG53^x0=K-c?UJgMDDa(W2aqhq%>uVPL?^X`{)!lfkvUYCVtSOcem&MlHRetsyn% zR^j1&irUe{1jSFj?_=V})Ff*%KW}fDL*kI5Y>J?|ML#nOOO2>^fKvPs|K1)11OR}- z*{?+oA$92>P?aEnF&Jiee`(Es{ke#+1bYFdPP#~}U#V~fO+qij`b0C2HF z4rxUaoT|02Fz_dB>m}qM?col?Ky&@y%QC}~67U4-F?Eg8wm+rTPzT8O({_mq5c>!X zEJ3NAf~{f?-)M=04i0Me#j9*2A}CXc>S26y!z}Efrx{?=rOl zp|cuOk!yFlxNP=1hxq68KwieJUXm2&v&jRxVhLZx%z(DYB^F5zA~E!BEm}j%*^JHof^bVM_$kdn}Mj>^WuE&CJ+ZR;0HiK2b_gQCv$-- zEuO-Qeh-}t4BPxUp^2nPr-N!-XX4J$dS+^5B{=<4xur?fX!E%7v{dQo9X0ngM9T}z zcHy<1&m*5nrlx&v+bNSbk!+R`NWJ)Aq3Es@>mjB~>yb~%=GHVwLVrrUKvdSruDnof=5!GS}PQjh9T4lQ5oL=Myq@9ufJqfmh4?>})t} z)+dfwWoBw-dpdRMX)Y8&g^xk-m^!gq%^xlQ&Iy3w0qCao1&&X3Q>1MWav;WzELMOE z_OvZQz-cHWW8DY89X~WBe@uXjBVaNsEZ5uFuym$p$9w)bid}Jg%%@Z!?XgeCH#7(U zqPp|fOlI3{!P6)?740cDDppO#(3;+8!ZpuZTEV!})Iy|D33Y)im@;aIy z-+{S$Dwi){5~*M}G2-S@B=274Xc!y!a#5yb`2DQoZPtwOdU2jMhOdspk}&kUwl{Bn5m*7212Nj!Xh<9sX4 z%hh}OUeoT{&Bo;T0z-cMB8gE$Hom>}G0hS|8nc|=DEFz>Pu;{NB?$i^$TB!Pzn5Kp zRBESt2m6r3&Y%j=*}7&?OqBajF^6uu#b?8~>{wLSCz`1RYtN&bId5@I%@cbuc3>7O ztIU|in6G)QyDZcun<=?KYL__MXyhndEYJ(9e=gK;xIY(otJkhCJESzX`e=*prdqn6 z%VfL3!&TuL{59Kf#@?A_F9-MVQ7I9z8a>VKr>8=rOwK=z^;Y{F4SXDJOfpfm-}cEI z{$}V*zN}7PzjGsuj81`GQJkoVk%>XtUVapNvDBM-jO7zv|3!7Im&;dZfl8G{Xi(&y zZ7Q~7T{%@Wp7lssrTEdl*?S=o_uYkS(P=U!*p-Lz-jpY!M_xk+!>IC8&pP(=a zIqky*q{%46<5Op1DH77dSwTeq83Yp$m+w6JtMwPF?MCy zMMbL~IMLYW`>S3r_{cRPm)l=eE#=-xb7t&_x-08e?UGpLcPKrJtSi{iN`FLLW-Jq`j;%SskT-z=H~RSsN+-n4EaK+%0K9G?^s!JE>IuP`*Sn(E zEMkd<0fNWt<{D1*A44GRU%v!EvUT}Y+|T+G*ihN Date: Thu, 14 Feb 2019 11:32:07 +0100 Subject: [PATCH 117/249] WIP H&D base structure Former-commit-id: dace1164c5a568adbb98c187106838d25334f934 --- .../godmode/wizards/HostDevices.class.php | 178 +++--------------- .../godmode/wizards/Wizard.main.php | 62 +++++- 2 files changed, 86 insertions(+), 154 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 6612e0e088..330ae72865 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -68,7 +68,7 @@ class HostDevices extends Wizard /** * Undocumented function. * - * @param integer $page Mensajito. + * @param integer $page Start page, by default 0. * @param string $msg Mensajito. * @param string $icon Mensajito. * @param string $label Mensajito. @@ -81,6 +81,8 @@ class HostDevices extends Wizard string $icon='hostDevices.png', string $label='Host & Devices' ) { + $this->setBreadcrum([]); + $this->id = null; $this->msg = $msg; $this->icon = $icon; @@ -105,6 +107,8 @@ class HostDevices extends Wizard $mode = get_parameter('mode', null); if ($mode === null) { + $this->setBreadcrum(['Host&devices']); + $this->printHeader(); if (extensions_is_enabled_extension('csv_import')) { echo 'Importar csv'; } @@ -114,10 +118,24 @@ class HostDevices extends Wizard } if ($mode == 'importcsv') { + $this->setBreadcrum( + [ + 'Host&devices', + 'Import CSV', + ] + ); + $this->printHeader(); return $this->runCSV(); } if ($mode == 'netscan') { + $this->setBreadcrum( + [ + 'Host&devices', + 'Net scan', + ] + ); + $this->printHeader(); return $this->runNetScan(); } @@ -154,6 +172,7 @@ class HostDevices extends Wizard public function runCSV() { global $config; + if (!check_acl($config['id_user'], 0, 'AW') ) { db_pandora_audit( @@ -187,7 +206,6 @@ class HostDevices extends Wizard { global $config; - echo 'formulario netscan'; check_login(); if (! check_acl($config['id_user'], 0, 'PM')) { @@ -688,158 +706,12 @@ class HostDevices extends Wizard echo ''; ui_require_javascript_file('pandora_modules'); - $javascript = ` - `; - echo $javascript; - - return [ - 'result' => $this->result, - 'id' => $this->id, - 'msg' => $this->msg, - ]; + return [ + 'result' => $this->result, + 'id' => $this->id, + 'msg' => $this->msg, + ]; } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 9a827d73da..6a97cf73a3 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -6,6 +6,37 @@ class Wizard { + /** + * Breadcrum + * + * @var array. + */ + public $breadcrum; + + + /** + * Setter for breadcrum + * + * @param array $str Breadcrum. + * + * @return void + */ + public function setBreadcrum(array $str) + { + $this->breadcrum = $str; + } + + + /** + * Getter for breadcrum + * + * @return array Breadcrum. + */ + public function getBreadcrum() + { + return $this->breadcrum; + } + /** * To be overwritten. @@ -27,6 +58,35 @@ class Wizard } + /** + * Print breadcrum to follow flow. + * + * @return string Breadcrum HTML code. + */ + public function printBreadcrum() + { + return '

    '.implode(' > ', $this->breadcrum).'

    '; + } + + + /** + * Prints a header for current wizard. + * + * @param boolean $return Return HTML or print it. + * + * @return string HTML code for header. + */ + public function printHeader(bool $return=false) + { + $output = $this->printBreadcrum(); + if ($return === false) { + echo $output; + } + + return $output; + } + + /** * Print input using functions html lib. * @@ -168,7 +228,7 @@ class Wizard * * @param array $data Definition of target form to be printed. * - * @return void + * @return string HTML code. */ public function printForm(array $data) { From 070db506b8de05a8d5c3e1a6b5dfb1ce54a30e0a Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 14 Feb 2019 11:53:06 +0100 Subject: [PATCH 118/249] WIP: H&D Former-commit-id: 8f66bccf64b219df20d19d72eb41bec8acdd9bbc --- .../godmode/wizards/HostDevices.class.php | 512 +----------------- .../godmode/wizards/Wizard.main.php | 14 +- 2 files changed, 36 insertions(+), 490 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 330ae72865..2b12530453 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -222,496 +222,38 @@ class HostDevices extends Wizard $user_groups = users_get_groups(false, 'AW', true, false, null, 'id_grupo'); $user_groups = array_keys($user_groups); - if (is_ajax()) { - $get_explanation = (bool) get_parameter('get_explanation', 0); + if (isset($this->page) === false + || $this->page == 0 + ) { + $form = []; - if ($get_explanation) { - $id = (int) get_parameter('id', 0); + // Input task name. + // Input Discovery Server. + // Input Network. + // Input interval. + // Input group. + $form['inputs'] = [ + [ + 'label' => __('Task name'), + 'arguments' => [ + 'name' => 'name', + 'value' => '', + 'type' => 'text', + 'size' => 25, + ], + ], + ]; - $explanation = db_get_value('description', 'trecon_script', 'id_recon_script', $id); - - echo io_safe_output($explanation); - - return; - } - - $get_recon_script_macros = get_parameter('get_recon_script_macros'); - if ($get_recon_script_macros) { - $id_recon_script = (int) get_parameter('id'); - $id_recon_task = (int) get_parameter('id_rt'); - - if (!empty($id_recon_task) && empty($id_recon_script)) { - $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); - } else if (!empty($id_recon_task)) { - $recon_task_id_rs = (int) db_get_value('id_recon_script', 'trecon_task', 'id_rt', $id_recon_task); - - if ($id_recon_script == $recon_task_id_rs) { - $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); - } else { - $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); - } - } else if (!empty($id_recon_script)) { - $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); - } else { - $recon_script_macros = []; - } - - $macros = []; - $macros['base64'] = base64_encode($recon_script_macros); - $macros['array'] = json_decode($recon_script_macros, true); - - echo io_json_mb_encode($macros); - return; - } - - return; + $this->printForm($form); } - // Edit mode. - if (isset($_GET['update']) || (isset($_GET['upd']))) { - $update_recon = true; - if (isset($_GET['upd'])) { - if ($_GET['upd'] != 'update') { - $update_recon = false; - } else { - $id_rt = get_parameter('upd'); - } - } - - if ($update_recon) { - if (!isset($id_rt)) { - $id_rt = (int) get_parameter_get('update'); - } - - $row = db_get_row('trecon_task', 'id_rt', $id_rt); - $name = $row['name']; - $network = $row['subnet']; - $id_recon_server = $row['id_recon_server']; - $description = $row['description']; - $interval = $row['interval_sweep']; - $id_group = $row['id_group']; - $create_incident = $row['create_incident']; - $id_network_profile = $row['id_network_profile']; - $id_os = $row['id_os']; - $recon_ports = $row['recon_ports']; - $snmp_community = $row['snmp_community']; - $snmp_version = $row['snmp_version']; - $snmp3_auth_user = $row['snmp_auth_user']; - $snmp3_auth_pass = $row['snmp_auth_pass']; - $snmp3_privacy_method = $row['snmp_privacy_method']; - $snmp3_privacy_pass = $row['snmp_privacy_pass']; - $snmp3_auth_method = $row['snmp_auth_method']; - $snmp3_security_level = $row['snmp_security_level']; - $id_recon_script = $row['id_recon_script']; - $field1 = $row['field1']; - $field2 = $row['field2']; - $field3 = $row['field3']; - $field4 = $row['field4']; - if ($id_recon_script == 0) { - $mode = 'network_sweep'; - } else { - $mode = 'recon_script'; - } - - $os_detect = $row['os_detect']; - $resolve_names = $row['resolve_names']; - $os_detect = $row['os_detect']; - $parent_detection = $row['parent_detection']; - $parent_recursion = $row['parent_recursion']; - $macros = $row['macros']; - $alias_as_name = $row['alias_as_name']; - $snmp_enabled = $row['snmp_enabled']; - $vlan_enabled = $row['vlan_enabled']; - - $name_script = db_get_value( - 'name', - 'trecon_script', - 'id_recon_script', - $id_recon_script - ); - - if (! in_array($id_group, $user_groups)) { - db_pandora_audit( - 'ACL Violation', - 'Trying to access Recon Task Management' - ); - include 'general/noaccess.php'; - return; - } - } - } else if (isset($_GET['create']) || isset($_GET['crt'])) { - $create_recon = true; - if (isset($_GET['crt'])) { - if ($_GET['crt'] != 'Create') { - $create_recon = false; - } - } - - if ($create_recon) { - $id_rt = -1; - $name = get_parameter('name'); - $network = get_parameter('network'); - $description = get_parameter('description'); - $id_recon_server = 0; - $interval = 0; - $id_group = 0; - $create_incident = 1; - $snmp_community = 'public'; - $snmp3_auth_user = ''; - $snmp3_auth_pass = ''; - $snmp_version = 1; - $snmp3_privacy_method = ''; - $snmp3_privacy_pass = ''; - $snmp3_auth_method = ''; - $snmp3_security_level = ''; - $id_network_profile = 0; - $id_os = -1; - // Any. - $recon_ports = ''; - // Any. - $field1 = ''; - $field2 = ''; - $field3 = ''; - $field4 = ''; - $id_recon_script = 0; - $mode = 'network_sweep'; - $os_detect = 0; - $resolve_names = 0; - $parent_detection = 1; - $parent_recursion = 5; - $macros = ''; - $alias_as_name = 0; - $snmp_enabled = 0; - $vlan_enabled = 0; - } - - $modify = false; - if (($name != '') || ($network != '')) { - $modify = true; - } + if ($this->page == 100) { + return [ + 'result' => $this->result, + 'id' => $this->id, + 'msg' => $this->msg, + ]; } - - $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; - if ($is_windows) { - echo '
    '; - echo __('Warning').': '.__('By default, in Windows, %s only support Standard network sweep, not custom scripts', get_product_name()); - echo '
    '; - } - - $table = new stdClass(); - $table->id = 'table_recon'; - $table->width = '100%'; - $table->cellspacing = 4; - $table->cellpadding = 4; - $table->class = 'databox filters'; - - $table->rowclass[3] = 'network_sweep'; - $table->rowclass[5] = 'network_sweep'; - $table->rowclass[7] = 'network_sweep'; - $table->rowclass[8] = 'network_sweep'; - $table->rowclass[11] = 'network_sweep'; - $table->rowclass[12] = 'network_sweep'; - $table->rowclass[18] = 'network_sweep'; - $table->rowclass[19] = 'network_sweep'; - $table->rowclass[20] = 'network_sweep'; - $table->rowclass[21] = 'network_sweep'; - $table->rowclass[22] = 'network_sweep'; - $table->rowclass[23] = 'network_sweep'; - $table->rowclass[24] = 'network_sweep'; - $table->rowclass[25] = 'network_sweep recon_v3'; - $table->rowclass[26] = 'network_sweep recon_v3'; - $table->rowclass[27] = 'network_sweep recon_v3'; - $table->rowclass[28] = 'network_sweep recon_v3'; - $table->rowclass[29] = 'network_sweep recon_v3'; - $table->rowclass[30] = 'network_sweep recon_v3'; - - $table->rowclass[6] = 'recon_script'; - $table->rowclass[13] = 'recon_script'; - $table->rowclass[14] = 'recon_script'; - $table->rowclass[15] = 'recon_script'; - $table->rowclass[16] = 'recon_script'; - $table->rowclass[17] = 'recon_script'; - // Name. - $table->data[0][0] = ''.__('Task name').''; - $table->data[0][1] = html_print_input_text('name', $name, '', 25, 0, true); - - // Discovery server. - $table->data[1][0] = ''.__('Discovery server').ui_print_help_tip( - __('You must select a Discovery Server for the Task, otherwise the Recon Task will never run'), - true - ); - - $sql = 'SELECT id_server, name - FROM tserver - WHERE server_type = 3 - ORDER BY name'; - $table->data[1][1] = html_print_select_from_sql($sql, 'id_recon_server', $id_recon_server, '', '', '', true); - - $fields['network_sweep'] = __('Network sweep'); - if (!$is_windows) { - $fields['recon_script'] = __('Custom script'); - } - - $table->data[2][0] = ''.__('Mode').''; - $table->data[2][1] = html_print_select($fields, 'mode', $mode, '', '', 0, true); - - // Network. - $table->data[3][0] = ''.__('Network').''; - $table->data[3][0] .= ui_print_help_tip(__('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'), true); - $table->data[3][1] = html_print_input_text('network', $network, '', 25, 0, true); - - // Interval. - $interv_manual = 0; - if ((int) $interval == 0) { - $interv_manual = 1; - } - - $table->data[4][0] = ''.__('Interval'); - $table->data[4][0] .= ui_print_help_tip(__('Manual interval means that it will be executed only On-demand'), true); - - $values = [ - 0 => __('Defined'), - 1 => __('Manual'), - ]; - $table->data[4][1] = html_print_select($values, 'interval_manual_defined', $interv_manual, '', '', '', true); - - $table->data[4][1] .= ''; - $table->data[4][1] .= html_print_extended_select_for_time('interval', $interval, '', '', '0', false, true, false, false); - $table->data[4][1] .= ui_print_help_tip(__('The minimum recomended interval for Recon Task is 5 minutes'), true); - $table->data[4][1] .= ''; - - // Module template. - $table->data[5][0] = ''.__('Module template').''; - - $sql = 'SELECT id_np, name - FROM tnetwork_profile - ORDER BY name'; - $table->data[5][1] = html_print_select_from_sql($sql, 'id_network_profile', $id_network_profile, '', __('None'), 0, true); - - // Recon script. - $data[1] = ''; - $table->data[6][0] = ''.__('Recon script').''; - - $sql = "SELECT id_recon_script, name - FROM trecon_script - WHERE name <> 'IPAM Recon' - ORDER BY name"; - if ($name_script != 'IPAM Recon') { - $table->data[6][1] = html_print_select_from_sql($sql, 'id_recon_script', $id_recon_script, '', '', '', true); - $table->data[6][1] .= "'; - $table->data[6][1] .= $data[1] .= html_print_input_hidden('macros', base64_encode($macros), true); - } else { - $table->data[6][1] = 'IPAM Recon'; - } - - // OS. - $table->data[7][0] = ''.__('OS').''; - - $sql = 'SELECT id_os, name - FROM tconfig_os - ORDER BY name'; - $table->data[7][1] = html_print_select_from_sql($sql, 'id_os', $id_os, '', __('Any'), -1, true); - - // Recon ports. - $table->data[8][0] = ''.__('Ports').''; - $table->data[8][1] = html_print_input_text('recon_ports', $recon_ports, '', 25, 0, true); - $table->data[8][1] .= ui_print_help_tip( - __('Ports defined like: 80 or 80,443,512 or even 0-1024 (Like Nmap command line format). If dont want to do a sweep using portscan, left it in blank'), - true - ); - - // Group. - $table->data[9][0] = ''.__('Group'); - $groups = users_get_groups(false, 'PM', false); - $table->data[9][1] = html_print_select_groups(false, 'PM', false, 'id_group', $id_group, '', '', 0, true); - - // Incident. - $values = [ - 0 => __('No'), - 1 => __('Yes'), - ]; - $table->data[10][0] = ''.__('Incident'); - $table->data[10][1] = html_print_select( - $values, - 'create_incident', - $create_incident, - '', - '', - '', - true - ).' '.ui_print_help_tip(__('Choose if the discovery of a new system creates an incident or not.'), true); - - // Snmp_enabled. - $table->data[11][0] = ''.__('SNMP enabled'); - $table->data[11][1] = html_print_checkbox('snmp_enabled', 1, $snmp_enabled, true); - - // SNMP default community. - $table->data[12][0] = ''.__('SNMP Default community'); - $table->data[12][0] .= ui_print_help_tip(__('You can specify several values, separated by commas, for example: public,mysecret,1234'), true); - $table->data[12][1] = html_print_input_text('snmp_community', $snmp_community, '', 35, 0, true); - - // SNMP version. - $snmp_versions['1'] = 'v. 1'; - $snmp_versions['2'] = 'v. 2'; - $snmp_versions['2c'] = 'v. 2c'; - $snmp_versions['3'] = 'v. 3'; - $table->data[24][0] = ''._('SNMP version'); - $table->data[24][1] = html_print_select($snmp_versions, 'snmp_version', $snmp_version, '', '', 0, true); - - $table->data[25][0] = ''.__('Auth user'); - $table->data[25][1] = html_print_input_text( - 'snmp_auth_user', - $snmp3_auth_user, - '', - 15, - 60, - true, - '', - false, - '', - '' - ); - $table->data[26][0] = ''.__('Auth password').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); - $table->data[26][1] = html_print_input_password( - 'snmp_auth_pass', - $snmp3_auth_pass, - '', - 15, - 60, - true, - '', - false, - '' - ); - $table->data[26][1] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_mmen', true); - - $table->data[27][0] = ''.__('Privacy method'); - $table->data[27][1] = html_print_select(['DES' => __('DES'), 'AES' => __('AES')], 'snmp_privacy_method', $snmp3_privacy_method, '', '', '', true, false, false, '', ''); - $table->data[28][0] = ''.__('Privacy pass').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); - $table->data[28][1] = html_print_input_password( - 'snmp_privacy_pass', - $snmp3_privacy_pass, - '', - 15, - 60, - true, - '', - false, - '' - ); - $table->data[29][0] = ''.__('Auth method'); - $table->data[29][1] = html_print_select(['MD5' => __('MD5'), 'SHA' => __('SHA')], 'snmp_auth_method', $snmp3_auth_method, '', '', '', true, false, false, '', ''); - $table->data[30][0] = ''.__('Security level'); - $table->data[30][1] = html_print_select( - [ - 'noAuthNoPriv' => __('Not auth and not privacy method'), - 'authNoPriv' => __('Auth and not privacy method'), - 'authPriv' => __('Auth and privacy method'), - ], - 'snmp_security_level', - $snmp3_security_level, - '', - '', - '', - true, - false, - false, - '', - '' - ); - - // Explanation. - $explanation = db_get_value('description', 'trecon_script', 'id_recon_script', $id_recon_script); - - $table->data[13][0] = ''.__('Explanation').''; - $table->data[13][1] = "'.html_print_textarea('explanation', 4, 60, $explanation, 'style="width: 388px;"', true); - - // A hidden "model row" to clone it from javascript to add fields dynamicaly. - $data = []; - $data[0] = 'macro_desc'; - $data[0] .= ui_print_help_tip('macro_help', true); - $data[1] = html_print_input_text('macro_name', 'macro_value', '', 100, 255, true); - $table->colspan['macro_field'][1] = 3; - $table->rowstyle['macro_field'] = 'display:none'; - $table->data['macro_field'] = $data; - - // If there are $macros, we create the form fields. - if (!empty($macros)) { - $macros = json_decode($macros, true); - - foreach ($macros as $k => $m) { - $data = []; - $data[0] = ''.$m['desc'].''; - if (!empty($m['help'])) { - $data[0] .= ui_print_help_tip($m['help'], true); - } - - if ($m['hide']) { - $data[1] = html_print_input_password($m['macro'], $m['value'], '', 100, 255, true); - } else { - $data[1] = html_print_input_text($m['macro'], $m['value'], '', 100, 255, true); - } - - $table->colspan['macro'.$m['macro']][1] = 3; - $table->rowclass['macro'.$m['macro']] = 'macro_field'; - - $table->data['macro'.$m['macro']] = $data; - } - } - - // Comments. - $table->data[18][0] = ''.__('Comments'); - $table->data[18][1] = html_print_input_text('description', $description, '', 45, 0, true); - - // OS detection. - $table->data[19][0] = ''.__('OS detection'); - $table->data[19][1] = html_print_checkbox('os_detect', 1, $os_detect, true); - - // Name resolution. - $table->data[20][0] = ''.__('Name resolution'); - $table->data[20][1] = html_print_checkbox('resolve_names', 1, $resolve_names, true); - - // Parent detection. - $table->data[21][0] = ''.__('Parent detection'); - $table->data[21][1] = html_print_checkbox('parent_detection', 1, $parent_detection, true); - - // Parent recursion. - $table->data[22][0] = ''.__('Parent recursion'); - $table->data[22][1] = html_print_input_text('parent_recursion', $parent_recursion, '', 5, 0, true).ui_print_help_tip(__('Maximum number of parent hosts that will be created if parent detection is enabled.'), true); - - // Is vlan_enabled. - $table->data[23][0] = ''.__('Vlan enabled'); - $table->data[23][1] = html_print_checkbox('vlan_enabled', 1, $vlan_enabled, true); - - // Alias as name - // NOTE: The 7.0NG Recon Server will not generate random names, since IP - // address collisions could have other consequences. - // $table->data[22][0] = "".__('Alias as Name'); - // $table->data[22][1] = html_print_checkbox ('alias_as_name', 1, $alias_as_name, true); - // Different Form url if it's a create or if it's a update form. - echo '
    '; - html_print_table($table); - echo '
    '; - - if ($id_rt != -1) { - if ($name_script != 'IPAM Recon') { - html_print_submit_button(__('Update'), 'crt', false, 'class="sub upd"'); - } - } else { - html_print_submit_button(__('Add'), 'crt', false, 'class="sub wand"'); - } - - echo '
    '; - - echo '
    '; - - ui_require_javascript_file('pandora_modules'); - - return [ - 'result' => $this->result, - 'id' => $this->id, - 'msg' => $this->msg, - ]; } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 6a97cf73a3..743d82dd11 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -105,9 +105,9 @@ class Wizard return html_print_input_text( $data['name'], $data['value'], - $data['alt'] = '', - $data['size'] = 50, - $data['maxlength'] = 255, + ((isset($data['alt']) === true) ? $data['alt'] : ''), + ((isset($data['size']) === true) ? $data['size'] : 50), + ((isset($data['maxlength']) === true) ? $data['maxlength'] : 255), ((isset($data['return']) === true) ? $data['return'] : true), ((isset($data['disabled']) === true) ? $data['disabled'] : false), ((isset($data['required']) === true) ? $data['required'] : false), @@ -230,7 +230,7 @@ class Wizard * * @return string HTML code. */ - public function printForm(array $data) + public function printForm(array $data, bool $return=false) { $form = $data['form']; $inputs = $data['inputs']; @@ -243,13 +243,17 @@ class Wizard foreach ($inputs as $input) { $output .= '
  • '; - $output .= '
  • '; + $output .= $this->printInput($input['arguments']).''; } $output .= '

'; $output .= ''; $output .= $js; + if ($return === false) { + echo $output; + } + return $output; } From 8acb658266ac79153027f01c62647c325c52099e Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 14 Feb 2019 13:27:49 +0100 Subject: [PATCH 119/249] WIP: H&D Former-commit-id: 7e74f1330b7e5cfdab3757ec62523942a1b4fe9f --- pandora_console/godmode/servers/discovery.php | 1 - .../godmode/wizards/HostDevices.class.php | 182 ++++++++++++++++-- .../godmode/wizards/Wizard.main.php | 81 +++++++- pandora_console/include/styles/wizard.css | 11 ++ 4 files changed, 254 insertions(+), 21 deletions(-) create mode 100644 pandora_console/include/styles/wizard.css diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index e02d62783e..39c31b9465 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -52,7 +52,6 @@ if ($classname_selected !== null) { $wiz = new $classname_selected($page); $wiz->run(); // TODO: Here we'll controlle if return is a valid recon task id. - exit(); } if ($classname_selected === null) { diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 2b12530453..421ea07484 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -1,6 +1,7 @@ page) === false - || $this->page == 0 - ) { - $form = []; + if (isset($this->page) && $this->page == 1) { + // Parse page 0 responses. + $this->parseNetScan(); + } - // Input task name. - // Input Discovery Server. - // Input Network. - // Input interval. - // Input group. - $form['inputs'] = [ - [ - 'label' => __('Task name'), + if (!isset($this->page) || $this->page == 0) { + // Interval. + $interv_manual = 0; + if ((int) $interval == 0) { + $interv_manual = 1; + } + + if (isset($this->page) === false + || $this->page == 0 + ) { + $form = []; + + // Input task name. + $form['inputs'][] = [ + 'label' => ''.__('Task name').'', + 'arguments' => [ + 'name' => 'taskname', + 'value' => '', + 'type' => 'text', + 'size' => 25, + ], + ]; + + // Input Discovery Server. + $form['inputs'][] = [ + 'label' => ''.__('Discovery server').''.ui_print_help_tip( + __('You must select a Discovery Server to run the Task, otherwise the Recon Task will never run'), + true + ), + 'arguments' => [ + 'type' => 'select_from_sql', + 'sql' => sprintf( + 'SELECT id_server, name + FROM tserver + WHERE server_type = %d + ORDER BY name', + SERVER_TYPE_DISCOVERY + ), + 'name' => 'id_recon_server', + 'selected' => 0, + 'return' => true, + ], + ]; + + // Input Network. + $form['inputs'][] = [ + + 'label' => ''.__('Network').''.ui_print_help_tip( + __('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'), + true + ), 'arguments' => [ 'name' => 'name', 'value' => '', 'type' => 'text', 'size' => 25, ], - ], - ]; + ]; - $this->printForm($form); + // Input interval. + $form['inputs'][] = [ + 'label' => ''.__('Interval').''.ui_print_help_tip( + __('Manual interval means that it will be executed only On-demand'), + true + ), + 'arguments' => [ + 'type' => 'select', + 'selected' => $interv_manual, + 'fields' => [ + 0 => __('Defined'), + 1 => __('Manual'), + ], + 'name' => 'interval_manual_defined', + 'return' => true, + ], + 'extra' => ''.html_print_extended_select_for_time( + 'interval', + $interval, + '', + '', + '0', + false, + true, + false, + false + ).ui_print_help_tip( + __('The minimum recomended interval for Recon Task is 5 minutes'), + true + ).'', + ]; + + // Input Group. + $form['inputs'][] = [ + 'label' => ''.__('Group').'', + 'arguments' => [ + 'name' => 'id_group', + 'privilege' => 'PM', + 'type' => 'select_groups', + 'return' => true, + ], + ]; + + // Hidden, page. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'page', + 'value' => ($this->page + 1), + 'type' => 'hidden', + 'return' => true, + ], + ]; + + // Submit button. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Next'), + 'type' => 'submit', + 'attributes' => 'class="sub next"', + 'return' => true, + ], + ]; + + $form['form'] = [ + 'method' => 'POST', + 'action' => '#', + ]; + + $form['js'] = ' + $("select#interval_manual_defined").change(function() { + if ($("#interval_manual_defined").val() == 1) { + $("#interval_manual_container").hide(); + $("#text-interval_text").val(0); + $("#hidden-interval").val(0); + } + else { + $("#interval_manual_container").show(); + $("#text-interval_text").val(10); + $("#hidden-interval").val(600); + $("#interval_units").val(60); + } + }).change();'; + + // Print NetScan page 0. + $this->printForm($form); + } + } + + if ($this->page == 1) { + // Page 1. + echo 'page 1!'; } if ($this->page == 100) { diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 743d82dd11..e8722ea8e8 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -45,6 +45,7 @@ class Wizard */ public function run() { + ui_require_css_file('wizard'); } @@ -214,6 +215,77 @@ class Wizard ((isset($data['options']) === true) ? $data['options'] : false) ); + case 'select': + return html_print_select( + $data['fields'], + $data['name'], + ((isset($data['selected']) === true) ? $data['selected'] : ''), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['nothing']) === true) ? $data['nothing'] : ''), + ((isset($data['nothing_value']) === true) ? $data['nothing_value'] : 0), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['multiple']) === true) ? $data['multiple'] : false), + ((isset($data['sort']) === true) ? $data['sort'] : true), + ((isset($data['class']) === true) ? $data['class'] : ''), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['style']) === true) ? $data['style'] : false), + ((isset($data['option_style']) === true) ? $data['option_style'] : false), + ((isset($data['size']) === true) ? $data['size'] : false), + ((isset($data['modal']) === true) ? $data['modal'] : false), + ((isset($data['message']) === true) ? $data['message'] : ''), + ((isset($data['select_all']) === true) ? $data['select_all'] : false) + ); + + case 'select_from_sql': + return html_print_select_from_sql( + $data['sql'], + $data['name'], + ((isset($data['selected']) === true) ? $data['selected'] : ''), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['nothing']) === true) ? $data['nothing'] : ''), + ((isset($data['nothing_value']) === true) ? $data['nothing_value'] : '0'), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['multiple']) === true) ? $data['multiple'] : false), + ((isset($data['sort']) === true) ? $data['sort'] : true), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['style']) === true) ? $data['style'] : false), + ((isset($data['size']) === true) ? $data['size'] : false), + ((isset($data['trucate_size']) === true) ? $data['trucate_size'] : GENERIC_SIZE_TEXT) + ); + + case 'select_groups': + return html_print_select_groups( + ((isset($data['id_user']) === true) ? $data['id_user'] : false), + ((isset($data['privilege']) === true) ? $data['privilege'] : 'AR'), + ((isset($data['returnAllGroup']) === true) ? $data['returnAllGroup'] : true), + $data['name'], + ((isset($data['selected']) === true) ? $data['selected'] : ''), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['nothing']) === true) ? $data['nothing'] : ''), + ((isset($data['nothing_value']) === true) ? $data['nothing_value'] : 0), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['multiple']) === true) ? $data['multiple'] : false), + ((isset($data['sort']) === true) ? $data['sort'] : true), + ((isset($data['class']) === true) ? $data['class'] : ''), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['style']) === true) ? $data['style'] : false), + ((isset($data['option_style']) === true) ? $data['option_style'] : false), + ((isset($data['id_group']) === true) ? $data['id_group'] : false), + ((isset($data['keys_field']) === true) ? $data['keys_field'] : 'id_grupo'), + ((isset($data['strict_user']) === true) ? $data['strict_user'] : false), + ((isset($data['delete_groups']) === true) ? $data['delete_groups'] : false), + ((isset($data['include_groups']) === true) ? $data['include_groups'] : false) + ); + + case 'submit': + return html_print_submit_button( + ((isset($data['label']) === true) ? $data['label'] : 'OK'), + ((isset($data['name']) === true) ? $data['name'] : ''), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['attributes']) === true) ? $data['attributes'] : ''), + ((isset($data['return']) === true) ? $data['return'] : false) + ); + default: // Ignore. break; @@ -239,16 +311,19 @@ class Wizard $output = '
'; - $ouput .= '
    '; + $output .= '
      '; foreach ($inputs as $input) { $output .= '
    • '; - $output .= $this->printInput($input['arguments']).'
    • '; + $output .= $this->printInput($input['arguments']); + // Allow dynamic content. + $output .= $input['extra']; + $output .= ''; } $output .= '
    '; $output .= ''; - $output .= $js; + $output .= ''; if ($return === false) { echo $output; diff --git a/pandora_console/include/styles/wizard.css b/pandora_console/include/styles/wizard.css new file mode 100644 index 0000000000..26f4ac0385 --- /dev/null +++ b/pandora_console/include/styles/wizard.css @@ -0,0 +1,11 @@ +ul.wizard { +} + +ul.wizard li { + padding: 10px; +} + +ul.wizard li > label { + width: 250px; + display: inline-block; +} From 40143a1402dabbb464a3673c9b78be0ef41953b5 Mon Sep 17 00:00:00 2001 From: Daniel Barbero Date: Thu, 14 Feb 2019 15:50:13 +0100 Subject: [PATCH 120/249] fixed reports Former-commit-id: 99e8d84b1db440156f8b382ded51be7c39322eed --- .../include/functions_reporting_html.php | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index 2c29258d05..935c12c871 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -2955,7 +2955,7 @@ function reporting_html_availability_graph($table, $item, $pdf=0) global $config; $metaconsole_on = is_metaconsole(); - if ($metaconsole_on) { + if ($metaconsole_on !== false) { $hack_metaconsole = '../../'; } else { $hack_metaconsole = ''; @@ -2997,7 +2997,10 @@ function reporting_html_availability_graph($table, $item, $pdf=0) break; } - $sla_value = sla_truncate($chart['sla_value'], $config['graph_precision']).'%'; + $sla_value = sla_truncate( + $chart['sla_value'], + $config['graph_precision'] + ).'%'; $checks_resume = '('.$chart['checks_ok'].'/'.$chart['checks_total'].')'; } @@ -3005,7 +3008,10 @@ function reporting_html_availability_graph($table, $item, $pdf=0) $table1->data[0][1] = $chart['chart']; $table1->data[0][2] = "".$sla_value.''; $table1->data[0][3] = $checks_resume; - $tables_chart .= html_print_table($table1, true); + $tables_chart .= html_print_table( + $table1, + true + ); } if ($item['type'] == 'availability_graph') { @@ -3045,13 +3051,20 @@ function reporting_html_availability_graph($table, $item, $pdf=0) $table2->data[0][11] = ''.__('Ignore time').''; } - $table->colspan['charts']['cell'] = 2; - $table->data['charts']['cell'] = $tables_chart; - $table->colspan['legend']['cell'] = 2; - $table->data['legend']['cell'] = html_print_table($table2, true); - if ($pdf !== 0) { - return $tables_chart.'
    '.html_print_table($table2, true); + $tables_chart .= html_print_table( + $table2, + true + ); + return $tables_chart; + } else { + $table->colspan['charts']['cell'] = 2; + $table->data['charts']['cell'] = $tables_chart; + $table->colspan['legend']['cell'] = 2; + $table->data['legend']['cell'] = html_print_table( + $table2, + true + ); } } From 0d7ea0d056030ffd5d2300a23ab6c122f72133d5 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 14 Feb 2019 16:56:03 +0100 Subject: [PATCH 121/249] Added CSV report and copy a lot of not revisted code Former-commit-id: 005362b157450862501963770df3fd0419bc573a --- .../godmode/wizards/HostDevices.class.php | 200 ++++++++++++++++-- .../godmode/wizards/Wizard.main.php | 2 +- 2 files changed, 189 insertions(+), 13 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 421ea07484..8a6a14f892 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -8,6 +8,10 @@ require_once $config['homedir'].'/include/functions_users.php'; */ class HostDevices extends Wizard { + // CSV constants. + const HDW_CSV_NOT_DATA = 0; + const HDW_CSV_DUPLICATED = 0; + const HDW_CSV_GROUP_EXISTS = 0; /** * Undocumented variable @@ -114,11 +118,10 @@ class HostDevices extends Wizard if ($mode === null) { $this->setBreadcrum(['Host&devices']); $this->printHeader(); - if (extensions_is_enabled_extension('csv_import')) { - echo 'Importar csv'; - } + echo 'Importar csv'; echo 'Escanear red'; + return; } @@ -126,7 +129,7 @@ class HostDevices extends Wizard $this->setBreadcrum( [ 'Host&devices', - 'Import CSV', + 'Import CSV', ] ); $this->printHeader(); @@ -178,8 +181,7 @@ class HostDevices extends Wizard { global $config; - if (!check_acl($config['id_user'], 0, 'AW') - ) { + if (!check_acl($config['id_user'], 0, 'AW')) { db_pandora_audit( 'ACL Violation', 'Trying to access db status' @@ -188,17 +190,133 @@ class HostDevices extends Wizard return; } - if (!extensions_is_enabled_extension('csv_import')) { - ui_print_error_message( + if (!isset($this->page) || $this->page == 0) { + $this->printForm( [ - 'message' => __('Extension CSV Import is not enabled.'), - 'no_close' => true, + 'form' => [ + 'action' => '#', + 'method' => 'POST', + 'enctype' => 'multipart/form-data', + ], + 'inputs' => [ + [ + 'arguments' => [ + 'type' => 'hidden', + 'name' => 'import_file', + 'value' => 1, + 'return' => true, + ], + ], + [ + 'label' => __('Upload file'), + 'arguments' => [ + 'type' => 'file', + 'name' => 'file', + 'return' => true, + ], + ], + [ + 'label' => __('Server'), + 'arguments' => [ + 'type' => 'select', + 'fields' => servers_get_names(), + 'name' => 'server', + 'return' => true, + ], + ], + [ + 'label' => __('Separator'), + 'arguments' => [ + 'type' => 'select', + 'fields' => [ + ',' => ',', + ';' => ';', + ':' => ':', + '.' => '.', + '#' => '#', + ], + 'name' => 'separator', + 'return' => true, + ], + ], + [ + 'arguments' => [ + 'name' => 'page', + 'value' => 1, + 'type' => 'hidden', + 'return' => true, + ], + ], + [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Go'), + 'type' => 'submit', + 'attributes' => 'class="sub next"', + 'return' => true, + ], + ], + ], ] ); - return; } - include_once $config['homedir'].'/enterprise/extensions/csv_import/main.php'; + if (isset($this->page) && $this->page == 1) { + $server = get_parameter('server'); + $separator = get_parameter('separator'); + + if (isset($_FILES['file'])) { + $file_status_code = get_file_upload_status('file'); + $file_status = translate_file_upload_status($file_status_code); + + if ($file_status === true) { + $error_message = []; + $line = -1; + $file = fopen($_FILES['file']['tmp_name'], 'r'); + if (! empty($file)) { + while (($data = fgetcsv($file, 1000, $separator)) !== false) { + $result = $this->processCsvData($data, $server); + $line++; + if ($result === HDW_CSV_NOT_DATA || $result === HDW_CSV_DUPLICATED || $result === HDW_CSV_GROUP_EXISTS) { + if ($result === HDW_CSV_NOT_DATA) { + $error_message[] = __('No data or wrong separator in line ').$line.'
    '; + } else if ($result === HDW_CSV_DUPLICATED) { + $error_message[] = __('Agent ').io_safe_input($data[0]).__(' duplicated').'
    '; + } else { + $error_message[] = __("Id group %s in line %s doesn't exist in %s", $data[4], $line, get_product_name()).'
    '; + } + + continue; + } + + ui_print_result_message( + $result !== false, + __('Created agent %s', $result['agent_name']), + __('Could not create agent %s', $result['agent_name']) + ); + } + } + + fclose($file); + + if (empty($error_message)) { + ui_print_success_message(__('File processed')); + } else { + foreach ($error_message as $msg) { + ui_print_error_message($msg); + } + } + } else { + ui_print_error_message($file_status); + } + + @unlink($_FILES['file']['tmp_name']); + } else { + ui_print_error_message(__('No input file detected')); + } + + echo $this->breadcrum[0]; + } } @@ -405,4 +523,62 @@ class HostDevices extends Wizard } + /** + * Process the csv of agent. + * + * @param array $data Data of agent. + * @param string $server Name of server. + * + * @return array with data porcessed. + */ + private static function processCsvData($data, $server='') + { + if (empty($data) || count($data) < 5) { + return HDW_CSV_NOT_DATA; + } + + $data['network_components'] = array_slice($data, 6); + $data['agent_name'] = io_safe_input($data[0]); + $data['alias'] = io_safe_input($data[0]); + $data['ip_address'] = $data[1]; + $data['id_os'] = $data[2]; + $data['interval'] = $data[3]; + $data['id_group'] = $data[4]; + $data['comentarios'] = io_safe_input($data[5]); + + $exists = (bool) agents_get_agent_id($data['agent_name']); + if ($exists) { + return HDW_CSV_DUPLICATED; + } + + $group_exists_in_pandora = (bool) groups_get_group_by_id($data['id_group']); + if (!$group_exists_in_pandora) { + return HDW_CSV_GROUP_EXISTS; + } + + $data['id_agent'] = agents_create_agent( + $data['agent_name'], + $data['id_group'], + $data['interval'], + $data['ip_address'], + [ + 'id_os' => $data['id_os'], + 'server_name' => $server, + 'modo' => 1, + 'alias' => $data['alias'], + 'comentarios' => $data['comentarios'], + ] + ); + + foreach ($data['network_components'] as $id_network_component) { + network_components_create_module_from_network_component( + (int) $id_network_component, + $data['id_agent'] + ); + } + + return $data; + } + + } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index e8722ea8e8..3298a2e0e7 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -308,7 +308,7 @@ class Wizard $inputs = $data['inputs']; $js = $data['js']; - $output = '
    '; $output .= '
      '; From 7df9d4f78b09cd35157457f2177e7e526ec871f6 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 14 Feb 2019 17:14:01 +0100 Subject: [PATCH 122/249] WIP: H&D merge Former-commit-id: d53f7d5abed5cfc8d45e6a42bfd52089ff463ff3 --- .../godmode/wizards/HostDevices.class.php | 295 ++++++++++++++++-- .../godmode/wizards/Wizard.main.php | 74 ++++- pandora_console/include/functions_html.php | 1 + pandora_console/include/styles/wizard.css | 6 +- 4 files changed, 344 insertions(+), 32 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 8a6a14f892..e6117afa4a 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -27,13 +27,6 @@ class HostDevices extends Wizard */ public $result; - /** - * Undocumented variable - * - * @var [type] - */ - public $id; - /** * Undocumented variable * @@ -69,6 +62,13 @@ class HostDevices extends Wizard */ public $page; + /** + * Stores all needed parameters to create a recon task. + * + * @var array + */ + public $task; + /** * Undocumented function. @@ -88,7 +88,7 @@ class HostDevices extends Wizard ) { $this->setBreadcrum([]); - $this->id = null; + $this->task = []; $this->msg = $msg; $this->icon = $icon; $this->label = $label; @@ -488,21 +488,7 @@ class HostDevices extends Wizard 'action' => '#', ]; - $form['js'] = ' - $("select#interval_manual_defined").change(function() { - if ($("#interval_manual_defined").val() == 1) { - $("#interval_manual_container").hide(); - $("#text-interval_text").val(0); - $("#hidden-interval").val(0); - } - else { - $("#interval_manual_container").show(); - $("#text-interval_text").val(10); - $("#hidden-interval").val(600); - $("#interval_units").val(60); - } - }).change();'; - + // XXX: Could be improved validating inputs before continue (JS) // Print NetScan page 0. $this->printForm($form); } @@ -510,7 +496,268 @@ class HostDevices extends Wizard if ($this->page == 1) { // Page 1. - echo 'page 1!'; + $form = []; + // Hidden, id_rt. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'task', + 'value' => $this->task['id_rt'], + 'type' => 'hidden', + 'return' => true, + ], + ]; + + // Hidden, page. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'page', + 'value' => ($this->page + 1), + 'type' => 'hidden', + 'return' => true, + ], + ]; + + $form['inputs'][] = [ + 'extra' => '

      Please, configure task '.io_safe_output($this->task['name']).'

      ', + ]; + + // Input: Module template. + $form['inputs'][] = [ + 'label' => __('Module template'), + 'arguments' => [ + 'name' => 'id_network_profile', + 'type' => 'select_from_sql', + 'sql' => 'SELECT id_np, name + FROM tnetwork_profile + ORDER BY name', + 'return' => true, + + ], + ]; + + // Feature configuration. + // Input: Module template. + $form['inputs'][] = [ + 'label' => __('SNMP enabled'), + 'arguments' => [ + 'name' => 'snmp_enabled', + 'type' => 'switch', + 'return' => true, + 'onclick' => "\$('#snmp_extra').toggle();", + + ], + ]; + + // SNMP CONFIGURATION. + $form['inputs'][] = [ + 'hidden' => 1, + 'block_id' => 'snmp_extra', + 'block_content' => [ + 'label' => __('SNMP version'), + 'arguments' => [ + 'name' => 'auth_strings', + 'fields' => [ + '1' => 'v. 1', + '2c' => 'v. 2c', + '3' => 'v. 3', + ], + 'type' => 'select', + 'script' => "\$('#snmp_options_v'+this.value).toggle()", + 'return' => true, + ], + ], + ]; + + $form['inputs'][] = [ + 'hidden' => 1, + 'block_id' => 'snmp_options_v1', + 'block_content' => [ + 'label' => __('Community'), + 'arguments' => [ + 'name' => 'community', + 'type' => 'text', + 'size' => 25, + 'return' => true, + + ], + ], + ]; + + // Input: WMI enabled. + $form['inputs'][] = [ + 'label' => __('WMI enabled'), + 'arguments' => [ + 'name' => 'wmi_enabled', + 'type' => 'switch', + 'return' => true, + 'onclick' => "\$('#wmi_extra').toggle();", + + ], + ]; + + // WMI CONFIGURATION. + $form['inputs'][] = [ + 'label' => __('WMI Auth. strings'), + 'hidden' => 1, + 'id' => 'wmi_extra', + 'arguments' => [ + 'name' => 'auth_strings', + 'type' => 'text', + 'return' => true, + + ], + ]; + + // Input: Module template. + $form['inputs'][] = [ + 'label' => __('OS detection'), + 'arguments' => [ + 'name' => 'os_detect', + 'type' => 'switch', + 'return' => true, + + ], + ]; + + // Input: Name resolution. + $form['inputs'][] = [ + 'label' => __('Name resolution'), + 'arguments' => [ + 'name' => 'resolve_names', + 'type' => 'switch', + 'return' => true, + ], + ]; + + // Input: Parent detection. + $form['inputs'][] = [ + 'label' => __('Parent detection'), + 'arguments' => [ + 'name' => 'parent_detection', + 'type' => 'switch', + 'return' => true, + ], + ]; + + // Input: VLAN enabled. + $form['inputs'][] = [ + 'label' => __('VLAN enabled'), + 'arguments' => [ + 'name' => 'os_detect', + 'type' => 'switch', + 'return' => true, + ], + ]; + + // Submit button. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Next'), + 'type' => 'submit', + 'attributes' => 'class="sub next"', + 'return' => true, + ], + ]; + + $form['form'] = [ + 'method' => 'POST', + 'action' => '#', + ]; + + $this->printForm($form); + } + + if ($this->page == 2) { + // Interval and schedules. + $interv_manual = 0; + if ((int) $interval == 0) { + $interv_manual = 1; + } + + $form['inputs'][] = [ + 'label' => ''.__('Interval').''.ui_print_help_tip( + __('Manual interval means that it will be executed only On-demand'), + true + ), + 'arguments' => [ + 'type' => 'select', + 'selected' => $interv_manual, + 'fields' => [ + 0 => __('Defined'), + 1 => __('Manual'), + ], + 'name' => 'interval_manual_defined', + 'return' => true, + ], + 'extra' => ''.html_print_extended_select_for_time( + 'interval', + $interval, + '', + '', + '0', + false, + true, + false, + false + ).ui_print_help_tip( + __('The minimum recomended interval for Recon Task is 5 minutes'), + true + ).'', + ]; + + // Hidden, id_rt. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'task', + 'value' => $this->task['id_rt'], + 'type' => 'hidden', + 'return' => true, + ], + ]; + + // Hidden, page. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'page', + 'value' => ($this->page + 1), + 'type' => 'hidden', + 'return' => true, + ], + ]; + + // Submit button. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Next'), + 'type' => 'submit', + 'attributes' => 'class="sub next"', + 'return' => true, + ], + ]; + + $form['form'] = [ + 'method' => 'POST', + 'action' => '#', + ]; + + $form['js'] = ' +$("select#interval_manual_defined").change(function() { + if ($("#interval_manual_defined").val() == 1) { + $("#interval_manual_container").hide(); + $("#text-interval_text").val(0); + $("#hidden-interval").val(0); + } + else { + $("#interval_manual_container").show(); + $("#text-interval_text").val(10); + $("#hidden-interval").val(600); + $("#interval_units").val(60); + } +}).change();'; + + $this->printForm($form); } if ($this->page == 100) { diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 3298a2e0e7..c164b287b7 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -95,7 +95,7 @@ class Wizard * * @return string HTML code for desired input. */ - public function printInput(array $data) + public function printInput($data) { if (is_array($data) === false) { return ''; @@ -286,6 +286,20 @@ class Wizard ((isset($data['return']) === true) ? $data['return'] : false) ); + case 'checkbox': + return html_print_checkbox( + $data['name'], + $data['value'], + ((isset($data['checked']) === true) ? $data['checked'] : false), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['disabled']) === true) ? $data['disabled'] : false), + ((isset($data['script']) === true) ? $data['script'] : ''), + ((isset($data['disabled_hidden']) === true) ? $data['disabled_hidden'] : false) + ); + + case 'switch': + return html_print_switch($data); + default: // Ignore. break; @@ -295,10 +309,60 @@ class Wizard } + /** + * Print a block of inputs. + * + * @param array $input Definition of target block to be printed. + * @param boolean $return Return as string or direct output. + * + * @return string HTML content. + */ + public function printBlock(array $input, bool $return=false) + { + $output = ''; + if ($input['hidden'] == 1) { + $class = ' class="hidden"'; + } else { + $class = ''; + } + + if (is_array($input['block_content']) === true) { + // Print independent block of inputs. + $output .= '
    • '; + $output .= '
        '; + foreach ($input['block_content'] as $input) { + $output .= $this->printBlock($input, $return); + } + + $output .= '
    • '; + } else { + if ($input['arguments']['type'] != 'hidden') { + $output .= '
    • '; + $output .= ''; + $output .= $this->printInput($input['arguments']); + // Allow dynamic content. + $output .= $input['extra']; + $output .= '
    • '; + } else { + $output .= $this->printInput($input['arguments']); + // Allow dynamic content. + $output .= $input['extra']; + } + } + + if ($return === false) { + echo $output; + } + + return $output; + } + + /** * Print a form. * - * @param array $data Definition of target form to be printed. + * @param array $data Definition of target form to be printed. + * @param boolean $return Return as string or direct output. * * @return string HTML code. */ @@ -314,11 +378,7 @@ class Wizard $output .= '
        '; foreach ($inputs as $input) { - $output .= '
      • '; - $output .= $this->printInput($input['arguments']); - // Allow dynamic content. - $output .= $input['extra']; - $output .= '
      • '; + $output .= $this->printBlock($input, true); } $output .= '
      '; diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 8985655745..ca23d3b029 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -3016,6 +3016,7 @@ function html_print_switch($attributes=[]) 'id', 'class', 'name', + 'onclick', ]; foreach ($valid_attrs as $va) { if (!isset($attributes[$va])) { diff --git a/pandora_console/include/styles/wizard.css b/pandora_console/include/styles/wizard.css index 26f4ac0385..fdaf5afa4b 100644 --- a/pandora_console/include/styles/wizard.css +++ b/pandora_console/include/styles/wizard.css @@ -5,7 +5,11 @@ ul.wizard li { padding: 10px; } -ul.wizard li > label { +ul.wizard li > label:not(.p-switch) { width: 250px; display: inline-block; } + +.hidden { + display: none; +} From 39958741763fb23de8f75fca6e7d675312461fa2 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 14 Feb 2019 17:19:20 +0100 Subject: [PATCH 123/249] WIP: H&D: merge Former-commit-id: c1e04b80a49fb0a9870676dc8f59732cd595fbc0 --- .../godmode/wizards/HostDevices.class.php | 249 +++- pandora_console/install.php | 1090 ----------------- 2 files changed, 192 insertions(+), 1147 deletions(-) delete mode 100644 pandora_console/install.php diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index e6117afa4a..23250995db 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -327,6 +327,93 @@ class HostDevices extends Wizard */ public function parseNetScan() { + if ($this->page == 0) { + // Error. Must not be here. + return true; + } + + // Validate response from page 0. No, not a bug, we're always 1 page + // from 'validation' page. + if ($this->page == 1) { + $taskname = get_parameter('taskname', ''); + $comment = get_parameter('comment', ''); + $server_id = get_parameter('id_recon_server', ''); + $network = get_parameter('name', ''); + $id_group = get_parameter('id_group', ''); + + if ($taskname == '') { + $this->msg = __('You must provide a task name.'); + return false; + } + + if ($server_id == '') { + $this->msg = __('You must select a Discovery Server.'); + return false; + } + + if ($network == '') { + // XXX: Could be improved validating provided network. + $this->msg = __('You must provide a valid network.'); + return false; + } + + if ($id_group == '') { + $this->msg = __('You must select a valid group.'); + return false; + } + + // Assign fields. + $this->task['name'] = $taskname; + $this->task['description'] = $comment; + $this->task['subnet'] = $network; + $this->task['id_recon_server'] = $server_id; + // Disabled 2 Implies wizard non finished. + $this->task['disabled'] = 2; + + $this->task['id_rt'] = 5; + + if (!isset($this->task['id_rt'])) { + // Create. + $this->task['id_rt'] = db_process_sql_insert( + 'trecon_task', + $this->task + ); + } else { + // Update. + db_process_sql_update( + 'trecon_task', + $this->task, + ['id_rt' => $this->task['id_rt']] + ); + } + + return true; + } + + // Validate response from page 1. + if ($this->page == 2) { + $id_rt = get_parameter('task', -1); + + $this->task = db_get_row( + 'trecon_task', + 'id_rt', + $id_rt + ); + + hd($this->task); + + return false; + } + + if ($this->page == 3) { + // Interval and schedules. + // By default manual if not defined. + $interval = get_parameter('interval', 0); + + $this->task['interval_sweep'] = $interval; + return false; + } + return false; } @@ -355,18 +442,83 @@ class HostDevices extends Wizard $user_groups = users_get_groups(false, 'AW', true, false, null, 'id_grupo'); $user_groups = array_keys($user_groups); - if (isset($this->page) && $this->page == 1) { - // Parse page 0 responses. - $this->parseNetScan(); + if ($this->parseNetScan() === false) { + // Error. + ui_print_error_message( + $this->msg + ); + + $form = [ + 'form' => [ + 'method' => 'POST', + 'action' => '#', + ], + 'inputs' => [ + [ + 'arguments' => [ + 'type' => 'hidden', + 'name' => 'page', + 'value' => ($this->page - 1), + ], + ], + [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Go back'), + 'type' => 'submit', + 'attributes' => 'class="sub cancel"', + 'return' => true, + ], + ], + ], + ]; + + $this->printForm($form); + return null; } - if (!isset($this->page) || $this->page == 0) { - // Interval. - $interv_manual = 0; - if ((int) $interval == 0) { - $interv_manual = 1; - } + if (isset($this->page) + && $this->page != 0 + && isset($this->task['id_rt']) === false + ) { + // Error. + ui_print_error_message( + __('Internal error, please re-run this wizard.') + ); + $form = [ + 'form' => [ + 'method' => 'POST', + 'action' => '#', + ], + 'inputs' => [ + [ + 'arguments' => [ + 'type' => 'hidden', + 'name' => 'page', + 'value' => 0, + ], + ], + [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Go back'), + 'type' => 'submit', + 'attributes' => 'class="sub cancel"', + 'return' => true, + ], + ], + ], + ]; + + $this->printForm($form); + return null; + } + + // -------------------------------. + // Page 0. wizard starts HERE. + // -------------------------------. + if (!isset($this->page) || $this->page == 0) { if (isset($this->page) === false || $this->page == 0 ) { @@ -383,6 +535,17 @@ class HostDevices extends Wizard ], ]; + // Input task name. + $form['inputs'][] = [ + 'label' => ''.__('Comment').'', + 'arguments' => [ + 'name' => 'comment', + 'value' => '', + 'type' => 'text', + 'size' => 25, + ], + ]; + // Input Discovery Server. $form['inputs'][] = [ 'label' => ''.__('Discovery server').''.ui_print_help_tip( @@ -419,38 +582,6 @@ class HostDevices extends Wizard ], ]; - // Input interval. - $form['inputs'][] = [ - 'label' => ''.__('Interval').''.ui_print_help_tip( - __('Manual interval means that it will be executed only On-demand'), - true - ), - 'arguments' => [ - 'type' => 'select', - 'selected' => $interv_manual, - 'fields' => [ - 0 => __('Defined'), - 1 => __('Manual'), - ], - 'name' => 'interval_manual_defined', - 'return' => true, - ], - 'extra' => ''.html_print_extended_select_for_time( - 'interval', - $interval, - '', - '', - '0', - false, - true, - false, - false - ).ui_print_help_tip( - __('The minimum recomended interval for Recon Task is 5 minutes'), - true - ).'', - ]; - // Input Group. $form['inputs'][] = [ 'label' => ''.__('Group').'', @@ -553,17 +684,19 @@ class HostDevices extends Wizard 'hidden' => 1, 'block_id' => 'snmp_extra', 'block_content' => [ - 'label' => __('SNMP version'), - 'arguments' => [ - 'name' => 'auth_strings', - 'fields' => [ - '1' => 'v. 1', - '2c' => 'v. 2c', - '3' => 'v. 3', + [ + 'label' => __('SNMP version'), + 'arguments' => [ + 'name' => 'auth_strings', + 'fields' => [ + '1' => 'v. 1', + '2c' => 'v. 2c', + '3' => 'v. 3', + ], + 'type' => 'select', + 'script' => "\$('#snmp_options_v'+this.value).toggle()", + 'return' => true, ], - 'type' => 'select', - 'script' => "\$('#snmp_options_v'+this.value).toggle()", - 'return' => true, ], ], ]; @@ -572,13 +705,15 @@ class HostDevices extends Wizard 'hidden' => 1, 'block_id' => 'snmp_options_v1', 'block_content' => [ - 'label' => __('Community'), - 'arguments' => [ - 'name' => 'community', - 'type' => 'text', - 'size' => 25, - 'return' => true, + [ + 'label' => __('Community'), + 'arguments' => [ + 'name' => 'community', + 'type' => 'text', + 'size' => 25, + 'return' => true, + ], ], ], ]; diff --git a/pandora_console/install.php b/pandora_console/install.php deleted file mode 100644 index 69e11b10bd..0000000000 --- a/pandora_console/install.php +++ /dev/null @@ -1,1090 +0,0 @@ - - - - - Pandora FMS - Installation Wizard - - - - - - - - - - - - - - - -
      - -
      - - - -'; - echo " $label "; - echo ''; - if (!extension_loaded($ext)) { - echo ""; - return 1; - } else { - echo ""; - return 0; - } - - echo ''; -} - -function check_include($ext, $label) -{ - echo ''; - echo " $label "; - echo ''; - if (!include $ext) { - echo ""; - return 1; - } else { - echo ""; - return 0; - } - - echo ''; -} - - -function check_exists($file, $label) -{ - echo ''; - echo " $label "; - echo ''; - if (!file_exists($file)) { - echo " "; - return 1; - } else { - echo " "; - return 0; - } - - echo ''; -} - - -function check_generic($ok, $label) -{ - echo ""; - if ($ok == 0) { - echo " "; - echo ''; - echo " $label "; - echo ''; - echo ''; - return 1; - } else { - echo " "; - echo ''; - echo " $label "; - echo ''; - echo ''; - return 0; - } -} - - -function check_writable($fullpath, $label) -{ - echo ""; - if (file_exists($fullpath)) { - if (is_writable($fullpath)) { - echo " "; - echo ''; - echo " $label "; - echo ''; - echo ''; - return 0; - } else { - echo " "; - echo ''; - echo " $label "; - echo ''; - echo ''; - return 1; - } - } else { - echo " "; - echo ''; - echo " $label "; - echo ''; - echo ''; - return 1; - } -} - - -function check_variable($var, $value, $label, $mode) -{ - echo ''; - echo " $label "; - echo ''; - if ($mode == 1) { - if ($var >= $value) { - echo " "; - return 0; - } else { - echo " "; - return 1; - } - } else if ($var == $value) { - echo " "; - return 0; - } else { - echo " "; - return 1; - } - - echo ''; -} - - -function parse_mysql_dump($url) -{ - if (file_exists($url)) { - $file_content = file($url); - $query = ''; - foreach ($file_content as $sql_line) { - if (trim($sql_line) != '' && strpos($sql_line, '-- ') === false) { - $query .= $sql_line; - if (preg_match("/;[\040]*\$/", $sql_line)) { - if (!$result = mysql_query($query)) { - echo mysql_error(); - // Uncomment for debug - echo "
      $query
      "; - return 0; - } - - $query = ''; - } - } - } - - return 1; - } else { - return 0; - } -} - - -function parse_mysqli_dump($connection, $url) -{ - if (file_exists($url)) { - $file_content = file($url); - $query = ''; - foreach ($file_content as $sql_line) { - if (trim($sql_line) != '' && strpos($sql_line, '-- ') === false) { - $query .= $sql_line; - if (preg_match("/;[\040]*\$/", $sql_line)) { - if (!$result = mysqli_query($connection, $query)) { - echo mysqli_error(); - // Uncomment for debug - echo "
      $query
      "; - return 0; - } - - $query = ''; - } - } - } - - return 1; - } else { - return 0; - } -} - - -function random_name($size) -{ - $temp = ''; - for ($a = 0; $a < $size; $a++) { - $temp = $temp.chr(rand(122, 97)); - } - - return $temp; -} - - -function print_logo_status($step, $step_total) -{ - global $banner; - - $header = " -
      -
      -
      - $banner -
      -
      "; - $header .= " -
      - Install step $step of $step_total -
      "; - - return $header; -} - - -// -// This function adjusts path settings in pandora db for FreeBSD. -// -// All packages and configuration files except operating system's base files -// are installed under /usr/local in FreeBSD. So, path settings in pandora db -// for some programs should be changed from the Linux default. -// -function adjust_paths_for_freebsd($engine, $connection=false) -{ - $adjust_sql = [ - "update trecon_script set script = REPLACE(script,'/usr/share','/usr/local/share');", - "update tconfig set value = REPLACE(value,'/usr/bin','/usr/local/bin') where token='netflow_daemon' OR token='netflow_nfdump' OR token='netflow_nfexpire';", - "update talert_commands set command = REPLACE(command,'/usr/bin','/usr/local/bin');", - "update talert_commands set command = REPLACE(command,'/usr/share', '/usr/local/share');", - "update tplugin set execute = REPLACE(execute,'/usr/share','/usr/local/share');", - "update tevent_response set target = REPLACE(target,'/usr/share','/usr/local/share');", - "insert into tconfig (token, value) VALUES ('graphviz_bin_dir', '/usr/local/bin');", - ]; - - for ($i = 0; $i < count($adjust_sql); $i++) { - switch ($engine) { - case 'mysql': - $result = mysql_query($adjust_sql[$i]); - break; - - case 'mysqli': - $result = mysqli_query($connection, $adjust_sql[$i]); - break; - - case 'oracle': - // Delete the last semicolon from current query - $query = substr($adjust_sql[$i], 0, (strlen($adjust_sql[$i]) - 1)); - $sql = oci_parse($connection, $query); - $result = oci_execute($sql); - break; - - case 'pgsql': - pg_send_query($connection, $adjust_sql[$i]); - $result = pg_get_result($connection); - break; - } - - if (!$result) { - return 0; - } - } - - return 1; -} - - -function install_step1() -{ - global $banner; - - echo " -
      -
      - ".print_logo_status(1, 6)." -
      -

      Welcome to Pandora FMS installation Wizard

      -

      This wizard helps you to quick install Pandora FMS console and main database in your system.

      -

      In four steps, this installer will check all dependencies and will create your configuration, ready to use.

      -

      For more information, please refer to documentation.
      - Pandora FMS Development Team

      - "; - if (file_exists('include/config.php')) { - echo "
      Warning: You already have a config.php file. - Configuration and database would be overwritten if you continued.
      "; - } - - echo '
      '; - echo ''; - $writable = check_writable('include', 'Checking if ./include is writable'); - if (file_exists('include/config.php')) { - $writable += check_writable('include/config.php', 'Checking if include/config.php is writable'); - } - - echo '
      '; - - echo "
      Warning: This installer will overwrite and destroy - your existing Pandora FMS configuration and Database. Before continue, - please be sure that you have no valuable Pandora FMS data in your Database.
      -
      "; - - echo "
      Upgrade: - If you want to upgrade from Pandora FMS 4.x to 5.0 version, please use the migration tool inside /extras directory in this setup. -
      "; - - echo '
      '; - - if ($writable == 0) { - echo "
      "; - echo ""; - echo '
      '; - } else { - echo "
      ERROR:You need to setup permissions to be able to write in ./include directory
      "; - } - - echo '
      '; - - echo "
      "; - echo " -
      -
      - Pandora FMS is an OpenSource Software project registered at - SourceForge -
      -
      "; -} - - -function install_step1_licence() -{ - echo " -
      -
      - ".print_logo_status(2, 6)." -
      -

      GPL2 Licence terms agreement

      -

      Pandora FMS is an OpenSource software project licensed under the GPL2 licence. Pandora FMS includes, as well, another software also licensed under LGPL and BSD licenses. Before continue, you must accept the licence terms.. -

      For more information, please refer to our website at http://pandorafms.org and contact us if you have any kind of question about the usage of Pandora FMS

      -

      If you dont accept the licence terms, please, close your browser and delete Pandora FMS files.

      - "; - - if (!file_exists('COPYING')) { - echo "
      Licence file 'COPYING' is not present in your distribution. This means you have some 'partial' Pandora FMS distribution. We cannot continue without accepting the licence file."; - echo '
      '; - } else { - echo ""; - echo "'; - echo '

      '; - echo "

      "; - } - - echo '
      '; - - echo "
      -
      -
      - Pandora FMS is an OpenSource Software project registered at - SourceForge -
      -
      "; -} - - -function install_step2() -{ - echo " -
      -
      - ".print_logo_status(3, 6)." -
      "; - echo '

      Checking software dependencies

      '; - echo ''; - $res = 0; - $res += check_variable(phpversion(), '5.2', 'PHP version >= 5.2', 1); - $res += check_extension('gd', 'PHP GD extension'); - $res += check_extension('ldap', 'PHP LDAP extension'); - $res += check_extension('snmp', 'PHP SNMP extension'); - $res += check_extension('session', 'PHP session extension'); - $res += check_extension('gettext', 'PHP gettext extension'); - $res += check_extension('mbstring', 'PHP Multibyte String'); - $res += check_extension('zip', 'PHP Zip'); - $res += check_extension('zlib', 'PHP Zlib extension'); - $res += check_extension('json', 'PHP json extension'); - $res += check_extension('curl', 'CURL (Client URL Library)'); - $res += check_extension('filter', 'PHP filter extension'); - $res += check_extension('calendar', 'PHP calendar extension'); - if (PHP_OS == 'FreeBSD') { - $res += check_exists('/usr/local/bin/twopi', 'Graphviz Binary'); - } else if (PHP_OS == 'NetBSD') { - $res += check_exists('/usr/pkg/bin/twopi', 'Graphviz Binary'); - } else if (substr(PHP_OS, 0, 3) == 'WIN') { - $res += check_exists("..\\..\\..\\Graphviz\\bin\\twopi.exe", 'Graphviz Binary'); - } else { - $res += check_exists('/usr/bin/twopi', 'Graphviz Binary'); - } - - echo ''; - check_extension('mysql', 'PHP MySQL extension'); - check_extension('mysqli', 'PHP MySQL(mysqli) extension'); - echo '
      '; - echo "DB Engines"; - echo ''; - echo '
      '; - - if ($res > 0) { - echo " -
      You have some incomplete - dependencies. Please correct them or this installer - will not be able to finish your installation. -
      -
      - Remember, if you install any PHP module to comply - with these dependences, you need to restart - your HTTP/Apache server after it to use the new - modules. -
      -
      - Ignore it. -
      "; - } else { - echo "
      "; - echo " - "; - echo '
      '; - } - - echo '
      '; - echo "
      "; - echo " -
      -
      -
      -
      - Pandora FMS is an OpenSource Software project registered at - SourceForge -
      -
"; -} - - -function install_step3() -{ - $options = ''; - if (extension_loaded('mysql')) { - $options .= ""; - } - - if (extension_loaded('mysqli')) { - $options .= ""; - } - - $error = false; - if (empty($options)) { - $error = true; - } - - echo " -
-
- ".print_logo_status(4, 6)." -
-

Environment and database setup

-

- This wizard will create your Pandora FMS database, - and populate it with all the data needed to run for the first time. -

-

- You need a privileged user to create database schema, this is usually root user. - Information about root user will not be used or stored anymore. -

-

- You can also deploy the scheme into an existing Database. - In this case you need a privileged Database user and password of that instance. -

-

- Now, please, complete all details to configure your database and environment setup. -

-
- Warning: This installer will overwrite and destroy your existing - Pandora FMS configuration and Database. Before continue, - please be sure that you have no valuable Pandora FMS data in your Database. -

-
"; - - if (extension_loaded('oci8')) { - echo "
For Oracle installation an existing Database with a privileged user is needed.
"; - } - - if (!$error) { - echo ""; - } - - echo ""; - echo '"; - - // the field dbgrant is only shown when the DB host is different from 127.0.0.1 or localhost - echo " - - "; - - echo " "; - - echo ""; - echo '
'; - echo 'DB Engine
'; - - if ($error) { - echo " -
- Warning: You haven't a any DB engine with PHP. Please check the previous step to DB engine dependencies. -
"; - } else { - echo "'; - - echo '
'; - echo ' Installation in
'; - echo "'; - } - - echo "
DB User with privileges
- - -
DB Password for this user
- - -
DB Hostname
- - -
DB Name (pandora by default)
- - -
Drop Database if exists
- -
Full path to HTTP publication directory
- For example /var/www/pandora_console/ -
- - -
'; - echo "URL path to Pandora FMS Console
- For example '/pandora_console' -
- -
- "; - - if (!$error) { - echo "
"; - echo " - "; - echo '
'; - ?> - - '; - - echo ''; - - echo "
"; - echo "
-
- Pandora FMS is an OpenSource Software project registered at - SourceForge -
-
"; -} - - -function install_step4() -{ - $pandora_config = 'include/config.php'; - - if ((! isset($_POST['user'])) || (! isset($_POST['dbname'])) || (! isset($_POST['host'])) - || (! isset($_POST['pass'])) || (!isset($_POST['engine'])) || (! isset($_POST['db_action'])) - ) { - $dbpassword = ''; - $dbuser = ''; - $dbhost = ''; - $dbname = ''; - $engine = ''; - $dbaction = ''; - $dbgrant = ''; - } else { - $engine = $_POST['engine']; - $dbpassword = $_POST['pass']; - $dbuser = $_POST['user']; - $dbhost = $_POST['host']; - $dbaction = $_POST['db_action']; - if (isset($_POST['dbgrant']) && $_POST['dbgrant'] != '') { - $dbgrant = $_POST['dbgrant']; - } else { - $dbgrant = $_SERVER['SERVER_ADDR']; - } - - if (isset($_POST['drop'])) { - $dbdrop = $_POST['drop']; - } else { - $dbdrop = 0; - } - - $dbname = $_POST['dbname']; - if (isset($_POST['url'])) { - $url = $_POST['url']; - } else { - $url = 'http://localhost'; - } - - if (isset($_POST['path'])) { - $path = $_POST['path']; - $path = str_replace('\\', '/', $path); - // Windows compatibility - } else { - $path = '/var/www'; - } - } - - $everything_ok = 0; - $step1 = 0; - $step2 = 0; - $step3 = 0; - $step4 = 0; - $step5 = 0; - $step6 = 0; - $step7 = 0; - - echo " -
-
- ".print_logo_status(5, 6)." -
-

Creating database and default configuration file

- "; - switch ($engine) { - case 'mysql': - if (! mysql_connect($dbhost, $dbuser, $dbpassword)) { - check_generic(0, 'Connection with Database'); - } else { - check_generic(1, 'Connection with Database'); - - // Drop database if needed and don't want to install over an existing DB - if ($dbdrop == 1) { - mysql_query("DROP DATABASE IF EXISTS `$dbname`"); - } - - // Create schema - if ($dbaction == 'db_new' || $dbdrop == 1) { - $step1 = mysql_query("CREATE DATABASE `$dbname`"); - check_generic($step1, "Creating database '$dbname'"); - } else { - $step1 = 1; - } - - if ($step1 == 1) { - $step2 = mysql_select_db($dbname); - check_generic($step2, "Opening database '$dbname'"); - - $step3 = parse_mysql_dump('pandoradb.sql'); - check_generic($step3, 'Creating schema'); - - $step4 = parse_mysql_dump('pandoradb_data.sql'); - check_generic($step4, 'Populating database'); - if (PHP_OS == 'FreeBSD') { - $step_freebsd = adjust_paths_for_freebsd($engine); - check_generic($step_freebsd, 'Adjusting paths in database for FreeBSD'); - } - - $random_password = random_name(8); - $host = $dbhost; - // set default granted origin to the origin of the queries - if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) { - $host = $dbgrant; - // if the granted origin is different from local machine, set the valid origin - } - - $step5 = mysql_query( - "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host - IDENTIFIED BY '".$random_password."'" - ); - mysql_query('FLUSH PRIVILEGES'); - check_generic($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
"); - - $step6 = is_writable('include'); - check_generic($step6, "Write permissions to save config file in './include'"); - - $cfgin = fopen('include/config.inc.php', 'r'); - $cfgout = fopen($pandora_config, 'w'); - $config_contents = fread($cfgin, filesize('include/config.inc.php')); - $dbtype = 'mysql'; - $config_new = ''; - $step7 = fputs($cfgout, $config_new); - $step7 = ($step7 + fputs($cfgout, $config_contents)); - if ($step7 > 0) { - $step7 = 1; - } - - fclose($cfgin); - fclose($cfgout); - chmod($pandora_config, 0600); - check_generic($step7, "Created new config file at '".$pandora_config."'"); - } - } - - if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { - $everything_ok = 1; - } - break; - - case 'mysqli': - $connection = mysqli_connect($dbhost, $dbuser, $dbpassword); - if (mysqli_connect_error() > 0) { - check_generic(0, 'Connection with Database'); - } else { - check_generic(1, 'Connection with Database'); - - // Drop database if needed and don't want to install over an existing DB - if ($dbdrop == 1) { - mysqli_query($connection, "DROP DATABASE IF EXISTS `$dbname`"); - } - - // Create schema - if ($dbaction == 'db_new' || $dbdrop == 1) { - $step1 = mysqli_query($connection, "CREATE DATABASE `$dbname`"); - check_generic($step1, "Creating database '$dbname'"); - } else { - $step1 = 1; - } - - if ($step1 == 1) { - $step2 = mysqli_select_db($connection, $dbname); - check_generic($step2, "Opening database '$dbname'"); - - $step3 = parse_mysqli_dump($connection, 'pandoradb.sql'); - check_generic($step3, 'Creating schema'); - - $step4 = parse_mysqli_dump($connection, 'pandoradb_data.sql'); - check_generic($step4, 'Populating database'); - if (PHP_OS == 'FreeBSD') { - $step_freebsd = adjust_paths_for_freebsd($engine, $connection); - check_generic($step_freebsd, 'Adjusting paths in database for FreeBSD'); - } - - $random_password = random_name(8); - $host = $dbhost; - // set default granted origin to the origin of the queries - if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) { - $host = $dbgrant; - // if the granted origin is different from local machine, set the valid origin - } - - $step5 = mysqli_query( - $connection, - "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host - IDENTIFIED BY '".$random_password."'" - ); - mysqli_query($connection, 'FLUSH PRIVILEGES'); - check_generic($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
"); - - $step6 = is_writable('include'); - check_generic($step6, "Write permissions to save config file in './include'"); - - $cfgin = fopen('include/config.inc.php', 'r'); - $cfgout = fopen($pandora_config, 'w'); - $config_contents = fread($cfgin, filesize('include/config.inc.php')); - $dbtype = 'mysql'; - $config_new = ''; - $step7 = fputs($cfgout, $config_new); - $step7 = ($step7 + fputs($cfgout, $config_contents)); - if ($step7 > 0) { - $step7 = 1; - } - - fclose($cfgin); - fclose($cfgout); - chmod($pandora_config, 0600); - check_generic($step7, "Created new config file at '".$pandora_config."'"); - } - } - - if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { - $everything_ok = 1; - } - break; - } - - echo '
'; - - if ($everything_ok == 1) { - echo "
"; - echo " - "; - echo '
'; - } else { - $info = "
There were some problems. - Installation was not completed. -

Please correct failures before trying again. - All database "; - if ($engine == 'oracle') { - $info .= 'objects '; - } else { - $info .= 'schemes '; - } - - $info .= 'created in this step have been dropped.

-
'; - echo $info; - - switch ($engine) { - case 'mysql': - if (mysql_error() != '') { - echo "
ERROR: ".mysql_error().'.
'; - } - - if ($step1 == 1) { - mysql_query("DROP DATABASE $dbname"); - } - break; - - case 'mysqli': - if (mysqli_error($connection) != '') { - echo "
ERROR: ".mysqli_error($connection).'.
'; - } - - if ($step1 == 1) { - mysqli_query($connection, "DROP DATABASE $dbname"); - } - break; - } - - echo '
'; - } - - echo '
'; - echo "
"; - echo " -
-
- Pandora FMS is an Open Source Software project registered at - SourceForge -
-
"; -} - - -function install_step5() -{ - echo " -
-
- ".print_logo_status(6, 6)." -
-

Installation complete

-

For security, you now must manually delete this installer - ('install.php') file before trying to access to your Pandora FMS console. -

You should also install Pandora FMS Servers before trying to monitor anything; - please read documentation on how to install it.

-

Default user is 'admin' with password 'pandora', - please change it both as soon as possible.

-

Don't forget to check http://pandorafms.com - for updates. -

Select if you want to rename 'install.php'.

-
- - -
-


. -

-
"; - - echo "
-
- Pandora FMS is an OpenSource Software project registered at - SourceForge -
-
"; -} From 2059614ba231115ffa46e388301b28f68b90253f Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 14 Feb 2019 17:20:00 +0100 Subject: [PATCH 124/249] missed install... Former-commit-id: a2e1bc42354612afde7e1a28845348f41eab7509 --- pandora_console/install.php | 1106 +++++++++++++++++++++++++++++++++++ 1 file changed, 1106 insertions(+) create mode 100644 pandora_console/install.php diff --git a/pandora_console/install.php b/pandora_console/install.php new file mode 100644 index 0000000000..2a190ff74e --- /dev/null +++ b/pandora_console/install.php @@ -0,0 +1,1106 @@ + + + + + Pandora FMS - Installation Wizard + + + + + + + + + + + + + + + +
+ +
+ + + +'; + echo " $label "; + echo ''; + if (!extension_loaded($ext)) { + echo ""; + return 1; + } else { + echo ""; + return 0; + } + + echo ''; +} + +function check_include($ext, $label) +{ + echo ''; + echo " $label "; + echo ''; + if (!include $ext) { + echo ""; + return 1; + } else { + echo ""; + return 0; + } + + echo ''; +} + + +function check_exists($file, $label) +{ + echo ''; + echo " $label "; + echo ''; + if (!file_exists($file)) { + echo " "; + return 1; + } else { + echo " "; + return 0; + } + + echo ''; +} + + +function check_generic($ok, $label) +{ + echo ""; + if ($ok == 0) { + echo " "; + echo ''; + echo " $label "; + echo ''; + echo ''; + return 1; + } else { + echo " "; + echo ''; + echo " $label "; + echo ''; + echo ''; + return 0; + } +} + + +function check_writable($fullpath, $label) +{ + echo ""; + if (file_exists($fullpath)) { + if (is_writable($fullpath)) { + echo " "; + echo ''; + echo " $label "; + echo ''; + echo ''; + return 0; + } else { + echo " "; + echo ''; + echo " $label "; + echo ''; + echo ''; + return 1; + } + } else { + echo " "; + echo ''; + echo " $label "; + echo ''; + echo ''; + return 1; + } +} + + +function check_variable($var, $value, $label, $mode) +{ + echo ''; + echo " $label "; + echo ''; + if ($mode == 1) { + if ($var >= $value) { + echo " "; + return 0; + } else { + echo " "; + return 1; + } + } else if ($var == $value) { + echo " "; + return 0; + } else { + echo " "; + return 1; + } + + echo ''; +} + + +function parse_mysql_dump($url) +{ + if (file_exists($url)) { + $file_content = file($url); + $query = ''; + foreach ($file_content as $sql_line) { + if (trim($sql_line) != '' && strpos($sql_line, '-- ') === false) { + $query .= $sql_line; + if (preg_match("/;[\040]*\$/", $sql_line)) { + if (!$result = mysql_query($query)) { + echo mysql_error(); + // Uncomment for debug + echo "
$query
"; + return 0; + } + + $query = ''; + } + } + } + + return 1; + } else { + return 0; + } +} + + +function parse_mysqli_dump($connection, $url) +{ + if (file_exists($url)) { + $file_content = file($url); + $query = ''; + foreach ($file_content as $sql_line) { + if (trim($sql_line) != '' && strpos($sql_line, '-- ') === false) { + $query .= $sql_line; + if (preg_match("/;[\040]*\$/", $sql_line)) { + if (!$result = mysqli_query($connection, $query)) { + echo mysqli_error(); + // Uncomment for debug + echo "
$query
"; + return 0; + } + + $query = ''; + } + } + } + + return 1; + } else { + return 0; + } +} + + +function random_name($size) +{ + $temp = ''; + for ($a = 0; $a < $size; $a++) { + $temp = $temp.chr(rand(122, 97)); + } + + return $temp; +} + + +function print_logo_status($step, $step_total) +{ + global $banner; + + $header = " +
+
+
+ $banner +
+
"; + $header .= " +
+ Install step $step of $step_total +
"; + + return $header; +} + + +// +// This function adjusts path settings in pandora db for FreeBSD. +// +// All packages and configuration files except operating system's base files +// are installed under /usr/local in FreeBSD. So, path settings in pandora db +// for some programs should be changed from the Linux default. +// +function adjust_paths_for_freebsd($engine, $connection=false) +{ + $adjust_sql = [ + "update trecon_script set script = REPLACE(script,'/usr/share','/usr/local/share');", + "update tconfig set value = REPLACE(value,'/usr/bin','/usr/local/bin') where token='netflow_daemon' OR token='netflow_nfdump' OR token='netflow_nfexpire';", + "update talert_commands set command = REPLACE(command,'/usr/bin','/usr/local/bin');", + "update talert_commands set command = REPLACE(command,'/usr/share', '/usr/local/share');", + "update tplugin set execute = REPLACE(execute,'/usr/share','/usr/local/share');", + "update tevent_response set target = REPLACE(target,'/usr/share','/usr/local/share');", + "insert into tconfig (token, value) VALUES ('graphviz_bin_dir', '/usr/local/bin');", + ]; + + for ($i = 0; $i < count($adjust_sql); $i++) { + switch ($engine) { + case 'mysql': + $result = mysql_query($adjust_sql[$i]); + break; + + case 'mysqli': + $result = mysqli_query($connection, $adjust_sql[$i]); + break; + + case 'oracle': + // Delete the last semicolon from current query + $query = substr($adjust_sql[$i], 0, (strlen($adjust_sql[$i]) - 1)); + $sql = oci_parse($connection, $query); + $result = oci_execute($sql); + break; + + case 'pgsql': + pg_send_query($connection, $adjust_sql[$i]); + $result = pg_get_result($connection); + break; + } + + if (!$result) { + return 0; + } + } + + return 1; +} + + +function install_step1() +{ + global $banner; + + echo " +
+
+ ".print_logo_status(1, 6)." +
+

Welcome to Pandora FMS installation Wizard

+

This wizard helps you to quick install Pandora FMS console and main database in your system.

+

In four steps, this installer will check all dependencies and will create your configuration, ready to use.

+

For more information, please refer to documentation.
+ Pandora FMS Development Team

+ "; + if (file_exists('include/config.php')) { + echo "
Warning: You already have a config.php file. + Configuration and database would be overwritten if you continued.
"; + } + + echo '
'; + echo ''; + $writable = check_writable('include', 'Checking if ./include is writable'); + if (file_exists('include/config.php')) { + $writable += check_writable('include/config.php', 'Checking if include/config.php is writable'); + } + + echo '
'; + + echo "
Warning: This installer will overwrite and destroy + your existing Pandora FMS configuration and Database. Before continue, + please be sure that you have no valuable Pandora FMS data in your Database.
+
"; + + echo "
Upgrade: + If you want to upgrade from Pandora FMS 4.x to 5.0 version, please use the migration tool inside /extras directory in this setup. +
"; + + echo '
'; + + if ($writable == 0) { + echo "
"; + echo ""; + echo '
'; + } else { + echo "
ERROR:You need to setup permissions to be able to write in ./include directory
"; + } + + echo '
'; + + echo "
"; + echo " +
+
+ Pandora FMS is an OpenSource Software project registered at + SourceForge +
+
"; +} + + +function install_step1_licence() +{ + echo " +
+
+ ".print_logo_status(2, 6)." +
+

GPL2 Licence terms agreement

+

Pandora FMS is an OpenSource software project licensed under the GPL2 licence. Pandora FMS includes, as well, another software also licensed under LGPL and BSD licenses. Before continue, you must accept the licence terms.. +

For more information, please refer to our website at http://pandorafms.org and contact us if you have any kind of question about the usage of Pandora FMS

+

If you dont accept the licence terms, please, close your browser and delete Pandora FMS files.

+ "; + + if (!file_exists('COPYING')) { + echo "
Licence file 'COPYING' is not present in your distribution. This means you have some 'partial' Pandora FMS distribution. We cannot continue without accepting the licence file."; + echo '
'; + } else { + echo "
"; + echo "'; + echo '

'; + echo "

"; + } + + echo '
'; + + echo "
+
+
+ Pandora FMS is an OpenSource Software project registered at + SourceForge +
+
"; +} + + +function install_step2() +{ + echo " +
+
+ ".print_logo_status(3, 6)." +
"; + echo '

Checking software dependencies

'; + echo ''; + $res = 0; + $res += check_variable(phpversion(), '5.2', 'PHP version >= 5.2', 1); + $res += check_extension('gd', 'PHP GD extension'); + $res += check_extension('ldap', 'PHP LDAP extension'); + $res += check_extension('snmp', 'PHP SNMP extension'); + $res += check_extension('session', 'PHP session extension'); + $res += check_extension('gettext', 'PHP gettext extension'); + $res += check_extension('mbstring', 'PHP Multibyte String'); + $res += check_extension('zip', 'PHP Zip'); + $res += check_extension('zlib', 'PHP Zlib extension'); + $res += check_extension('json', 'PHP json extension'); + $res += check_extension('curl', 'CURL (Client URL Library)'); + $res += check_extension('filter', 'PHP filter extension'); + $res += check_extension('calendar', 'PHP calendar extension'); + if (PHP_OS == 'FreeBSD') { + $res += check_exists('/usr/local/bin/twopi', 'Graphviz Binary'); + } else if (PHP_OS == 'NetBSD') { + $res += check_exists('/usr/pkg/bin/twopi', 'Graphviz Binary'); + } else if (substr(PHP_OS, 0, 3) == 'WIN') { + $res += check_exists("..\\..\\..\\Graphviz\\bin\\twopi.exe", 'Graphviz Binary'); + } else { + $res += check_exists('/usr/bin/twopi', 'Graphviz Binary'); + } + + echo ''; + check_extension('mysql', 'PHP MySQL extension'); + check_extension('mysqli', 'PHP MySQL(mysqli) extension'); + echo '
'; + echo "DB Engines"; + echo ''; + echo '
'; + + if ($res > 0) { + echo " +
You have some incomplete + dependencies. Please correct them or this installer + will not be able to finish your installation. +
+
+ Remember, if you install any PHP module to comply + with these dependences, you need to restart + your HTTP/Apache server after it to use the new + modules. +
+
+ Ignore it. +
"; + } else { + echo "
"; + echo " + "; + echo '
'; + } + + echo '
'; + echo "
"; + echo " +
+
+
+
+ Pandora FMS is an OpenSource Software project registered at + SourceForge +
+ "; +} + + +function install_step3() +{ + $options = ''; + if (extension_loaded('mysql')) { + $options .= ""; + } + + if (extension_loaded('mysqli')) { + $options .= ""; + } + + $error = false; + if (empty($options)) { + $error = true; + } + + echo " +
+
+ ".print_logo_status(4, 6)." +
+

Environment and database setup

+

+ This wizard will create your Pandora FMS database, + and populate it with all the data needed to run for the first time. +

+

+ You need a privileged user to create database schema, this is usually root user. + Information about root user will not be used or stored anymore. +

+

+ You can also deploy the scheme into an existing Database. + In this case you need a privileged Database user and password of that instance. +

+

+ Now, please, complete all details to configure your database and environment setup. +

+
+ Warning: This installer will overwrite and destroy your existing + Pandora FMS configuration and Database. Before continue, + please be sure that you have no valuable Pandora FMS data in your Database. +

+
"; + + if (extension_loaded('oci8')) { + echo "
For Oracle installation an existing Database with a privileged user is needed.
"; + } + + if (!$error) { + echo ""; + } + + echo ""; + echo '"; + + // the field dbgrant is only shown when the DB host is different from 127.0.0.1 or localhost + echo " + + "; + + echo " "; + + echo ""; + echo '
'; + echo 'DB Engine
'; + + if ($error) { + echo " +
+ Warning: You haven't a any DB engine with PHP. Please check the previous step to DB engine dependencies. +
"; + } else { + echo "'; + + echo '
'; + echo ' Installation in
'; + echo "'; + } + + echo "
DB User with privileges
+ + +
DB Password for this user
+ + +
DB Hostname
+ + +
DB Name (pandora by default)
+ + +
Drop Database if exists
+ +
Full path to HTTP publication directory
+ For example /var/www/pandora_console/ +
+ + +
'; + echo "URL path to Pandora FMS Console
+ For example '/pandora_console' +
+ +
+ "; + + if (!$error) { + echo "
"; + echo " + "; + echo '
'; + ?> + + '; + + echo ''; + + echo "
"; + echo "
+
+ Pandora FMS is an OpenSource Software project registered at + SourceForge +
+
"; +} + + +function install_step4() +{ + $pandora_config = 'include/config.php'; + + if ((! isset($_POST['user'])) || (! isset($_POST['dbname'])) || (! isset($_POST['host'])) + || (! isset($_POST['pass'])) || (!isset($_POST['engine'])) || (! isset($_POST['db_action'])) + ) { + $dbpassword = ''; + $dbuser = ''; + $dbhost = ''; + $dbname = ''; + $engine = ''; + $dbaction = ''; + $dbgrant = ''; + } else { + $engine = $_POST['engine']; + $dbpassword = $_POST['pass']; + $dbuser = $_POST['user']; + $dbhost = $_POST['host']; + $dbaction = $_POST['db_action']; + if (isset($_POST['dbgrant']) && $_POST['dbgrant'] != '') { + $dbgrant = $_POST['dbgrant']; + } else { + $dbgrant = $_SERVER['SERVER_ADDR']; + } + + if (isset($_POST['drop'])) { + $dbdrop = $_POST['drop']; + } else { + $dbdrop = 0; + } + + $dbname = $_POST['dbname']; + if (isset($_POST['url'])) { + $url = $_POST['url']; + } else { + $url = 'http://localhost'; + } + + if (isset($_POST['path'])) { + $path = $_POST['path']; + $path = str_replace('\\', '/', $path); + // Windows compatibility + } else { + $path = '/var/www'; + } + } + + $everything_ok = 0; + $step1 = 0; + $step2 = 0; + $step3 = 0; + $step4 = 0; + $step5 = 0; + $step6 = 0; + $step7 = 0; + + echo " +
+
+ ".print_logo_status(5, 6)." +
+

Creating database and default configuration file

+ "; + switch ($engine) { + case 'mysql': + if (! mysql_connect($dbhost, $dbuser, $dbpassword)) { + check_generic(0, 'Connection with Database'); + } else { + check_generic(1, 'Connection with Database'); + + // Drop database if needed and don't want to install over an existing DB + if ($dbdrop == 1) { + mysql_query("DROP DATABASE IF EXISTS `$dbname`"); + } + + // Create schema + if ($dbaction == 'db_new' || $dbdrop == 1) { + $step1 = mysql_query("CREATE DATABASE `$dbname`"); + check_generic($step1, "Creating database '$dbname'"); + } else { + $step1 = 1; + } + + if ($step1 == 1) { + $step2 = mysql_select_db($dbname); + check_generic($step2, "Opening database '$dbname'"); + + $step3 = parse_mysql_dump('pandoradb.sql'); + check_generic($step3, 'Creating schema'); + + $step4 = parse_mysql_dump('pandoradb_data.sql'); + check_generic($step4, 'Populating database'); + if (PHP_OS == 'FreeBSD') { + $step_freebsd = adjust_paths_for_freebsd($engine); + check_generic($step_freebsd, 'Adjusting paths in database for FreeBSD'); + } + + $random_password = random_name(8); + $host = $dbhost; + // set default granted origin to the origin of the queries + if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) { + $host = $dbgrant; + // if the granted origin is different from local machine, set the valid origin + } + + $step5 = mysql_query( + "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host + IDENTIFIED BY '".$random_password."'" + ); + mysql_query('FLUSH PRIVILEGES'); + check_generic($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
"); + + $step6 = is_writable('include'); + check_generic($step6, "Write permissions to save config file in './include'"); + + $cfgin = fopen('include/config.inc.php', 'r'); + $cfgout = fopen($pandora_config, 'w'); + $config_contents = fread($cfgin, filesize('include/config.inc.php')); + $dbtype = 'mysql'; + $config_new = ''; + $step7 = fputs($cfgout, $config_new); + $step7 = ($step7 + fputs($cfgout, $config_contents)); + if ($step7 > 0) { + $step7 = 1; + } + + fclose($cfgin); + fclose($cfgout); + chmod($pandora_config, 0600); + check_generic($step7, "Created new config file at '".$pandora_config."'"); + } + } + + if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { + $everything_ok = 1; + } + break; + + case 'mysqli': + $connection = mysqli_connect($dbhost, $dbuser, $dbpassword); + if (mysqli_connect_error() > 0) { + check_generic(0, 'Connection with Database'); + } else { + check_generic(1, 'Connection with Database'); + + // Drop database if needed and don't want to install over an existing DB + if ($dbdrop == 1) { + mysqli_query($connection, "DROP DATABASE IF EXISTS `$dbname`"); + } + + // Create schema + if ($dbaction == 'db_new' || $dbdrop == 1) { + $step1 = mysqli_query($connection, "CREATE DATABASE `$dbname`"); + check_generic($step1, "Creating database '$dbname'"); + } else { + $step1 = 1; + } + + if ($step1 == 1) { + $step2 = mysqli_select_db($connection, $dbname); + check_generic($step2, "Opening database '$dbname'"); + + $step3 = parse_mysqli_dump($connection, 'pandoradb.sql'); + check_generic($step3, 'Creating schema'); + + $step4 = parse_mysqli_dump($connection, 'pandoradb_data.sql'); + check_generic($step4, 'Populating database'); + if (PHP_OS == 'FreeBSD') { + $step_freebsd = adjust_paths_for_freebsd($engine, $connection); + check_generic($step_freebsd, 'Adjusting paths in database for FreeBSD'); + } + + $random_password = random_name(8); + $host = $dbhost; + // set default granted origin to the origin of the queries + if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) { + $host = $dbgrant; + // if the granted origin is different from local machine, set the valid origin + } + + $step5 = mysqli_query( + $connection, + "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host + IDENTIFIED BY '".$random_password."'" + ); + mysqli_query($connection, 'FLUSH PRIVILEGES'); + check_generic($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
"); + + $step6 = is_writable('include'); + check_generic($step6, "Write permissions to save config file in './include'"); + + $cfgin = fopen('include/config.inc.php', 'r'); + $cfgout = fopen($pandora_config, 'w'); + $config_contents = fread($cfgin, filesize('include/config.inc.php')); + $dbtype = 'mysql'; + $config_new = ''; + $step7 = fputs($cfgout, $config_new); + $step7 = ($step7 + fputs($cfgout, $config_contents)); + if ($step7 > 0) { + $step7 = 1; + } + + fclose($cfgin); + fclose($cfgout); + chmod($pandora_config, 0600); + check_generic($step7, "Created new config file at '".$pandora_config."'"); + } + } + + if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { + $everything_ok = 1; + } + break; + } + + echo '
'; + + if ($everything_ok == 1) { + echo "
"; + echo " + "; + echo '
'; + } else { + $info = "
There were some problems. + Installation was not completed. +

Please correct failures before trying again. + All database "; + if ($engine == 'oracle') { + $info .= 'objects '; + } else { + $info .= 'schemes '; + } + + $info .= 'created in this step have been dropped.

+
'; + echo $info; + + switch ($engine) { + case 'mysql': + if (mysql_error() != '') { + echo "
ERROR: ".mysql_error().'.
'; + } + + if ($step1 == 1) { + mysql_query("DROP DATABASE $dbname"); + } + break; + + case 'mysqli': + if (mysqli_error($connection) != '') { + echo "
ERROR: ".mysqli_error($connection).'.
'; + } + + if ($step1 == 1) { + mysqli_query($connection, "DROP DATABASE $dbname"); + } + break; + } + + echo '
'; + } + + echo '
'; + echo "
"; + echo " +
+
+ Pandora FMS is an Open Source Software project registered at + SourceForge +
+
"; +} + + +function install_step5() +{ + echo " +
+
+ ".print_logo_status(6, 6)." +
+

Installation complete

+

For security, you now must manually delete this installer + ('install.php') file before trying to access to your Pandora FMS console. +

You should also install Pandora FMS Servers before trying to monitor anything; + please read documentation on how to install it.

+

Default user is 'admin' with password 'pandora', + please change it both as soon as possible.

+

Don't forget to check http://pandorafms.com + for updates. +

Select if you want to rename 'install.php'.

+
+ + +
+


. +

+
"; + + echo "
+
+ Pandora FMS is an OpenSource Software project registered at + SourceForge +
+
"; +} From 96fccc578c2349207482b4daf1a25e411f04c8b7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 14 Feb 2019 17:56:10 +0100 Subject: [PATCH 125/249] WIP: H&D Former-commit-id: 82a6c84a2c896a08f420a89dc3fe6cd79d8ff3bb --- .../godmode/wizards/HostDevices.class.php | 298 +++++------------- .../godmode/wizards/Wizard.main.php | 7 + 2 files changed, 83 insertions(+), 222 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 23250995db..758f8e653b 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -1,7 +1,34 @@ setBreadcrum( - [ - 'Host&devices', - 'Import CSV', - ] - ); - $this->printHeader(); - return $this->runCSV(); + if (enterprise_installed()) { + if ($mode == 'importcsv') { + $this->setBreadcrum( + [ + 'Host&devices', + 'Import CSV', + ] + ); + $this->printHeader(); + $csv_importer = new CSVImportAgents($this->page, $this->breadcrum); + return $csv_importer->runCSV(); + } } if ($mode == 'netscan') { @@ -172,154 +195,6 @@ class HostDevices extends Wizard // Extra methods. - /** - * Undocumented function - * - * @return void - */ - public function runCSV() - { - global $config; - - if (!check_acl($config['id_user'], 0, 'AW')) { - db_pandora_audit( - 'ACL Violation', - 'Trying to access db status' - ); - include 'general/noaccess.php'; - return; - } - - if (!isset($this->page) || $this->page == 0) { - $this->printForm( - [ - 'form' => [ - 'action' => '#', - 'method' => 'POST', - 'enctype' => 'multipart/form-data', - ], - 'inputs' => [ - [ - 'arguments' => [ - 'type' => 'hidden', - 'name' => 'import_file', - 'value' => 1, - 'return' => true, - ], - ], - [ - 'label' => __('Upload file'), - 'arguments' => [ - 'type' => 'file', - 'name' => 'file', - 'return' => true, - ], - ], - [ - 'label' => __('Server'), - 'arguments' => [ - 'type' => 'select', - 'fields' => servers_get_names(), - 'name' => 'server', - 'return' => true, - ], - ], - [ - 'label' => __('Separator'), - 'arguments' => [ - 'type' => 'select', - 'fields' => [ - ',' => ',', - ';' => ';', - ':' => ':', - '.' => '.', - '#' => '#', - ], - 'name' => 'separator', - 'return' => true, - ], - ], - [ - 'arguments' => [ - 'name' => 'page', - 'value' => 1, - 'type' => 'hidden', - 'return' => true, - ], - ], - [ - 'arguments' => [ - 'name' => 'submit', - 'label' => __('Go'), - 'type' => 'submit', - 'attributes' => 'class="sub next"', - 'return' => true, - ], - ], - ], - ] - ); - } - - if (isset($this->page) && $this->page == 1) { - $server = get_parameter('server'); - $separator = get_parameter('separator'); - - if (isset($_FILES['file'])) { - $file_status_code = get_file_upload_status('file'); - $file_status = translate_file_upload_status($file_status_code); - - if ($file_status === true) { - $error_message = []; - $line = -1; - $file = fopen($_FILES['file']['tmp_name'], 'r'); - if (! empty($file)) { - while (($data = fgetcsv($file, 1000, $separator)) !== false) { - $result = $this->processCsvData($data, $server); - $line++; - if ($result === HDW_CSV_NOT_DATA || $result === HDW_CSV_DUPLICATED || $result === HDW_CSV_GROUP_EXISTS) { - if ($result === HDW_CSV_NOT_DATA) { - $error_message[] = __('No data or wrong separator in line ').$line.'
'; - } else if ($result === HDW_CSV_DUPLICATED) { - $error_message[] = __('Agent ').io_safe_input($data[0]).__(' duplicated').'
'; - } else { - $error_message[] = __("Id group %s in line %s doesn't exist in %s", $data[4], $line, get_product_name()).'
'; - } - - continue; - } - - ui_print_result_message( - $result !== false, - __('Created agent %s', $result['agent_name']), - __('Could not create agent %s', $result['agent_name']) - ); - } - } - - fclose($file); - - if (empty($error_message)) { - ui_print_success_message(__('File processed')); - } else { - foreach ($error_message as $msg) { - ui_print_error_message($msg); - } - } - } else { - ui_print_error_message($file_status); - } - - @unlink($_FILES['file']['tmp_name']); - } else { - ui_print_error_message(__('No input file detected')); - } - - echo $this->breadcrum[0]; - } - } - - /** * Retrieves and validates information given by user in NetScan wizard. * @@ -701,6 +576,7 @@ class HostDevices extends Wizard ], ]; + // SNMP Options pack v1. $form['inputs'][] = [ 'hidden' => 1, 'block_id' => 'snmp_options_v1', @@ -718,6 +594,42 @@ class HostDevices extends Wizard ], ]; + // SNMP Options pack v2c. + $form['inputs'][] = [ + 'hidden' => 1, + 'block_id' => 'snmp_options_v2c', + 'block_content' => [ + [ + 'label' => __('Community'), + 'arguments' => [ + 'name' => 'community', + 'type' => 'text', + 'size' => 25, + 'return' => true, + + ], + ], + ], + ]; + + // SNMP Options pack v3. + $form['inputs'][] = [ + 'hidden' => 1, + 'block_id' => 'snmp_options_v3', + 'block_content' => [ + [ + 'label' => __(''), + 'arguments' => [ + 'name' => 'community', + 'type' => 'text', + 'size' => 25, + 'return' => true, + + ], + ], + ], + ]; + // Input: WMI enabled. $form['inputs'][] = [ 'label' => __('WMI enabled'), @@ -905,62 +817,4 @@ $("select#interval_manual_defined").change(function() { } - /** - * Process the csv of agent. - * - * @param array $data Data of agent. - * @param string $server Name of server. - * - * @return array with data porcessed. - */ - private static function processCsvData($data, $server='') - { - if (empty($data) || count($data) < 5) { - return HDW_CSV_NOT_DATA; - } - - $data['network_components'] = array_slice($data, 6); - $data['agent_name'] = io_safe_input($data[0]); - $data['alias'] = io_safe_input($data[0]); - $data['ip_address'] = $data[1]; - $data['id_os'] = $data[2]; - $data['interval'] = $data[3]; - $data['id_group'] = $data[4]; - $data['comentarios'] = io_safe_input($data[5]); - - $exists = (bool) agents_get_agent_id($data['agent_name']); - if ($exists) { - return HDW_CSV_DUPLICATED; - } - - $group_exists_in_pandora = (bool) groups_get_group_by_id($data['id_group']); - if (!$group_exists_in_pandora) { - return HDW_CSV_GROUP_EXISTS; - } - - $data['id_agent'] = agents_create_agent( - $data['agent_name'], - $data['id_group'], - $data['interval'], - $data['ip_address'], - [ - 'id_os' => $data['id_os'], - 'server_name' => $server, - 'modo' => 1, - 'alias' => $data['alias'], - 'comentarios' => $data['comentarios'], - ] - ); - - foreach ($data['network_components'] as $id_network_component) { - network_components_create_module_from_network_component( - (int) $id_network_component, - $data['id_agent'] - ); - } - - return $data; - } - - } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index c164b287b7..1a70bae362 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -13,6 +13,13 @@ class Wizard */ public $breadcrum; + /** + * Undocumented variable + * + * @var [type] + */ + public $page; + /** * Setter for breadcrum From ffe8bba3f784ef392fdb6cd78be685e99e828ab4 Mon Sep 17 00:00:00 2001 From: Daniel Maya Date: Fri, 15 Feb 2019 09:10:21 +0100 Subject: [PATCH 126/249] added exception in ldapsearch Former-commit-id: 4ab1637c30cac2bb4c827b1e08017f6b08fae1b9 --- pandora_console/include/auth/mysql.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/auth/mysql.php b/pandora_console/include/auth/mysql.php index 8003275fbf..aab0b4c9e4 100644 --- a/pandora_console/include/auth/mysql.php +++ b/pandora_console/include/auth/mysql.php @@ -1369,7 +1369,12 @@ function local_ldap_search($ldap_host, $ldap_port=389, $ldap_version=3, $dn, $ac $tls = ' -ZZ '; } - $ldap_host = ' -H '.$ldap_host.':'.$ldap_port; + if (stripos($ldap_host, 'ldap') !== false) { + $ldap_host = ' -H '.$ldap_host.':'.$ldap_port; + } else { + $ldap_host = ' -h '.$ldap_host.' -p '.$ldap_port; + } + $ldap_version = ' -P '.$ldap_version; if (!empty($ldap_admin_user)) { $ldap_admin_user = " -D '".$ldap_admin_user."'"; From f777c59a8374025b1c2d3950c4b0df9ad6500df7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 10:00:23 +0100 Subject: [PATCH 127/249] WIP: H&D skel files css wiz&discov Former-commit-id: e57758a9e77b19868262557d9e11a0ff7b38f02c --- pandora_console/godmode/servers/discovery.php | 2 ++ pandora_console/include/styles/discovery.css | 3 +++ pandora_console/include/styles/wizard.css | 4 ++++ 3 files changed, 9 insertions(+) create mode 100644 pandora_console/include/styles/discovery.css diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 39c31b9465..25619fbc7a 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -13,6 +13,8 @@ if (! check_acl($config['id_user'], 0, 'AW')) { exit; } +ui_require_css_file('discovery'); + ui_print_page_header(__('Discover'), 'wizards/hostDevices.png', false, '', true); diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css new file mode 100644 index 0000000000..62be6c7c98 --- /dev/null +++ b/pandora_console/include/styles/discovery.css @@ -0,0 +1,3 @@ +/* + * Discovery css global + */ diff --git a/pandora_console/include/styles/wizard.css b/pandora_console/include/styles/wizard.css index fdaf5afa4b..912f5d5a4f 100644 --- a/pandora_console/include/styles/wizard.css +++ b/pandora_console/include/styles/wizard.css @@ -1,3 +1,7 @@ +/* + * Discovery > Wizard css global style + */ + ul.wizard { } From efdc17b801579c1f69d095ea8e251f61f5c43522 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 13:08:44 +0100 Subject: [PATCH 128/249] WIP: H&D Former-commit-id: 605aa350c6d8d9bcebadbb941bba2a6fc399cb7c --- pandora_console/godmode/servers/discovery.php | 3 +- .../godmode/wizards/HostDevices.class.php | 417 +++++++++++++++--- pandora_console/include/functions.php | 20 + 3 files changed, 374 insertions(+), 66 deletions(-) diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 25619fbc7a..70da2939e7 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -52,8 +52,9 @@ $classname_selected = get_wiz_class($wiz_in_use); // Else: class not found pseudo exception. if ($classname_selected !== null) { $wiz = new $classname_selected($page); - $wiz->run(); + $result = $wiz->run(); // TODO: Here we'll controlle if return is a valid recon task id. + hd($result); } if ($classname_selected === null) { diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 758f8e653b..7e2772d6e1 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -102,7 +102,7 @@ class HostDevices extends Wizard */ public function __construct( int $page=0, - string $msg='hola', + string $msg='Default message. Not set.', string $icon='hostDevices.png', string $label='Host & Devices' ) { @@ -203,19 +203,68 @@ class HostDevices extends Wizard public function parseNetScan() { if ($this->page == 0) { - // Error. Must not be here. + // Check if we're updating a task. + $task_id = get_parameter('task', null); + + if (isset($task_id) === true) { + // We're updating this task. + $task = db_get_row( + 'trecon_task', + 'id_rt', + $task_id + ); + + if ($task !== false) { + $this->task = $task; + } + } + return true; } // Validate response from page 0. No, not a bug, we're always 1 page // from 'validation' page. if ($this->page == 1) { + $task_id = get_parameter('task', null); $taskname = get_parameter('taskname', ''); $comment = get_parameter('comment', ''); $server_id = get_parameter('id_recon_server', ''); - $network = get_parameter('name', ''); + $network = get_parameter('network', ''); $id_group = get_parameter('id_group', ''); + if (isset($task_id) === true) { + // We're updating this task. + $task = db_get_row( + 'trecon_task', + 'id_rt', + $task_id + ); + + if ($task !== false) { + $this->task = $task; + } + } else if (isset($taskname) === true + && isset($network) === true + ) { + // Avoid double creation. + $task = db_get_row_filter( + 'trecon_task', + [ + 'name' => $taskname, + 'subnet' => $network, + ] + ); + + if ($task !== false) { + $this->task = $task; + } + } + + if (isset($this->task['id_rt']) === false) { + // Disabled 2 Implies wizard non finished. + $this->task['disabled'] = 2; + } + if ($taskname == '') { $this->msg = __('You must provide a task name.'); return false; @@ -242,12 +291,9 @@ class HostDevices extends Wizard $this->task['description'] = $comment; $this->task['subnet'] = $network; $this->task['id_recon_server'] = $server_id; - // Disabled 2 Implies wizard non finished. - $this->task['disabled'] = 2; + $this->task['id_group'] = $id_group; - $this->task['id_rt'] = 5; - - if (!isset($this->task['id_rt'])) { + if (isset($this->task['id_rt']) === false) { // Create. $this->task['id_rt'] = db_process_sql_insert( 'trecon_task', @@ -269,24 +315,121 @@ class HostDevices extends Wizard if ($this->page == 2) { $id_rt = get_parameter('task', -1); - $this->task = db_get_row( + $task = db_get_row( 'trecon_task', 'id_rt', $id_rt ); - hd($this->task); + if ($task !== false) { + $this->task = $task; + } else { + $this->msg = __('Failed to find network scan task.'); + return false; + } - return false; + $id_network_profile = get_parameter('id_network_profile', null); + $snmp_enabled = get_parameter_switch('snmp_enabled'); + $os_detect = get_parameter_switch('os_detect'); + $parent_detection = get_parameter_switch('parent_detection'); + $parent_recursion = get_parameter_switch('parent_recursion'); + $vlan_enabled = get_parameter_switch('vlan_enabled'); + $snmp_version = get_parameter('snmp_version', null); + $community = get_parameter('community', null); + $snmp_context = get_parameter('snmp_context', null); + $snmp_auth_user = get_parameter('snmp_auth_user', null); + $snmp_auth_pass = get_parameter('snmp_auth_pass', null); + $snmp_privacy_method = get_parameter('snmp_privacy_method', null); + $snmp_privacy_pass = get_parameter('snmp_privacy_pass', null); + $snmp_auth_method = get_parameter('snmp_auth_method', null); + $snmp_security_level = get_parameter('snmp_security_level', null); + $auth_strings = get_parameter('auth_strings', null); + + if ($snmp_version == 3) { + $this->task['snmp_community'] = $snmp_context; + } else { + $this->task['snmp_community'] = $community; + } + + $this->task['id_network_profile'] = $id_network_profile; + $this->task['snmp_enabled'] = $snmp_enabled; + $this->task['os_detect'] = $os_detect; + $this->task['parent_detection'] = $parent_detection; + $this->task['parent_recursion'] = $parent_recursion; + $this->task['vlan_enabled'] = $vlan_enabled; + $this->task['snmp_version'] = $snmp_version; + $this->task['snmp_auth_user'] = $snmp_auth_user; + $this->task['snmp_auth_pass'] = $snmp_auth_pass; + $this->task['snmp_privacy_method'] = $snmp_privacy_method; + $this->task['snmp_privacy_pass'] = $snmp_privacy_pass; + $this->task['snmp_auth_method'] = $snmp_auth_method; + $this->task['snmp_security_level'] = $snmp_security_level; + $this->task['auth_strings'] = $auth_strings; + + // Update. + $res = db_process_sql_update( + 'trecon_task', + $this->task, + ['id_rt' => $this->task['id_rt']] + ); + + return true; } if ($this->page == 3) { // Interval and schedules. // By default manual if not defined. - $interval = get_parameter('interval', 0); + $id_rt = get_parameter('task', -1); + $task = db_get_row( + 'trecon_task', + 'id_rt', + $id_rt + ); + + if ($task !== false) { + $this->task = $task; + } else { + $this->msg = __('Failed to find network scan task.'); + return false; + } + + $interval = get_parameter('interval', 0); $this->task['interval_sweep'] = $interval; - return false; + + if ($this->task['disabled'] == 2) { + // Wizard finished. + $this->task['disabled'] = 0; + } + + // Update. + $res = db_process_sql_update( + 'trecon_task', + $this->task, + ['id_rt' => $this->task['id_rt']] + ); + + return true; + } + + if ($this->page == 4) { + // Wizard ended. Load data and return control to Discovery. + $id_rt = get_parameter('task', -1); + + $task = db_get_row( + 'trecon_task', + 'id_rt', + $id_rt + ); + + if ($task !== false) { + $this->task = $task; + } else { + $this->msg = __('Failed to find network scan task.'); + return false; + } + + return true; } return false; @@ -326,14 +469,14 @@ class HostDevices extends Wizard $form = [ 'form' => [ 'method' => 'POST', - 'action' => '#', + 'action' => $this->url.'&mode=netscan&page='.($this->page - 1).'&task='.$this->task['id_rt'], ], 'inputs' => [ [ 'arguments' => [ 'type' => 'hidden', - 'name' => 'page', - 'value' => ($this->page - 1), + 'name' => 'task', + 'value' => $this->task['id_rt'], ], ], [ @@ -364,7 +507,7 @@ class HostDevices extends Wizard $form = [ 'form' => [ 'method' => 'POST', - 'action' => '#', + 'action' => $this->url.'&mode=netscan&page=0', ], 'inputs' => [ [ @@ -404,18 +547,29 @@ class HostDevices extends Wizard 'label' => ''.__('Task name').'', 'arguments' => [ 'name' => 'taskname', - 'value' => '', + 'value' => $this->task['name'], 'type' => 'text', 'size' => 25, ], ]; + if (isset($this->task['id_rt']) === true) { + // Propagate id. + $form['inputs'][] = [ + 'arguments' => [ + 'name' => 'task', + 'value' => $this->task['id_rt'], + 'type' => 'hidden', + ], + ]; + } + // Input task name. $form['inputs'][] = [ 'label' => ''.__('Comment').'', 'arguments' => [ 'name' => 'comment', - 'value' => '', + 'value' => $this->task['description'], 'type' => 'text', 'size' => 25, ], @@ -437,7 +591,7 @@ class HostDevices extends Wizard SERVER_TYPE_DISCOVERY ), 'name' => 'id_recon_server', - 'selected' => 0, + 'selected' => $this->task['id_recon_server'], 'return' => true, ], ]; @@ -450,8 +604,8 @@ class HostDevices extends Wizard true ), 'arguments' => [ - 'name' => 'name', - 'value' => '', + 'name' => 'network', + 'value' => $this->task['subnet'], 'type' => 'text', 'size' => 25, ], @@ -464,25 +618,22 @@ class HostDevices extends Wizard 'name' => 'id_group', 'privilege' => 'PM', 'type' => 'select_groups', + 'selected' => $this->task['id_group'], 'return' => true, ], ]; - // Hidden, page. - $form['inputs'][] = [ - 'arguments' => [ - 'name' => 'page', - 'value' => ($this->page + 1), - 'type' => 'hidden', - 'return' => true, - ], - ]; + $str = __('Next'); + + if (isset($this->task['id_rt']) === true) { + $str = __('Update and continue'); + } // Submit button. $form['inputs'][] = [ 'arguments' => [ 'name' => 'submit', - 'label' => __('Next'), + 'label' => $str, 'type' => 'submit', 'attributes' => 'class="sub next"', 'return' => true, @@ -491,7 +642,7 @@ class HostDevices extends Wizard $form['form'] = [ 'method' => 'POST', - 'action' => '#', + 'action' => $this->url.'&mode=netscan&page='.($this->page + 1), ]; // XXX: Could be improved validating inputs before continue (JS) @@ -549,27 +700,28 @@ class HostDevices extends Wizard 'name' => 'snmp_enabled', 'type' => 'switch', 'return' => true, - 'onclick' => "\$('#snmp_extra').toggle();", + 'value' => 1, + 'onclick' => 'extraSNMP();', ], ]; // SNMP CONFIGURATION. $form['inputs'][] = [ - 'hidden' => 1, + 'hidden' => 0, 'block_id' => 'snmp_extra', 'block_content' => [ [ 'label' => __('SNMP version'), 'arguments' => [ - 'name' => 'auth_strings', + 'name' => 'snmp_version', 'fields' => [ '1' => 'v. 1', '2c' => 'v. 2c', '3' => 'v. 3', ], 'type' => 'select', - 'script' => "\$('#snmp_options_v'+this.value).toggle()", + 'script' => 'SNMPExtraShow(this.value)', 'return' => true, ], ], @@ -579,28 +731,15 @@ class HostDevices extends Wizard // SNMP Options pack v1. $form['inputs'][] = [ 'hidden' => 1, - 'block_id' => 'snmp_options_v1', + 'block_id' => 'snmp_options_basic', 'block_content' => [ [ - 'label' => __('Community'), - 'arguments' => [ - 'name' => 'community', - 'type' => 'text', - 'size' => 25, - 'return' => true, - - ], - ], - ], - ]; - - // SNMP Options pack v2c. - $form['inputs'][] = [ - 'hidden' => 1, - 'block_id' => 'snmp_options_v2c', - 'block_content' => [ - [ - 'label' => __('Community'), + 'label' => ''.__('SNMP Default community').''.ui_print_help_tip( + __( + 'You can specify several values, separated by commas, for example: public,mysecret,1234' + ), + true + ), 'arguments' => [ 'name' => 'community', 'type' => 'text', @@ -618,15 +757,99 @@ class HostDevices extends Wizard 'block_id' => 'snmp_options_v3', 'block_content' => [ [ - 'label' => __(''), + 'label' => ''.__('Context').'', 'arguments' => [ - 'name' => 'community', + 'name' => 'snmp_context', 'type' => 'text', - 'size' => 25, + 'size' => 15, 'return' => true, ], ], + [ + 'label' => ''.__('Auth user').'', + 'arguments' => [ + 'name' => 'snmp_auth_user', + 'type' => 'text', + 'size' => 15, + 'return' => true, + + ], + ], + [ + 'label' => ''.__('Auth password').''.ui_print_help_tip( + __( + 'The pass length must be eight character minimum.' + ), + true + ), + 'arguments' => [ + 'name' => 'snmp_auth_pass', + 'type' => 'password', + 'size' => 15, + 'return' => true, + + ], + ], + [ + 'label' => ''.__('Privacy method').'', + 'arguments' => [ + 'name' => 'snmp_privacy_method', + 'type' => 'select', + 'fields' => [ + 'DES' => __('DES'), + 'AES' => __('AES'), + ], + 'size' => 15, + 'return' => true, + + ], + ], + [ + 'label' => ''.__('Privacy pass').''.ui_print_help_tip( + __( + 'The pass length must be eight character minimum.' + ), + true + ), + 'arguments' => [ + 'name' => 'snmp_privacy_pass', + 'type' => 'password', + 'size' => 15, + 'return' => true, + + ], + ], + [ + 'label' => ''.__('Auth method').'', + 'arguments' => [ + 'name' => 'snmp_auth_method', + 'type' => 'select', + 'fields' => [ + 'MD5' => __('MD5'), + 'SHA' => __('SHA'), + ], + 'size' => 15, + 'return' => true, + + ], + ], + [ + 'label' => ''.__('Security level').'', + 'arguments' => [ + 'name' => 'snmp_security_level', + 'type' => 'select', + 'fields' => [ + 'noAuthNoPriv' => __('Not auth and not privacy method'), + 'authNoPriv' => __('Auth and not privacy method'), + 'authPriv' => __('Auth and privacy method'), + ], + 'size' => 15, + 'return' => true, + + ], + ], + ], ]; @@ -662,6 +885,7 @@ class HostDevices extends Wizard 'name' => 'os_detect', 'type' => 'switch', 'return' => true, + 'value' => 1, ], ]; @@ -683,6 +907,18 @@ class HostDevices extends Wizard 'name' => 'parent_detection', 'type' => 'switch', 'return' => true, + 'value' => 1, + ], + ]; + + // Input: Parent recursion. + $form['inputs'][] = [ + 'label' => __('Parent recursion'), + 'arguments' => [ + 'name' => 'parent_recursion', + 'type' => 'switch', + 'return' => true, + 'value' => 1, ], ]; @@ -690,9 +926,10 @@ class HostDevices extends Wizard $form['inputs'][] = [ 'label' => __('VLAN enabled'), 'arguments' => [ - 'name' => 'os_detect', + 'name' => 'vlan_enabled', 'type' => 'switch', 'return' => true, + 'value' => 1, ], ]; @@ -707,9 +944,49 @@ class HostDevices extends Wizard ], ]; + $form['js'] = ' +function SNMPExtraShow(target) { + $("#snmp_options_basic").hide(); + $("#snmp_options_v3").hide(); + if (target == 3) { + $("#snmp_options_v3").show(); + } else { + $("#snmp_options_basic").show(); + } + +} + +function extraSNMP() { + if (document.getElementsByName("snmp_enabled")[0].checked) { + SNMPExtraShow($("#snmp_version").val()); + $("#snmp_extra").show(); + } else { + // Hide unusable sections + $("#snmp_extra").hide(); + $("#snmp_options_basic").hide(); + $("#snmp_options_v3").hide(); + + // Disable snmp dependant checks + if (document.getElementsByName("parent_recursion")[0].checked) + $("input[name=parent_recursion]").click(); + + if (document.getElementsByName("parent_detection")[0].checked) + $("input[name=parent_detection]").click(); + + if (document.getElementsByName("vlan_enabled")[0].checked) + $("input[name=vlan_enabled]").click(); + + } +} + +$(function() { + SNMPExtraShow($("#snmp_version").val()) +}); + '; + $form['form'] = [ 'method' => 'POST', - 'action' => '#', + 'action' => $this->url.'&mode=netscan&page='.($this->page + 1).'&task='.$this->task['id_rt'], ]; $this->printForm($form); @@ -786,7 +1063,7 @@ class HostDevices extends Wizard $form['form'] = [ 'method' => 'POST', - 'action' => '#', + 'action' => $this->url.'&mode=netscan&page='.($this->page + 1).'&task='.$this->task['id_rt'], ]; $form['js'] = ' @@ -807,10 +1084,20 @@ $("select#interval_manual_defined").change(function() { $this->printForm($form); } - if ($this->page == 100) { + if ($this->page == 3) { + if ($this->task['id_rt']) { + // 0 - Is OK. + $this->result = 0; + $this->msg = __('Task configured.'); + } else { + // 1 - Is NOT OK. + $this->result = 1; + $this->msg = __('Wizard failed. Cannot configure task.'); + } + return [ 'result' => $this->result, - 'id' => $this->id, + 'id' => $this->task['id_rt'], 'msg' => $this->msg, ]; } diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index 6f13388fc0..58120c4616 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -852,6 +852,26 @@ function get_parameter_checkbox($name, $default='') } +/** + * Transforms a swicth data (on - non present) to a int value. + * + * @param string $name Variable, switch name. + * @param string $default Default value. + * + * @return integer Value, 1 on, 0 off. + */ +function get_parameter_switch($name, $default='') +{ + $data = get_parameter($name, 0); + + if ($data == 'on') { + return 1; + } + + return 0; +} + + function get_cookie($name, $default='') { if (isset($_COOKIE[$name])) { From c9c855da9ace314aecfa1abbc79a6613467a6fd2 Mon Sep 17 00:00:00 2001 From: Fermin Date: Fri, 15 Feb 2019 13:47:11 +0100 Subject: [PATCH 129/249] Added new Cloud Wizard class Former-commit-id: 789af2b6cba344bac44b34c4c90228801f2468a0 --- pandora_console/godmode/servers/discovery.php | 3 + .../godmode/wizards/Cloud.class.php | 267 ++++++++++++++++++ 2 files changed, 270 insertions(+) create mode 100755 pandora_console/godmode/wizards/Cloud.class.php diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 25619fbc7a..974dadc82b 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -30,6 +30,9 @@ function get_wiz_class($str) case 'hd': return 'HostDevices'; + case 'cloud': + return 'Cloud'; + default: // Ignore. return null; diff --git a/pandora_console/godmode/wizards/Cloud.class.php b/pandora_console/godmode/wizards/Cloud.class.php new file mode 100755 index 0000000000..1de88c2ca7 --- /dev/null +++ b/pandora_console/godmode/wizards/Cloud.class.php @@ -0,0 +1,267 @@ +setBreadcrum([]); + + $this->task = []; + $this->msg = $msg; + $this->icon = $icon; + $this->label = $label; + $this->page = $page; + $this->url = ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=cloud' + ); + + return $this; + } + + + /** + * Run AmazonWS class. Entry point. + * + * @return void + */ + public function run() + { + global $config; + + // Load styles. + parent::run(); + + $mode = get_parameter('mode', null); + + if ($mode === null) { + $this->setBreadcrum(['Cloud']); + $this->printHeader(); + + echo 'Amazon WS'; + + return; + } + + if ($mode == 'amazonws') { + $this->setBreadcrum( + [ + 'Cloud', + 'Amazon AWS', + ] + ); + $this->printHeader(); + return $this->runAmazonAWS(); + } + + return null; + } + + + /** + * Checks if environment is ready, + * returns array + * icon: icon to be displayed + * label: label to be displayed + * + * @return array With data. + **/ + public function load() + { + return [ + 'icon' => $this->icon, + 'label' => $this->label, + 'url' => $this->url, + ]; + } + + + // ///////////////////////////////////////////////////////////////////////// + // Extra methods. + // ///////////////////////////////////////////////////////////////////////// + + + /** + * Amazon AWS pages manager. + * + * @return void + */ + public function runAmazonAWS() + { + global $config; + + check_login(); + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + return; + } + + // -------------------------------. + // Page 0. wizard starts HERE. + // -------------------------------. + if (!isset($this->page) || $this->page == 0) { + if (isset($this->page) === false + || $this->page == 0 + ) { + $this->printForm( + [ + 'form' => [ + 'action' => '#', + 'method' => 'POST', + ], + 'inputs' => [ + [ + 'label' => __('AWS access key ID'), + 'arguments' => [ + 'name' => 'aws_id', + 'value' => '', + 'type' => 'text', + ], + ], + [ + 'label' => __('AWS secret access key'), + 'arguments' => [ + 'name' => 'aws_id', + 'value' => '', + 'type' => 'text', + ], + ], + [ + 'arguments' => [ + 'name' => 'page', + 'value' => ($this->page + 1), + 'type' => 'hidden', + 'return' => true, + ], + ], + [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Validate'), + 'type' => 'submit', + 'attributes' => 'class="sub wand"', + 'return' => true, + ], + ], + ], + ] + ); + } + } + + if ($this->page == 1) { + echo 'TODO'; + // TODOS. + } + + if ($this->page == 100) { + return [ + 'result' => $this->result, + 'id' => $this->id, + 'msg' => $this->msg, + ]; + } + } + + +} From ec672d6bfbb7a0c133d372e772d4fd5ed4df34c1 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 13:57:33 +0100 Subject: [PATCH 130/249] H&D network scan Former-commit-id: dcd22994d6addf69ab5d68a6724d12e26e994d15 --- pandora_console/godmode/servers/discovery.php | 14 +- .../godmode/wizards/HostDevices.class.php | 135 ++++++++++++------ 2 files changed, 100 insertions(+), 49 deletions(-) diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 70da2939e7..2afbbb0f24 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -53,8 +53,18 @@ $classname_selected = get_wiz_class($wiz_in_use); if ($classname_selected !== null) { $wiz = new $classname_selected($page); $result = $wiz->run(); - // TODO: Here we'll controlle if return is a valid recon task id. - hd($result); + if (is_array($result) === true) { + if ($result['result'] === 0) { + // Success. + ui_print_success_message($result['msg']); + // TODO: Show task progress before redirect to main discovery menu. + } else { + // Failed. + ui_print_error_message($result['msg']); + } + + $classname_selected = null; + } } if ($classname_selected === null) { diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 7e2772d6e1..f31d16618b 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -160,13 +160,17 @@ class HostDevices extends Wizard } if ($mode == 'netscan') { - $this->setBreadcrum( - [ - 'Host&devices', - 'Net scan', - ] - ); - $this->printHeader(); + if ($this->page != 3) { + // Do not paint breadcrum in last page. Redirected. + $this->setBreadcrum( + [ + 'Host&devices', + 'Net scan', + ] + ); + $this->printHeader(); + } + return $this->runNetScan(); } @@ -258,6 +262,9 @@ class HostDevices extends Wizard if ($task !== false) { $this->task = $task; } + + $this->msg = __('This network scan task has been already defined. Please edit it or create a new one.'); + return false; } if (isset($this->task['id_rt']) === false) { @@ -334,6 +341,8 @@ class HostDevices extends Wizard $parent_detection = get_parameter_switch('parent_detection'); $parent_recursion = get_parameter_switch('parent_recursion'); $vlan_enabled = get_parameter_switch('vlan_enabled'); + $wmi_enabled = get_parameter_switch('wmi_enabled'); + $resolve_names = get_parameter_switch('resolve_names'); $snmp_version = get_parameter('snmp_version', null); $community = get_parameter('community', null); $snmp_context = get_parameter('snmp_context', null); @@ -357,6 +366,8 @@ class HostDevices extends Wizard $this->task['parent_detection'] = $parent_detection; $this->task['parent_recursion'] = $parent_recursion; $this->task['vlan_enabled'] = $vlan_enabled; + $this->task['wmi_enabled'] = $wmi_enabled; + $this->task['resolve_names'] = $resolve_names; $this->task['snmp_version'] = $snmp_version; $this->task['snmp_auth_user'] = $snmp_auth_user; $this->task['snmp_auth_pass'] = $snmp_auth_pass; @@ -640,9 +651,14 @@ class HostDevices extends Wizard ], ]; + $task_url = ''; + if (isset($this->task['id_rt'])) { + $task_url = '&task='.$this->task['id_rt']; + } + $form['form'] = [ 'method' => 'POST', - 'action' => $this->url.'&mode=netscan&page='.($this->page + 1), + 'action' => $this->url.'&mode=netscan&page='.($this->page + 1).$task_url, ]; // XXX: Could be improved validating inputs before continue (JS) @@ -682,12 +698,13 @@ class HostDevices extends Wizard $form['inputs'][] = [ 'label' => __('Module template'), 'arguments' => [ - 'name' => 'id_network_profile', - 'type' => 'select_from_sql', - 'sql' => 'SELECT id_np, name + 'name' => 'id_network_profile', + 'type' => 'select_from_sql', + 'sql' => 'SELECT id_np, name FROM tnetwork_profile ORDER BY name', - 'return' => true, + 'return' => true, + 'selected' => $this->task['id_network_profile'], ], ]; @@ -700,7 +717,7 @@ class HostDevices extends Wizard 'name' => 'snmp_enabled', 'type' => 'switch', 'return' => true, - 'value' => 1, + 'value' => (isset($this->task['snmp_enabled'])) ? $this->task['snmp_enabled'] : 1, 'onclick' => 'extraSNMP();', ], @@ -714,15 +731,16 @@ class HostDevices extends Wizard [ 'label' => __('SNMP version'), 'arguments' => [ - 'name' => 'snmp_version', - 'fields' => [ + 'name' => 'snmp_version', + 'fields' => [ '1' => 'v. 1', '2c' => 'v. 2c', '3' => 'v. 3', ], - 'type' => 'select', - 'script' => 'SNMPExtraShow(this.value)', - 'return' => true, + 'type' => 'select', + 'script' => 'SNMPExtraShow(this.value)', + 'selected' => $this->task['snmp_version'], + 'return' => true, ], ], ], @@ -743,6 +761,7 @@ class HostDevices extends Wizard 'arguments' => [ 'name' => 'community', 'type' => 'text', + 'value' => $this->task['snmp_community'], 'size' => 25, 'return' => true, @@ -761,6 +780,7 @@ class HostDevices extends Wizard 'arguments' => [ 'name' => 'snmp_context', 'type' => 'text', + 'value' => $this->task['snmp_community'], 'size' => 15, 'return' => true, @@ -771,6 +791,7 @@ class HostDevices extends Wizard 'arguments' => [ 'name' => 'snmp_auth_user', 'type' => 'text', + 'value' => $this->task['snmp_auth_user'], 'size' => 15, 'return' => true, @@ -786,6 +807,7 @@ class HostDevices extends Wizard 'arguments' => [ 'name' => 'snmp_auth_pass', 'type' => 'password', + 'value' => $this->task['snmp_auth_pass'], 'size' => 15, 'return' => true, @@ -794,14 +816,15 @@ class HostDevices extends Wizard [ 'label' => ''.__('Privacy method').'', 'arguments' => [ - 'name' => 'snmp_privacy_method', - 'type' => 'select', - 'fields' => [ + 'name' => 'snmp_privacy_method', + 'type' => 'select', + 'fields' => [ 'DES' => __('DES'), 'AES' => __('AES'), ], - 'size' => 15, - 'return' => true, + 'selected' => $this->task['snmp_privacy_method'], + 'size' => 15, + 'return' => true, ], ], @@ -815,6 +838,7 @@ class HostDevices extends Wizard 'arguments' => [ 'name' => 'snmp_privacy_pass', 'type' => 'password', + 'value' => $this->task['snmp_privacy_pass'], 'size' => 15, 'return' => true, @@ -823,29 +847,31 @@ class HostDevices extends Wizard [ 'label' => ''.__('Auth method').'', 'arguments' => [ - 'name' => 'snmp_auth_method', - 'type' => 'select', - 'fields' => [ + 'name' => 'snmp_auth_method', + 'type' => 'select', + 'fields' => [ 'MD5' => __('MD5'), 'SHA' => __('SHA'), ], - 'size' => 15, - 'return' => true, + 'selected' => $this->task['snmp_auth_method'], + 'size' => 15, + 'return' => true, ], ], [ 'label' => ''.__('Security level').'', 'arguments' => [ - 'name' => 'snmp_security_level', - 'type' => 'select', - 'fields' => [ + 'name' => 'snmp_security_level', + 'type' => 'select', + 'fields' => [ 'noAuthNoPriv' => __('Not auth and not privacy method'), 'authNoPriv' => __('Auth and not privacy method'), 'authPriv' => __('Auth and privacy method'), ], - 'size' => 15, - 'return' => true, + 'selected' => $this->task['snmp_security_level'], + 'size' => 15, + 'return' => true, ], ], @@ -859,22 +885,27 @@ class HostDevices extends Wizard 'arguments' => [ 'name' => 'wmi_enabled', 'type' => 'switch', + 'value' => (isset($this->task['wmi_enabled'])) ? $this->task['wmi_enabled'] : 0, 'return' => true, - 'onclick' => "\$('#wmi_extra').toggle();", + 'onclick' => 'toggleWMI();', ], ]; // WMI CONFIGURATION. $form['inputs'][] = [ - 'label' => __('WMI Auth. strings'), - 'hidden' => 1, - 'id' => 'wmi_extra', - 'arguments' => [ - 'name' => 'auth_strings', - 'type' => 'text', - 'return' => true, - + 'block_id' => 'wmi_extra', + 'hidden' => 1, + 'block_content' => [ + [ + 'label' => __('WMI Auth. strings'), + 'arguments' => [ + 'name' => 'auth_strings', + 'type' => 'text', + 'value' => $this->task['auth_strings'], + 'return' => true, + ], + ], ], ]; @@ -885,7 +916,7 @@ class HostDevices extends Wizard 'name' => 'os_detect', 'type' => 'switch', 'return' => true, - 'value' => 1, + 'value' => (isset($this->task['os_detect'])) ? $this->task['os_detect'] : 1, ], ]; @@ -897,6 +928,7 @@ class HostDevices extends Wizard 'name' => 'resolve_names', 'type' => 'switch', 'return' => true, + 'value' => (isset($this->task['resolve_names'])) ? $this->task['resolve_names'] : 0, ], ]; @@ -907,7 +939,7 @@ class HostDevices extends Wizard 'name' => 'parent_detection', 'type' => 'switch', 'return' => true, - 'value' => 1, + 'value' => (isset($this->task['parent_detection'])) ? $this->task['parent_detection'] : 1, ], ]; @@ -918,7 +950,7 @@ class HostDevices extends Wizard 'name' => 'parent_recursion', 'type' => 'switch', 'return' => true, - 'value' => 1, + 'value' => (isset($this->task['parent_recursion'])) ? $this->task['parent_recursion'] : 1, ], ]; @@ -929,7 +961,7 @@ class HostDevices extends Wizard 'name' => 'vlan_enabled', 'type' => 'switch', 'return' => true, - 'value' => 1, + 'value' => (isset($this->task['vlan_enabled'])) ? $this->task['vlan_enabled'] : 1, ], ]; @@ -979,8 +1011,16 @@ function extraSNMP() { } } +function toggleWMI() { + if (document.getElementsByName("wmi_enabled")[0].checked) + $("#wmi_extra").show(); + else + $("#wmi_extra").hide(); +} + $(function() { - SNMPExtraShow($("#snmp_version").val()) + SNMPExtraShow($("#snmp_version").val()); + toggleWMI(); }); '; @@ -1082,6 +1122,7 @@ $("select#interval_manual_defined").change(function() { }).change();'; $this->printForm($form); + return null; } if ($this->page == 3) { From 32d34cd09b9ff6fbfed2e6d9a77d3aaf7232a3b0 Mon Sep 17 00:00:00 2001 From: manuel Date: Fri, 15 Feb 2019 14:02:32 +0100 Subject: [PATCH 131/249] Changed styles in host and devices Former-commit-id: 743f203466e8e3745a33837054e5bc4faa69337c --- pandora_console/godmode/servers/discovery.php | 9 +++--- .../godmode/wizards/HostDevices.class.php | 21 +++++++++++-- pandora_console/images/wizard/csv_image.svg | 4 +++ pandora_console/include/styles/discovery.css | 30 +++++++++++++++++++ 4 files changed, 56 insertions(+), 8 deletions(-) create mode 100644 pandora_console/images/wizard/csv_image.svg diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 70da2939e7..39cc86675c 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -15,7 +15,7 @@ if (! check_acl($config['id_user'], 0, 'AW')) { ui_require_css_file('discovery'); -ui_print_page_header(__('Discover'), 'wizards/hostDevices.png', false, '', true); +ui_print_page_header(__('Discover'), '', false, '', true); /** @@ -64,13 +64,12 @@ if ($classname_selected === null) { $classname = basename($classpath, '.class.php'); $obj = new $classname(); $wiz_data = $obj->load(); - - hd($wiz_data); ?> +
  • - <?php echo $classname; ?> -
    + <?php echo $classname; ?> +
  • diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 7e2772d6e1..157657d237 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -138,9 +138,24 @@ class HostDevices extends Wizard if ($mode === null) { $this->setBreadcrum(['Host&devices']); $this->printHeader(); - - echo 'Importar csv'; - echo 'Escanear red'; + echo '
    '; + echo '
    '; + echo '
    '; + echo 'importcsv'; + echo '
    '; + echo '
    '; + echo ''.__('Import CSV').''; + echo '
    '; + echo '
    '; + echo '
    '; + echo '
    '; + echo 'importcsv'; + echo '
    '; + echo '
    '; + echo ''.__('Escanear red').''; + echo '
    '; + echo '
    '; + echo '
    '; return; } diff --git a/pandora_console/images/wizard/csv_image.svg b/pandora_console/images/wizard/csv_image.svg new file mode 100644 index 0000000000..1e82511472 --- /dev/null +++ b/pandora_console/images/wizard/csv_image.svg @@ -0,0 +1,4 @@ + + + + diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css index 62be6c7c98..5f2cc45b68 100644 --- a/pandora_console/include/styles/discovery.css +++ b/pandora_console/include/styles/discovery.css @@ -1,3 +1,33 @@ /* * Discovery css global */ + +#contenedor_principal { + height: auto; + position: relative; + margin: auto; +} +#contenedor_imagen_texto { + width: 11%; + height: auto; + position: relative; + display: inline-block; + vertical-align: top; + overflow: hidden; + margin-right: 5%; +} +#imagen { + width: 15%; + height: auto; + position: relative; + display: inline; +} +.texto { + height: auto; + text-align: center; +} +#text_wizard { + font-weight: bolder; + text-decoration: none; + font-size: 24px; +} From e397353f71b2cb60bab75a65ad788cb5d91f814f Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 14:03:16 +0100 Subject: [PATCH 132/249] minor fix get_parameter_switch Former-commit-id: c8e430e1cbd789a99058217e7dffb4098aab821a --- pandora_console/include/functions.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index 58120c4616..e1861e70a3 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -862,9 +862,11 @@ function get_parameter_checkbox($name, $default='') */ function get_parameter_switch($name, $default='') { - $data = get_parameter($name, 0); + $data = get_parameter($name, null); - if ($data == 'on') { + if ($data === null) { + return 0; + } else if ($data == 'on') { return 1; } From c62c01c4a0cc26759b1dcc68dbc69720b96a8ea0 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 14:14:56 +0100 Subject: [PATCH 133/249] H&D minor fix - visual Former-commit-id: 57d1e3c62192d9568bfa4db11658e31a8d811a3a --- .../godmode/wizards/HostDevices.class.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index c7eddc84f4..adbc13180e 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -740,7 +740,7 @@ class HostDevices extends Wizard // SNMP CONFIGURATION. $form['inputs'][] = [ - 'hidden' => 0, + 'hidden' => 1, 'block_id' => 'snmp_extra', 'block_content' => [ [ @@ -995,10 +995,12 @@ class HostDevices extends Wizard function SNMPExtraShow(target) { $("#snmp_options_basic").hide(); $("#snmp_options_v3").hide(); - if (target == 3) { - $("#snmp_options_v3").show(); - } else { - $("#snmp_options_basic").show(); + if (document.getElementsByName("snmp_enabled")[0].checked) { + if (target == 3) { + $("#snmp_options_v3").show(); + } else { + $("#snmp_options_basic").show(); + } } } From 087978aa701e0939daa60553d5fe97b9ce44aebc Mon Sep 17 00:00:00 2001 From: daniel Date: Fri, 15 Feb 2019 14:36:58 +0100 Subject: [PATCH 134/249] fixed errors in reports Former-commit-id: de2cb22c4545dd5ae859f7059e5c8ba13a195723 --- .../include/functions_reporting_html.php | 281 ++++++++++++++---- 1 file changed, 219 insertions(+), 62 deletions(-) diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index 935c12c871..b882cc0ae0 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -1496,11 +1496,12 @@ function reporting_html_agent_module($table, $item) $table_data .= "".$file_name.''; foreach ($row['modules'] as $module_name => $module) { - if (is_null($module)) { + if ($module === null) { $table_data .= ""; } else { $table_data .= ""; switch ($module) { + default: case AGENT_STATUS_NORMAL: $table_data .= ui_print_status_image( 'module_ok.png', @@ -1756,6 +1757,15 @@ function reporting_html_exception($table, $item, $pdf=0) } +/** + * Function to print to HTML group report. + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf If it comes from pdf. + * + * @return html + */ function reporting_html_group_report($table, $item, $pdf=0) { global $config; @@ -2266,7 +2276,11 @@ function reporting_html_alert_report($table, $item, $pdf=0) $table1->valign = []; if ($item['data'] == null) { - $table->data['alerts']['cell'] = ui_print_empty_data(__('No alerts defined'), '', true); + $table->data['alerts']['cell'] = ui_print_empty_data( + __('No alerts defined'), + '', + true + ); return true; } @@ -2298,7 +2312,7 @@ function reporting_html_alert_report($table, $item, $pdf=0) $row['fired'] = ''; foreach ($alert['actions'] as $action) { if ($action['name'] == '') { - // Removed from retrieved hash + // Removed from retrieved hash. continue; } @@ -2315,7 +2329,7 @@ function reporting_html_alert_report($table, $item, $pdf=0) $row['tfired'] .= '
    '.$fired.'
    '."\n"; } - // Skip first td's to avoid repeat the agent and module names + // Skip first td's to avoid repeat the agent and module names. $table1->data[] = $row; if ($td > 1) { for ($i = 0; $i < $td; $i++) { @@ -2355,7 +2369,18 @@ function reporting_html_sql_graph($table, $item) } -function reporting_html_monitor_report($table, $item, $mini) +/** + * It shows the percentage of time a module has been + * right or wrong within a predefined period. + * + * @param object $table Parameters table. + * @param array $item Items data. + * @param boolean $mini True or flase. + * @param integer $pdf Values 0 or 1. + * + * @return mixed + */ +function reporting_html_monitor_report($table, $item, $mini, $pdf=0) { global $config; @@ -2377,16 +2402,50 @@ function reporting_html_monitor_report($table, $item, $mini) $table1->data['data']['unknown'] .= __('Unknown').'

    '; } else { $table1->data['data']['ok'] = '

    '; - $table1->data['data']['ok'] .= html_print_image('images/module_ok.png', true).' '.__('OK').': '.remove_right_zeros(number_format($item['data']['ok']['formated_value'], $config['graph_precision'])).' %

    '; + $table1->data['data']['ok'] .= html_print_image( + 'images/module_ok.png', + true + ).' '.__('OK').': '.remove_right_zeros( + number_format( + $item['data']['ok']['formated_value'], + $config['graph_precision'] + ) + ).' %

    '; $table1->data['data']['fail'] = '

    '; - $table1->data['data']['fail'] .= html_print_image('images/module_critical.png', true).' '.__('Not OK').': '.remove_right_zeros(number_format($item['data']['fail']['formated_value'], $config['graph_precision'])).' % '.'

    '; + $table1->data['data']['fail'] .= html_print_image( + 'images/module_critical.png', + true + ).' '.__('Not OK').': '.remove_right_zeros( + number_format( + $item['data']['fail']['formated_value'], + $config['graph_precision'] + ) + ).' % '.'

    '; } - $table->data['module']['cell'] = html_print_table($table1, true); + if ($pdf === 0) { + $table->data['module']['cell'] = html_print_table( + $table1, + true + ); + } else { + return html_print_table( + $table1, + true + ); + } } +/** + * Print report html. + * + * @param object $table Parameters table. + * @param array $item Items data. + * + * @return mixed + */ function reporting_html_graph($table, $item) { $table->colspan['chart']['cell'] = 3; @@ -2395,6 +2454,15 @@ function reporting_html_graph($table, $item) } +/** + * Print report prediction date. + * + * @param object $table Parameters table. + * @param array $item Items data. + * @param boolean $mini True or False. + * + * @return mixed + */ function reporting_html_prediction_date($table, $item, $mini) { reporting_html_value($table, $item, $mini, true); @@ -2719,10 +2787,31 @@ function reporting_html_text(&$table, $item) } -function reporting_html_availability(&$table, $item) +/** + * Report availability + * + * @param string $table Reference table in pdf a false. + * @param array $item Parameters for item pdf. + * @param boolean $pdf Send pdf. + * + * @return html + */ +function reporting_html_availability($table, $item, $pdf=0) { - $style = db_get_value('style', 'treport_content', 'id_rc', $item['id_rc']); - $style = json_decode(io_safe_output($style), true); + $retun_pdf = ''; + + $style = db_get_value( + 'style', + 'treport_content', + 'id_rc', + $item['id_rc'] + ); + + $style = json_decode( + io_safe_output($style), + true + ); + $same_agent_in_resume = ''; global $config; @@ -2886,16 +2975,30 @@ function reporting_html_availability(&$table, $item) $table->data['error']['cell'] = __('There are no Agent/Modules defined'); } - $table->colspan[1][0] = 2; - $table->colspan[2][0] = 2; - $data = []; - $data[0] = html_print_table($table1, true); - array_push($table->data, $data); + if ($pdf === 0) { + $table->colspan[1][0] = 2; + $table->colspan[2][0] = 2; + $data = []; + $data[0] = html_print_table($table1, true); + array_push($table->data, $data); + } else { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table($table1, true); + } if ($item['resume']['resume']) { - $data2 = []; - $data2[0] = html_print_table($table2, true); - array_push($table->data, $data2); + if ($pdf === 0) { + $data2 = []; + $data2[0] = html_print_table($table2, true); + array_push($table->data, $data2); + } else { + $table2->title = $item['title']; + $table2->titleclass = 'title_table_pdf'; + $table2->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table($table2, true); + } } if ($item['resume']['resume'] && !empty($item['data'])) { @@ -2925,18 +3028,41 @@ function reporting_html_availability(&$table, $item) $table1->data[] = [ 'max_text' => $item['resume']['max_text'], - 'max' => sla_truncate($item['resume']['max'], $config['graph_precision']).'%', + 'max' => sla_truncate( + $item['resume']['max'], + $config['graph_precision'] + ).'%', 'min_text' => $item['resume']['min_text'], - 'min' => sla_truncate($item['resume']['min'], $config['graph_precision']).'%', + 'min' => sla_truncate( + $item['resume']['min'], + $config['graph_precision'] + ).'%', 'avg' => ''.sla_truncate($item['resume']['avg'], $config['graph_precision']).'%', ]; - $table->colspan[3][0] = 3; - $data = []; - $data[0] = html_print_table($table1, true); - array_push($table->data, $data); + if ($pdf === 0) { + $table->colspan[3][0] = 3; + $data = []; + $data[0] = html_print_table( + $table1, + true + ); + array_push($table->data, $data); + } else { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table( + $table1, + true + ); + } } } + + if ($pdf !== 0) { + return $return_pdf; + } } @@ -3069,6 +3195,13 @@ function reporting_html_availability_graph($table, $item, $pdf=0) } +/** + * Function for first time data agent. + * + * @param string $agent_name Agent name. + * + * @return array + */ function get_agent_first_time($agent_name) { $id = agents_get_agent_id($agent_name, true); @@ -3347,6 +3480,15 @@ function reporting_html_sql($table, $item, $pdf=0) } +/** + * Function for stats. + * + * @param array $data Array item. + * @param integer $graph_width Items data. + * @param integer $graph_height If it comes from pdf. + * + * @return html + */ function reporting_get_stats_summary($data, $graph_width, $graph_height) { global $config; @@ -3376,13 +3518,21 @@ function reporting_get_stats_summary($data, $graph_width, $graph_height) $tdata[0] = '
    '.graph_agent_status(false, $graph_width, $graph_height, true, true).'
    '; } else { - $tdata[2] = html_print_image('images/image_problem_area_small.png', true, ['width' => $graph_width]); + $tdata[2] = html_print_image( + 'images/image_problem_area_small.png', + true, + ['width' => $graph_width] + ); } if ($data['monitor_alerts'] > 0) { $tdata[2] = '
    '.graph_alert_status($data['monitor_alerts'], $data['monitor_alerts_fired'], $graph_width, $graph_height, true, true).'
    '; } else { - $tdata[2] = html_print_image('images/image_problem_area_small.png', true, ['width' => $graph_width]); + $tdata[2] = html_print_image( + 'images/image_problem_area_small.png', + true, + ['width' => $graph_width] + ); } $table_sum->rowclass[] = ''; @@ -3401,10 +3551,11 @@ function reporting_get_stats_summary($data, $graph_width, $graph_height) * It construct a table object with all the events happened in a group * during a period of time. * - * @param int Group id to get the report. - * @param int Period of time to get the report. - * @param int Beginning date of the report - * @param int Flag to return or echo the report table (echo by default). + * @param integer $id_group Group id to get the report. + * @param integer $period Period of time to get the report. + * @param integer $date Beginning date of the report. + * @param boolean $return Flag to return or echo the + * report table (echo by default). * * @return object A table object */ @@ -3437,7 +3588,7 @@ function reporting_event_reporting($id_group, $period, $date=0, $return=false) } $data[1] = $event['evento']; - $data[2] = $event['id_usuario'] != '0' ? $event['id_usuario'] : ''; + $data[2] = ($event['id_usuario'] != '0') ? $event['id_usuario'] : ''; $data[3] = $event['timestamp']; array_push($table->data, $data); } @@ -3453,8 +3604,9 @@ function reporting_event_reporting($id_group, $period, $date=0, $return=false) /** * Get a table report from a alerts fired array. * - * @param array Alerts fired array. - * @see function get_alerts_fired () + * @param array $alerts_fired Alerts fired array. + * + * @see function get_alerts_fired () * * @return object A table object with a report of the fired alerts. */ @@ -3515,8 +3667,9 @@ function reporting_get_fired_alerts_table($alerts_fired) /** * Get a report table with all the monitors down. * - * @param array An array with all the monitors down - * @see function modules_get_monitors_down() + * @param array $monitors_down An array with all the monitors down. + * + * @see Function modules_get_monitors_down(). * * @return object A table object with a monitors down report. */ @@ -3570,8 +3723,8 @@ function reporting_get_monitors_down_table($monitors_down) * * It shows the number of agents and no more things right now. * - * @param int Group to get the report - * @param bool Flag to return or echo the report (by default). + * @param integer $id_group Group to get the report. + * @param boolean $return Flag to return or echo the report (by default). * * @return HTML string with group report */ @@ -3591,9 +3744,10 @@ function reporting_print_group_reporting($id_group, $return=false) /** * Get a report table of the fired alerts group by agents. * - * @param int Agent id to generate the report. - * @param int Period of time of the report. - * @param int Beginning date of the report in UNIX time (current date by default). + * @param integer $id_agent Agent id to generate the report. + * @param integer $period Period of time of the report. + * @param integer $date Beginning date of the report in + * UNIX time (current date by default). * * @return object A table object with the alert reporting.. */ @@ -3637,23 +3791,19 @@ function reporting_get_agent_alerts_table($id_agent, $period=0, $date=0) case 'equal': case 'not_equal': $data[2] = $template['value']; - break; case 'max-min': $data[2] = __('Min.').': '.$template['min_value'].' '; $data[2] .= __('Max.').': '.$template['max_value'].' '; - break; case 'max': $data[2] = $template['max_value']; - break; case 'min': $data[2] = $template['min_value']; - break; } @@ -3671,9 +3821,10 @@ function reporting_get_agent_alerts_table($id_agent, $period=0, $date=0) /** * Get a report of monitors in an agent. * - * @param int Agent id to get the report - * @param int Period of time of the report. - * @param int Beginning date of the report in UNIX time (current date by default). + * @param integer $id_agent Agent id to get the report. + * @param integer $period Period of time of the report. + * @param integer $date Beginning date of the report in UNIX time + * (current date by default). * * @return object A table object with the report. */ @@ -3722,9 +3873,10 @@ function reporting_get_agent_monitors_table($id_agent, $period=0, $date=0) /** * Get a report of all the modules in an agent. * - * @param int Agent id to get the report. - * @param int Period of time of the report - * @param int Beginning date of the report in UNIX time (current date by default). + * @param integer $id_agent Agent id to get the report. + * @param integer $period Period of time of the report. + * @param integer $date Beginning date of the report in UNIX time + * (current date by default). * * @return object */ @@ -3756,19 +3908,24 @@ function reporting_get_agent_modules_table($id_agent, $period=0, $date=0) /** * Get a detailed report of an agent * - * @param int Agent to get the report. - * @param int Period of time of the desired report. - * @param int Beginning date of the report in UNIX time (current date by default). - * @param bool Flag to return or echo the report (by default). + * @param integer $id_agent Agent to get the report. + * @param integer $period Period of time of the desired report. + * @param integer $date Beginning date of the report in UNIX time + * (current date by default). + * @param boolean $return Flag to return or echo the report (by default). * * @return string */ -function reporting_get_agent_detailed($id_agent, $period=0, $date=0, $return=false) -{ +function reporting_get_agent_detailed( + $id_agent, + $period=0, + $date=0, + $return=false +) { $output = ''; $n_a_string = __('N/A(*)'); - // Show modules in agent + // Show modules in agent. $output .= '
    '; $output .= '

    '.__('Agent').' - '.agents_get_alias($id_agent).'

    '; $output .= '

    '.__('Modules').'

    '; @@ -3776,17 +3933,17 @@ function reporting_get_agent_detailed($id_agent, $period=0, $date=0, $return=fal $table_modules->width = '99%'; $output .= html_print_table($table_modules, true); - // Show alerts in agent + // Show alerts in agent. $table_alerts = reporting_get_agent_alerts_table($id_agent, $period, $date); $table_alerts->width = '99%'; - if (sizeof($table_alerts->data)) { + if (count($table_alerts->data)) { $output .= '

    '.__('Alerts').'

    '; $output .= html_print_table($table_alerts, true); } - // Show monitor status in agent (if any) + // Show monitor status in agent (if any). $table_monitors = reporting_get_agent_monitors_table($id_agent, $period, $date); - if (sizeof($table_monitors->data) == 0) { + if (count($table_monitors->data) == 0) { $output .= '
    '; if (! $return) { echo $output; From 45fd528e3880bea244a350425fbb4003013e0c7f Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 16:02:55 +0100 Subject: [PATCH 135/249] minor fixes H&D Former-commit-id: c3236b91b4b6a0f37af2d4da4955c711dd4ace43 --- pandora_console/godmode/wizards/HostDevices.class.php | 5 ++--- pandora_server/lib/PandoraFMS/Recon/Base.pm | 3 +++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index adbc13180e..12fcaaa39e 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -276,10 +276,9 @@ class HostDevices extends Wizard if ($task !== false) { $this->task = $task; + $this->msg = __('This network scan task has been already defined. Please edit it or create a new one.'); + return false; } - - $this->msg = __('This network scan task has been already defined. Please edit it or create a new one.'); - return false; } if (isset($this->task['id_rt']) === false) { diff --git a/pandora_server/lib/PandoraFMS/Recon/Base.pm b/pandora_server/lib/PandoraFMS/Recon/Base.pm index 8d24ebf311..116bcd75e6 100644 --- a/pandora_server/lib/PandoraFMS/Recon/Base.pm +++ b/pandora_server/lib/PandoraFMS/Recon/Base.pm @@ -1500,6 +1500,9 @@ sub snmp_get_command { my $command = "snmpwalk -M/dev/null -r$self->{'snmp_checks'} -t$self->{'snmp_timeout'} -v$self->{'snmp_version'} -On -Oe "; if ($self->{'snmp_version'} eq "3") { + if ($self->{'community'}) { # Context + $command .= " -N $self->{'community} "; + } $command .= " -l$self->{'snmp_security_level'} "; if ($self->{'snmp_security_level'} ne "noAuthNoPriv") { $command .= " -u$self->{'snmp_auth_user'} -a$self->{'snmp_auth_method'} -A$self->{'snmp_auth_pass'} "; From 7a1b66755deea0a35d5f3ba83fb455726b54db93 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 16:06:28 +0100 Subject: [PATCH 136/249] minor fixes H&D Former-commit-id: a4ffc2e761dc0a4d06209fb1c448bc17d5d45022 --- pandora_server/lib/PandoraFMS/Recon/Base.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_server/lib/PandoraFMS/Recon/Base.pm b/pandora_server/lib/PandoraFMS/Recon/Base.pm index 116bcd75e6..e819b06476 100644 --- a/pandora_server/lib/PandoraFMS/Recon/Base.pm +++ b/pandora_server/lib/PandoraFMS/Recon/Base.pm @@ -1501,7 +1501,7 @@ sub snmp_get_command { my $command = "snmpwalk -M/dev/null -r$self->{'snmp_checks'} -t$self->{'snmp_timeout'} -v$self->{'snmp_version'} -On -Oe "; if ($self->{'snmp_version'} eq "3") { if ($self->{'community'}) { # Context - $command .= " -N $self->{'community} "; + $command .= " -N $self->{'community'} "; } $command .= " -l$self->{'snmp_security_level'} "; if ($self->{'snmp_security_level'} ne "noAuthNoPriv") { From 0f375d6a766e5118f999c9337b8368c4d1abedd5 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 16:37:48 +0100 Subject: [PATCH 137/249] H&D minor fix group cannot be All Former-commit-id: 2feb42ce06bd379bbb3804a30fab744a4b01b1e1 --- .../godmode/wizards/HostDevices.class.php | 54 +++++++++++++++---- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 12fcaaa39e..f619d2d706 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -420,7 +420,12 @@ class HostDevices extends Wizard } $interval = get_parameter('interval', 0); + $id_os = get_parameter('id_os', 0); + $recon_ports = get_parameter('recon_ports', ''); + + $this->task['id_os'] = $id_os; $this->task['interval_sweep'] = $interval; + $this->task['recon_ports'] = $recon_ports; if ($this->task['disabled'] == 2) { // Wizard finished. @@ -640,11 +645,12 @@ class HostDevices extends Wizard $form['inputs'][] = [ 'label' => ''.__('Group').'', 'arguments' => [ - 'name' => 'id_group', - 'privilege' => 'PM', - 'type' => 'select_groups', - 'selected' => $this->task['id_group'], - 'return' => true, + 'name' => 'id_group', + 'returnAllGroup' => false, + 'privilege' => 'PM', + 'type' => 'select_groups', + 'selected' => $this->task['id_group'], + 'return' => true, ], ]; @@ -724,7 +730,7 @@ class HostDevices extends Wizard ]; // Feature configuration. - // Input: Module template. + // Input: SNMP enabled. $form['inputs'][] = [ 'label' => __('SNMP enabled'), 'arguments' => [ @@ -923,7 +929,7 @@ class HostDevices extends Wizard ], ]; - // Input: Module template. + // Input: Enforce os detection. $form['inputs'][] = [ 'label' => __('OS detection'), 'arguments' => [ @@ -1051,10 +1057,40 @@ $(function() { if ($this->page == 2) { // Interval and schedules. $interv_manual = 0; - if ((int) $interval == 0) { + if ((int) $this->task['interval_sweep'] == 0) { $interv_manual = 1; } + // Filter: OS. + $form['inputs'][] = [ + 'label' => ''.__('Filter by OS').'', + 'arguments' => [ + 'type' => 'select_from_sql', + 'sql' => 'SELECT id_os, name + FROM tconfig_os + ORDER BY name', + 'name' => 'id_os', + 'return' => 'true', + 'nothing' => __('Any'), + 'selected' => $this->task['id_os'], + ], + ]; + + // Filter: Ports. + $form['inputs'][] = [ + 'label' => ''.__('Filter by ports').''.ui_print_help_tip( + __('Ports defined like: 80 or 80,443,512 or even 0-1024 (Like Nmap command line format). If dont want to do a sweep using portscan, left it in blank'), + true + ), + 'arguments' => [ + 'type' => 'text', + 'name' => 'recon_ports', + 'return' => 'true', + 'recon_ports' => $this->task['recon_ports'], + ], + ]; + + // Schedule. $form['inputs'][] = [ 'label' => ''.__('Interval').''.ui_print_help_tip( __('Manual interval means that it will be executed only On-demand'), @@ -1072,7 +1108,7 @@ $(function() { ], 'extra' => ''.html_print_extended_select_for_time( 'interval', - $interval, + $this->task['interval_sweep'], '', '', '0', From 5093094d7d20bc4e1e1b6fc5f3b9e75ce98ed32b Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 18:05:59 +0100 Subject: [PATCH 138/249] H&D tasklist and some visual changes Former-commit-id: d9130ec520b0c23a9cf42ce62aae6c3d2432649b --- pandora_console/godmode/servers/discovery.php | 15 +- .../wizards/DiscoveryTaskList.class.php | 297 ++++++++++++++++++ .../godmode/wizards/HostDevices.class.php | 59 +--- .../godmode/wizards/Wizard.main.php | 70 ++++- pandora_console/images/wizard/hostdevices.svg | 4 + pandora_console/images/wizard/tasklist.svg | 4 + pandora_console/include/styles/discovery.css | 37 +++ 7 files changed, 430 insertions(+), 56 deletions(-) create mode 100644 pandora_console/godmode/wizards/DiscoveryTaskList.class.php create mode 100644 pandora_console/images/wizard/hostdevices.svg create mode 100644 pandora_console/images/wizard/tasklist.svg diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 456bf05c01..024eb39e30 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -30,6 +30,9 @@ function get_wiz_class($str) case 'hd': return 'HostDevices'; + case 'tasklist': + return 'DiscoveryTaskList'; + default: // Ignore. return null; @@ -37,6 +40,10 @@ function get_wiz_class($str) } +/* + * CLASS LOADER. + */ + // Dynamic class loader. $classes = glob($config['homedir'].'/godmode/wizards/*.class.php'); foreach ($classes as $classpath) { @@ -76,10 +83,12 @@ if ($classname_selected === null) { $wiz_data = $obj->load(); ?> -
  • +
  • - <?php echo $classname; ?> -
    +
    + +
    +
  • diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php new file mode 100644 index 0000000000..0ad4af9683 --- /dev/null +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -0,0 +1,297 @@ +setBreadcrum([]); + + $this->task = []; + $this->msg = $msg; + $this->icon = $icon; + $this->label = __($label); + $this->page = $page; + $this->url = ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist' + ); + + return $this; + } + + + /** + * Implements run method. + * + * @return mixed Returns null if wizard is ongoing. Result if done. + */ + public function run() + { + // Load styles. + parent::run(); + return $this->showList(); + } + + + /** + * Implements load method. + * + * @return mixed Skeleton for button. + */ + public function load() + { + return [ + 'icon' => $this->icon, + 'label' => $this->label, + 'url' => $this->url, + + ]; + + } + + + /** + * Show complete list of running tasks. + * + * @return boolean Success or not. + */ + public function showList() + { + global $config; + + check_login(); + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access recon task viewer' + ); + include 'general/noaccess.php'; + return; + } + + // Get all recon servers + $servers = db_get_all_rows_sql('SELECT * FROM tserver WHERE server_type = 3'); + if ($servers === false) { + $servers = []; + ui_print_error_message(__('Discovery Server is disabled')); + return; + } else { + $recon_task = db_get_all_rows_sql('SELECT * FROM trecon_task'); + if ($recon_task === false) { + ui_print_page_header(__('Recon View'), 'images/op_recon.png', false, '', false); + include_once $config['homedir'].'/general/firts_task/recon_view.php'; + return; + } else { + include_once $config['homedir'].'/include/functions_graph.php'; + include_once $config['homedir'].'/include/functions_servers.php'; + include_once $config['homedir'].'/include/functions_network_profiles.php'; + + $modules_server = 0; + $total_modules = 0; + $total_modules_data = 0; + + // -------------------------------- + // FORCE A RECON TASK + // -------------------------------- + if (check_acl($config['id_user'], 0, 'PM')) { + if (isset($_GET['force'])) { + $id = (int) get_parameter_get('force', 0); + servers_force_recon_task($id); + } + } + + foreach ($servers as $serverItem) { + $id_server = $serverItem['id_server']; + $server_name = servers_get_name($id_server); + $recon_tasks = db_get_all_rows_field_filter('trecon_task', 'id_recon_server', $id_server); + + // Show network tasks for Recon Server + if ($recon_tasks === false) { + $recon_tasks = []; + } + + $table = new StdClass(); + $table->cellpadding = 4; + $table->cellspacing = 4; + $table->width = '100%'; + $table->class = 'databox data'; + $table->head = []; + $table->data = []; + $table->align = []; + $table->headstyle = []; + for ($i = 0; $i < 9; $i++) { + $table->headstyle[$i] = 'text-align: left;'; + } + + $table->head[0] = __('Force'); + $table->align[0] = 'left'; + + $table->head[1] = __('Task name'); + $table->align[1] = 'left'; + + $table->head[2] = __('Interval'); + $table->align[2] = 'left'; + + $table->head[3] = __('Network'); + $table->align[3] = 'left'; + + $table->head[4] = __('Status'); + $table->align[4] = 'left'; + + $table->head[5] = __('Template'); + $table->align[5] = 'left'; + + $table->head[6] = __('Progress'); + $table->align[6] = 'left'; + + $table->head[7] = __('Updated at'); + $table->align[7] = 'left'; + + $table->head[8] = __('Edit'); + $table->align[8] = 'left'; + + foreach ($recon_tasks as $task) { + $data = []; + + if ($task['disabled'] == 0) { + $data[0] = ''; + $data[0] .= html_print_image('images/target.png', true, ['title' => __('Force')]); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = ''.$task['name'].''; + + $data[2] = human_time_description_raw($task['interval_sweep']); + + if ($task['id_recon_script'] == 0) { + $data[3] = $task['subnet']; + } else { + $data[3] = '-'; + } + + if ($task['status'] <= 0) { + $data[4] = __('Done'); + } else { + $data[4] = __('Pending'); + } + + if ($task['id_recon_script'] == 0) { + // Network recon task + $data[5] = html_print_image('images/network.png', true, ['title' => __('Network recon task')]).'  '; + $data[5] .= network_profiles_get_name($task['id_network_profile']); + } else { + // APP recon task + $data[5] = html_print_image('images/plugin.png', true).'  '; + $data[5] .= db_get_sql(sprintf('SELECT name FROM trecon_script WHERE id_recon_script = %d', $task['id_recon_script'])); + } + + if ($task['status'] <= 0 || $task['status'] > 100) { + $data[6] = '-'; + } else { + $data[6] = progress_bar($task['status'], 100, 20, __('Progress').':'.$task['status'].'%', 1); + } + + $data[7] = ui_print_timestamp($task['utimestamp'], true); + + if (check_acl($config['id_user'], $task['id_group'], 'PM')) { + $data[8] = ''.html_print_image( + 'images/wrench_orange.png', + true + ).''; + } else { + $data[8] = ''; + } + + array_push($table->data, $data); + } + + if (empty($table->data)) { + echo '
    '.__('Server').' '.$server_name.' '.__('has no recon tasks assigned').'
    '; + } else { + html_print_table($table); + } + + unset($table); + } + } + } + + $form = [ + 'form' => [ + 'method' => 'POST', + 'action' => ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery' + ), + ], + 'inputs' => [ + [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Go back'), + 'type' => 'submit', + 'attributes' => 'class="sub cancel"', + 'return' => true, + ], + ], + ], + ]; + + $this->printForm($form); + + return true; + } + + +} diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index f619d2d706..633fbfe19f 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -31,56 +31,12 @@ require_once $config['homedir'].'/include/functions_users.php'; enterprise_include('include/class/CSVImportAgents.class.php'); /** - * Undocumented class + * Wizard section Host&devices. + * Provides classic recon task creation. + * In enterprise environments, provides also CSV agent import features. */ class HostDevices extends Wizard { - // CSV constants. - const HDW_CSV_NOT_DATA = 0; - const HDW_CSV_DUPLICATED = 0; - const HDW_CSV_GROUP_EXISTS = 0; - - /** - * Undocumented variable - * - * @var array - */ - public $values = []; - - /** - * Undocumented variable - * - * @var [type] - */ - public $result; - - /** - * Undocumented variable - * - * @var [type] - */ - public $msg; - - /** - * Undocumented variable - * - * @var [type] - */ - public $icon; - - /** - * Undocumented variable - * - * @var [type] - */ - public $label; - - /** - * Undocumented variable - * - * @var [type] - */ - public $url; /** * Stores all needed parameters to create a recon task. @@ -91,7 +47,7 @@ class HostDevices extends Wizard /** - * Undocumented function. + * Constructor. * * @param integer $page Start page, by default 0. * @param string $msg Mensajito. @@ -103,7 +59,7 @@ class HostDevices extends Wizard public function __construct( int $page=0, string $msg='Default message. Not set.', - string $icon='hostDevices.png', + string $icon='images/wizard/hostdevices.svg', string $label='Host & Devices' ) { $this->setBreadcrum([]); @@ -122,9 +78,9 @@ class HostDevices extends Wizard /** - * Undocumented function + * Run wizard manager. * - * @return void + * @return mixed Returns null if wizard is ongoing. Result if done. */ public function run() { @@ -684,6 +640,7 @@ class HostDevices extends Wizard // XXX: Could be improved validating inputs before continue (JS) // Print NetScan page 0. $this->printForm($form); + $this->printGoBackButton(); } } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 1a70bae362..ecc253ad04 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -20,6 +20,41 @@ class Wizard */ public $page; + /** + * Target icon to be shown in discovery wizard list. + * + * @var string + */ + public $icon; + + /** + * Target label to be shown in discovery wizard list. + * + * @var string + */ + public $label; + + /** + * This wizard's url. + * + * @var string + */ + public $url; + + /** + * Result of wizard execution (0 - ok, 1 - not ok). + * + * @var integer + */ + public $result; + + /** + * Message to be delivered to user. + * + * @var string + */ + public $msg; + /** * Setter for breadcrum @@ -285,13 +320,13 @@ class Wizard ); case 'submit': - return html_print_submit_button( + return '
    '.html_print_submit_button( ((isset($data['label']) === true) ? $data['label'] : 'OK'), ((isset($data['name']) === true) ? $data['name'] : ''), ((isset($data['disabled']) === true) ? $data['disabled'] : false), ((isset($data['attributes']) === true) ? $data['attributes'] : ''), ((isset($data['return']) === true) ? $data['return'] : false) - ); + ).'
    '; case 'checkbox': return html_print_checkbox( @@ -316,6 +351,37 @@ class Wizard } + /** + * Prints a go back button redirecting to main page. + * + * @return void + */ + public function printGoBackButton() + { + $form = [ + 'form' => [ + 'method' => 'POST', + 'action' => ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery' + ), + ], + 'inputs' => [ + [ + 'arguments' => [ + 'name' => 'submit', + 'label' => __('Go back'), + 'type' => 'submit', + 'attributes' => 'class="sub cancel"', + 'return' => true, + ], + ], + ], + ]; + + $this->printForm($form); + } + + /** * Print a block of inputs. * diff --git a/pandora_console/images/wizard/hostdevices.svg b/pandora_console/images/wizard/hostdevices.svg new file mode 100644 index 0000000000..1e82511472 --- /dev/null +++ b/pandora_console/images/wizard/hostdevices.svg @@ -0,0 +1,4 @@ + + + + diff --git a/pandora_console/images/wizard/tasklist.svg b/pandora_console/images/wizard/tasklist.svg new file mode 100644 index 0000000000..1e82511472 --- /dev/null +++ b/pandora_console/images/wizard/tasklist.svg @@ -0,0 +1,4 @@ + + + + diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css index 5f2cc45b68..df393fdf3e 100644 --- a/pandora_console/include/styles/discovery.css +++ b/pandora_console/include/styles/discovery.css @@ -2,6 +2,43 @@ * Discovery css global */ +li.discovery { + display: inline-block; + float: left; + width: 250px; + height: 120px; + margin: 15px; +} + +li.discovery > a { + text-decoration: none; +} + +li.discovery > a:hover { + color: #000; +} + +li.discovery img { + height: 90px; +} + +li.discovery > a label { + cursor: pointer; +} + +div.data_container { + width: 100%; + height: 100%; + text-align: center; + border: 1px solid #ddd; + padding-top: 30px; + padding-bottom: 30px; +} + +div.data_container:hover { + box-shadow: 2px 2px 10px #ddd; +} + #contenedor_principal { height: auto; position: relative; From a5ad61f340ac851ca5dc5226132a29e50c1c2ed7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 18:35:35 +0100 Subject: [PATCH 139/249] discovery delete task Former-commit-id: 8809067053aa6bebfa61498afb2108aea352f3d7 --- .../wizards/DiscoveryTaskList.class.php | 73 ++++++++++++++++--- 1 file changed, 64 insertions(+), 9 deletions(-) diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index 0ad4af9683..5488b675b9 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -76,6 +76,13 @@ class DiscoveryTaskList extends Wizard { // Load styles. parent::run(); + + $delete = (bool) get_parameter('delete', false); + + if ($delete) { + return $this->deleteTask(); + } + return $this->showList(); } @@ -97,6 +104,41 @@ class DiscoveryTaskList extends Wizard } + /** + * Delete a recon task. + * + * @return void + */ + public function deleteTask() + { + global $config; + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access recon task viewer' + ); + include 'general/noaccess.php'; + return; + } + + $task = get_parameter('task', null); + + if ($task !== null) { + db_process_sql_delete( + 'trecon_task', + ['id_rt' => $task] + ); + } + + return [ + 'result' => 0, + 'msg' => __('Task successfully deleted'), + 'id' => false, + ]; + } + + /** * Show complete list of running tasks. * @@ -114,21 +156,21 @@ class DiscoveryTaskList extends Wizard 'Trying to access recon task viewer' ); include 'general/noaccess.php'; - return; + return false; } - // Get all recon servers + // Get all recon servers. $servers = db_get_all_rows_sql('SELECT * FROM tserver WHERE server_type = 3'); if ($servers === false) { $servers = []; ui_print_error_message(__('Discovery Server is disabled')); - return; + return false; } else { $recon_task = db_get_all_rows_sql('SELECT * FROM trecon_task'); if ($recon_task === false) { ui_print_page_header(__('Recon View'), 'images/op_recon.png', false, '', false); include_once $config['homedir'].'/general/firts_task/recon_view.php'; - return; + return false; } else { include_once $config['homedir'].'/include/functions_graph.php'; include_once $config['homedir'].'/include/functions_servers.php'; @@ -145,6 +187,11 @@ class DiscoveryTaskList extends Wizard if (isset($_GET['force'])) { $id = (int) get_parameter_get('force', 0); servers_force_recon_task($id); + header( + 'Location: '.ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist' + ) + ); } } @@ -153,7 +200,7 @@ class DiscoveryTaskList extends Wizard $server_name = servers_get_name($id_server); $recon_tasks = db_get_all_rows_field_filter('trecon_task', 'id_recon_server', $id_server); - // Show network tasks for Recon Server + // Show network tasks for Recon Server. if ($recon_tasks === false) { $recon_tasks = []; } @@ -195,14 +242,16 @@ class DiscoveryTaskList extends Wizard $table->head[7] = __('Updated at'); $table->align[7] = 'left'; - $table->head[8] = __('Edit'); + $table->head[8] = __('Operations'); $table->align[8] = 'left'; foreach ($recon_tasks as $task) { $data = []; if ($task['disabled'] == 0) { - $data[0] = ''; + $data[0] = ''; $data[0] .= html_print_image('images/target.png', true, ['title' => __('Force')]); $data[0] .= ''; } else { @@ -226,11 +275,11 @@ class DiscoveryTaskList extends Wizard } if ($task['id_recon_script'] == 0) { - // Network recon task + // Network recon task. $data[5] = html_print_image('images/network.png', true, ['title' => __('Network recon task')]).'  '; $data[5] .= network_profiles_get_name($task['id_network_profile']); } else { - // APP recon task + // APP recon task. $data[5] = html_print_image('images/plugin.png', true).'  '; $data[5] .= db_get_sql(sprintf('SELECT name FROM trecon_script WHERE id_recon_script = %d', $task['id_recon_script'])); } @@ -250,6 +299,12 @@ class DiscoveryTaskList extends Wizard 'images/wrench_orange.png', true ).''; + $data[8] .= ''.html_print_image( + 'images/cross.png', + true + ).''; } else { $data[8] = ''; } From 912f0baace3b3917fdf76dd7703078901f86de48 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 18:42:44 +0100 Subject: [PATCH 140/249] Discovery Tasks first tasks and some minor fixes Former-commit-id: 4a37dc99f1b1a95217e9be207526d750133a14a6 --- pandora_console/general/firts_task/recon_view.php | 10 +++++----- .../godmode/wizards/DiscoveryTaskList.class.php | 1 - 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/pandora_console/general/firts_task/recon_view.php b/pandora_console/general/firts_task/recon_view.php index 1d81c13e98..2377ce7c20 100755 --- a/pandora_console/general/firts_task/recon_view.php +++ b/pandora_console/general/firts_task/recon_view.php @@ -15,17 +15,17 @@ global $config; check_login(); ui_require_css_file('firts_task'); ?> - true, 'message' => __('There are no recon task defined yet.') ]); ?> + true, 'message' => __('There are no discovery tasks defined yet.') ]); ?>
    __('Discovery server')]); ?>
    -

    +

    ICMP (pings), SNMP (detecting the topology of networks and their interfaces), and other customized @@ -33,8 +33,8 @@ ui_require_css_file('firts_task'); ); ?>

    -
    - + +

    diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index 5488b675b9..d0c5da17fb 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -168,7 +168,6 @@ class DiscoveryTaskList extends Wizard } else { $recon_task = db_get_all_rows_sql('SELECT * FROM trecon_task'); if ($recon_task === false) { - ui_print_page_header(__('Recon View'), 'images/op_recon.png', false, '', false); include_once $config['homedir'].'/general/firts_task/recon_view.php'; return false; } else { From c49c8bc0b5d84ab2b61c05ee629fe15764d27a76 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 15 Feb 2019 18:44:59 +0100 Subject: [PATCH 141/249] discovery minor style changes Former-commit-id: ea572c9d797214cbfc6f1b9ff2025f0c4819b4ed --- pandora_console/include/styles/discovery.css | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css index df393fdf3e..930dbd047d 100644 --- a/pandora_console/include/styles/discovery.css +++ b/pandora_console/include/styles/discovery.css @@ -30,7 +30,6 @@ div.data_container { width: 100%; height: 100%; text-align: center; - border: 1px solid #ddd; padding-top: 30px; padding-bottom: 30px; } @@ -39,6 +38,9 @@ div.data_container:hover { box-shadow: 2px 2px 10px #ddd; } +/* + * TODO: This may be at hostdevices.css + */ #contenedor_principal { height: auto; position: relative; From 0d93ccc09437c429d1775ae7781b11f8aaaa6945 Mon Sep 17 00:00:00 2001 From: artica Date: Sat, 16 Feb 2019 00:01:31 +0100 Subject: [PATCH 142/249] Auto-updated build strings. Former-commit-id: 8789c127ad23a066317bd86d0bfe456dd4a3ec38 --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index c9e01190e9..b9d79cac74 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190215 +Version: 7.0NG.731-190216 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index f50b4ee8dc..ec6468c904 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190215" +pandora_version="7.0NG.731-190216" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 187f94b41d..f8ed0ee790 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190215'; +use constant AGENT_BUILD => '190216'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 16bf75ef2f..5054296122 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190215 +%define release 190216 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 1dd06bf43e..42bd97df7c 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190215 +%define release 190216 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index 340a0c2712..101a222475 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190215" +PI_BUILD="190216" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index b7dff2f2ec..bd1c2706f2 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190215} +{190216} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 48aba959cb..d9f92d20df 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190215)") +#define PANDORA_VERSION ("7.0NG.731(Build 190216)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 2b58063706..c5bc83348a 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190215))" + VALUE "ProductVersion", "(7.0NG.731(Build 190216))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 12ecde5daf..aad2a6c328 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190215 +Version: 7.0NG.731-190216 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 0171643ae5..1651ec67f0 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190215" +pandora_version="7.0NG.731-190216" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 4de1f20d2f..872d436a69 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190215'; +$build_version = 'PC190216'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index 5608de3f79..bbfe4ca5b5 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@
    [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index e0834c0d3a..0450a2345f 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190215 +%define release 190216 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 29a5c3e307..bd8c4ca077 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190215 +%define release 190216 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index 1b9483c5fe..ad5c1295df 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190215" +PI_BUILD="190216" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 97816668a5..9ca2593077 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190215"; +my $version = "7.0NG.731 PS190216"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 08854530dd..46bce81907 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190215"; +my $version = "7.0NG.731 PS190216"; # save program name for logging my $progname = basename($0); From 1fafda850208701b3945f3029d011a849d180c99 Mon Sep 17 00:00:00 2001 From: artica Date: Sun, 17 Feb 2019 00:01:24 +0100 Subject: [PATCH 143/249] Auto-updated build strings. Former-commit-id: affb7e6fc134d1ae80be0450f759a30960b177fd --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index b9d79cac74..6dab91eb16 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190216 +Version: 7.0NG.731-190217 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index ec6468c904..53f76fc068 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190216" +pandora_version="7.0NG.731-190217" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index f8ed0ee790..910d8eab00 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190216'; +use constant AGENT_BUILD => '190217'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 5054296122..2992e00140 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190216 +%define release 190217 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 42bd97df7c..9f05dacb7c 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190216 +%define release 190217 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index 101a222475..769adba62b 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190216" +PI_BUILD="190217" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index bd1c2706f2..c77bde62fc 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190216} +{190217} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index d9f92d20df..570420a6d4 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190216)") +#define PANDORA_VERSION ("7.0NG.731(Build 190217)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index c5bc83348a..44e384be4a 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190216))" + VALUE "ProductVersion", "(7.0NG.731(Build 190217))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index aad2a6c328..c602d5e124 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190216 +Version: 7.0NG.731-190217 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 1651ec67f0..447bfbcef9 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190216" +pandora_version="7.0NG.731-190217" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 872d436a69..107551dc3a 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190216'; +$build_version = 'PC190217'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index bbfe4ca5b5..ccb36a31ac 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@
    [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 0450a2345f..d4f9f0ff4e 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190216 +%define release 190217 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index bd8c4ca077..829e2d127c 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190216 +%define release 190217 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index ad5c1295df..439d1615d5 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190216" +PI_BUILD="190217" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 9ca2593077..061e3404d7 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190216"; +my $version = "7.0NG.731 PS190217"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 46bce81907..343f591067 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190216"; +my $version = "7.0NG.731 PS190217"; # save program name for logging my $progname = basename($0); From 0ef118f401bab29783aefb09245eb649fc013210 Mon Sep 17 00:00:00 2001 From: artica Date: Mon, 18 Feb 2019 00:01:24 +0100 Subject: [PATCH 144/249] Auto-updated build strings. Former-commit-id: 2e217d82f2119ffdca6218a233fa8eeb743c3fb0 --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 6dab91eb16..9e5ab2a275 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190217 +Version: 7.0NG.731-190218 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 53f76fc068..b292a5b27e 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190217" +pandora_version="7.0NG.731-190218" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 910d8eab00..e115ed1464 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190217'; +use constant AGENT_BUILD => '190218'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 2992e00140..09dda6c12c 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190217 +%define release 190218 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 9f05dacb7c..cfbcd4d9e2 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190217 +%define release 190218 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index 769adba62b..ea0776fa0b 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190217" +PI_BUILD="190218" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index c77bde62fc..6e9ed1ef35 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190217} +{190218} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 570420a6d4..e13c1aaaef 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190217)") +#define PANDORA_VERSION ("7.0NG.731(Build 190218)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 44e384be4a..ebc2597545 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190217))" + VALUE "ProductVersion", "(7.0NG.731(Build 190218))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index c602d5e124..3a35a79ccb 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190217 +Version: 7.0NG.731-190218 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 447bfbcef9..4e85297bc6 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190217" +pandora_version="7.0NG.731-190218" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 107551dc3a..040ea33307 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190217'; +$build_version = 'PC190218'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index ccb36a31ac..92b6dd1217 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@
    [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index d4f9f0ff4e..8e88f8c8e7 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190217 +%define release 190218 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 829e2d127c..4d51b35563 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190217 +%define release 190218 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index 439d1615d5..adde2139a0 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190217" +PI_BUILD="190218" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 061e3404d7..100e38cea1 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190217"; +my $version = "7.0NG.731 PS190218"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 343f591067..a19ae1e3ff 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190217"; +my $version = "7.0NG.731 PS190218"; # save program name for logging my $progname = basename($0); From a9caebbbf41f4dfcc6a38e7fc2a7e5093caf7f78 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Mon, 18 Feb 2019 10:24:19 +0100 Subject: [PATCH 145/249] Put the list into a function Former-commit-id: 11e4d0faa3512e46582530f48bab2cfa1031e89f --- pandora_console/godmode/servers/discovery.php | 18 ++------- .../godmode/wizards/Wizard.main.php | 40 +++++++++++++++++++ 2 files changed, 43 insertions(+), 15 deletions(-) diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 024eb39e30..97b9b8a884 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -76,24 +76,12 @@ if ($classname_selected !== null) { if ($classname_selected === null) { // Load classes and print selector. - echo '
      '; + $wiz_data = []; foreach ($classes as $classpath) { $classname = basename($classpath, '.class.php'); $obj = new $classname(); - $wiz_data = $obj->load(); - ?> - -
    • - -
      - -
      -
      -
      -
    • - - load(); } - echo '
    '; + Wizard::printBigButtonsList($wiz_data); } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index ecc253ad04..709e601fa5 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -467,4 +467,44 @@ class Wizard } + /** + * Print a big button element (huge image, big text and link). + * + * @param array $data Element data (link, image...). + * + * @return void Only prints the element. + */ + public static function printBigButtonElement($data) + { + if (isset($data['url']) === false) { + $data['url'] = '#'; + } + + ?> +
  • + +
    + +
    +
    +
    +
  • + '; + array_map('self::printBigButtonElement', $list_data); + echo ''; + } } From 29206eb3bbd2b9bd10e0dc9570cf1dabde797923 Mon Sep 17 00:00:00 2001 From: manuel Date: Mon, 18 Feb 2019 11:42:55 +0100 Subject: [PATCH 146/249] Added visual changes Former-commit-id: 33ac4873763e6b0e2cf3d2ad2b25492fe5b33583 --- .../godmode/wizards/HostDevices.class.php | 32 ++++++++----------- pandora_console/images/wizard/hostdevices.svg | 4 +-- pandora_console/images/wizard/tasklist.svg | 5 ++- 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 633fbfe19f..54fdeb0716 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -94,24 +94,20 @@ class HostDevices extends Wizard if ($mode === null) { $this->setBreadcrum(['Host&devices']); $this->printHeader(); - echo '
    '; - echo '
    '; - echo '
    '; - echo 'importcsv'; - echo '
    '; - echo '
    '; - echo ''.__('Import CSV').''; - echo '
    '; - echo '
    '; - echo '
    '; - echo '
    '; - echo 'importcsv'; - echo '
    '; - echo '
    '; - echo ''.__('Escanear red').''; - echo '
    '; - echo '
    '; - echo '
    '; + $this->printBigButtonsList( + [ + [ + 'url' => $this->url.'&mode=importcsv', + 'icon' => 'images/wizard/csv_image.svg', + 'label' => __('Import CSV'), + ], + [ + 'url' => $this->url.'&mode=netscan', + 'icon' => 'images/wizard/csv_image.svg', + 'label' => __('Net Scan'), + ], + ] + ); return; } diff --git a/pandora_console/images/wizard/hostdevices.svg b/pandora_console/images/wizard/hostdevices.svg index 1e82511472..3add7ea833 100644 --- a/pandora_console/images/wizard/hostdevices.svg +++ b/pandora_console/images/wizard/hostdevices.svg @@ -1,4 +1,4 @@ - - + + diff --git a/pandora_console/images/wizard/tasklist.svg b/pandora_console/images/wizard/tasklist.svg index 1e82511472..bac9f75f6f 100644 --- a/pandora_console/images/wizard/tasklist.svg +++ b/pandora_console/images/wizard/tasklist.svg @@ -1,4 +1,3 @@ - - - + + From a1a429aa5275081ba230fb027f508641ef5be098 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 18 Feb 2019 12:14:03 +0100 Subject: [PATCH 147/249] H&D minor fixes and acl checks Former-commit-id: cec9ec899e648ab6e76716333c8ee09ca875023a --- .../godmode/wizards/HostDevices.class.php | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 54fdeb0716..07f8e1ee7b 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -439,9 +439,6 @@ class HostDevices extends Wizard return; } - $user_groups = users_get_groups(false, 'AW', true, false, null, 'id_grupo'); - $user_groups = array_keys($user_groups); - if ($this->parseNetScan() === false) { // Error. ui_print_error_message( @@ -473,6 +470,17 @@ class HostDevices extends Wizard ], ]; + // Check ACL. If user is not able to manage target task, + // redirect him to main page. + if (users_is_admin() || check_acl( + $config['id_usuario'], + $this->task['id_group'], + 'PM' + ) !== true + ) { + $form['form']['action'] = $this->url.'&mode=netscan&page='.($this->page - 1); + } + $this->printForm($form); return null; } @@ -954,6 +962,7 @@ function SNMPExtraShow(target) { $("#snmp_options_basic").hide(); $("#snmp_options_v3").hide(); if (document.getElementsByName("snmp_enabled")[0].checked) { + $("#snmp_extra").show(); if (target == 3) { $("#snmp_options_v3").show(); } else { From efd65edefa2ec9623e9b4b5a28af99c931fba839 Mon Sep 17 00:00:00 2001 From: daniel Date: Mon, 18 Feb 2019 13:13:17 +0100 Subject: [PATCH 148/249] fixed errors Former-commit-id: dc70e23da17691f3af6602cd85e2f01b27d27d58 --- .../reporting_builder.item_editor.php | 1 + .../godmode/reporting/reporting_builder.php | 14 ++- .../include/functions_reporting.php | 2 - .../include/functions_reporting_html.php | 109 ++++++++++++++---- 4 files changed, 100 insertions(+), 26 deletions(-) diff --git a/pandora_console/godmode/reporting/reporting_builder.item_editor.php b/pandora_console/godmode/reporting/reporting_builder.item_editor.php index 38584d6b6a..c274ce7b30 100755 --- a/pandora_console/godmode/reporting/reporting_builder.item_editor.php +++ b/pandora_console/godmode/reporting/reporting_builder.item_editor.php @@ -202,6 +202,7 @@ switch ($action) { switch ($type) { case 'event_report_log': + hd('entra', true); $period = $item['period']; $description = $item['description']; diff --git a/pandora_console/godmode/reporting/reporting_builder.php b/pandora_console/godmode/reporting/reporting_builder.php index abab21b8fe..fa3e720a00 100755 --- a/pandora_console/godmode/reporting/reporting_builder.php +++ b/pandora_console/godmode/reporting/reporting_builder.php @@ -1116,8 +1116,13 @@ switch ($action) { $name_it = (string) get_parameter('name'); $values['name'] = reporting_label_macro($items_label, $name_it); - // Added support for projection graphs, prediction date and SLA reports - // 'top_n_value','top_n' and 'text' fields will be reused for these types of report + /* + Added support for projection graphs, + prediction date and SLA reports + 'top_n_value','top_n' and 'text' + fields will be reused for these types of report + */ + switch ($values['type']) { case 'projection_graph': $values['period'] = get_parameter('period1'); @@ -1127,7 +1132,8 @@ switch ($action) { break; case 'event_report_log': - $agents_to_report = get_parameter('id_agents2'); + + $agents_to_report = get_parameter('id_agents3'); $source = get_parameter('source', ''); $search = get_parameter('search', ''); $log_number = get_parameter('log_number', ''); @@ -1525,7 +1531,7 @@ switch ($action) { break; case 'event_report_log': - $agents_to_report = get_parameter('id_agents2'); + $agents_to_report = get_parameter('id_agents3'); $source = get_parameter('source', ''); $search = get_parameter('search', ''); $log_number = get_parameter('log_number', ''); diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index 1aa9ecf618..1581119772 100755 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -142,7 +142,6 @@ function reporting_make_reporting_data( enterprise_include_once('include/functions_metaconsole.php'); $return = []; - if (!empty($report)) { $contents = $report['contents']; } else { @@ -6792,7 +6791,6 @@ function reporting_general($report, $content) if (!is_numeric($data_res[$index])) { $return['data'][$ag_name][$mod_name] = $data_res[$index]; } else { - hd($data_res[$index], true); $return['data'][$ag_name][$mod_name] = format_for_graph($data_res[$index], 2).' '.$unit; } } diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index b882cc0ae0..362120e0a1 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -1322,15 +1322,29 @@ function reporting_html_event_report_module($table, $item, $pdf=0) } -function reporting_html_inventory_changes($table, $item) +/** + * Print in html inventory changes reports + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf Print pdf true or false. + * + * @return html + */ +function reporting_html_inventory_changes($table, $item, $pdf=0) { + $return_pdf = ''; if (!empty($item['failed'])) { - $table->colspan['failed']['cell'] = 3; - $table->cellstyle['failed']['cell'] = 'text-align: center;'; - $table->data['failed']['cell'] = $item['failed']; + if ($pdf === 0) { + $table->colspan['failed']['cell'] = 3; + $table->cellstyle['failed']['cell'] = 'text-align: center;'; + $table->data['failed']['cell'] = $item['failed']; + } else { + $return_pdf .= $item['failed']; + } } else { foreach ($item['data'] as $module_item) { - $table1 = null; + $table1 = new stdClass(); $table1->width = '99%'; $table1->cellstyle = []; @@ -1348,7 +1362,10 @@ function reporting_html_inventory_changes($table, $item) $table1->colspan[2][0] = 2; if (count($module_item['added'])) { - $table1->data = array_merge($table1->data, $module_item['added']); + $table1->data = array_merge( + $table1->data, + $module_item['added'] + ); } $table1->cellstyle[(3 + count($module_item['added']))][0] = 'background: #373737; color: #FFF; text-align: center;'; @@ -1356,25 +1373,59 @@ function reporting_html_inventory_changes($table, $item) $table1->colspan[(3 + count($module_item['added']))][0] = 2; if (count($module_item['deleted'])) { - $table1->data = array_merge($table1->data, $module_item['deleted']); + $table1->data = array_merge( + $table1->data, + $module_item['deleted'] + ); } - $table->colspan[$module_item['agent'].'_'.$module_item['module']]['cell'] = 3; - $table->data[$module_item['agent'].'_'.$module_item['module']]['cell'] = html_print_table($table1, true); + if ($pdf === 0) { + $table->colspan[$module_item['agent'].'_'.$module_item['module']]['cell'] = 3; + $table->data[$module_item['agent'].'_'.$module_item['module']]['cell'] = html_print_table( + $table1, + true + ); + } else { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table( + $table1, + true + ); + } } } + + if ($pdf !== 0) { + return $return_pdf; + } } -function reporting_html_inventory($table, $item) +/** + * Print in html inventory reportd + * + * @param object $table Head table or false if it comes from pdf. + * @param array $item Items data. + * @param boolean $pdf Print pdf true or false. + * + * @return html + */ +function reporting_html_inventory($table, $item, $pdf=0) { + $return_pdf = ''; if (!empty($item['failed'])) { - $table->colspan['failed']['cell'] = 3; - $table->cellstyle['failed']['cell'] = 'text-align: center;'; - $table->data['failed']['cell'] = $item['failed']; + if ($pdf === 0) { + $table->colspan['failed']['cell'] = 3; + $table->cellstyle['failed']['cell'] = 'text-align: center;'; + $table->data['failed']['cell'] = $item['failed']; + } else { + $return_pdf .= $item['failed']; + } } else { foreach ($item['data'] as $module_item) { - $table1 = null; + $table1 = new stdClass(); $table1->width = '99%'; $first = reset($module_item['data']); @@ -1384,12 +1435,12 @@ function reporting_html_inventory($table, $item) $table1->data[0][0] = $module_item['agent_name']; if ($count_columns == 1) { $table1->colspan[0][0] = ($count_columns + 1); - // + columm date } else { $table1->colspan[0][0] = $count_columns; } - $table1->cellstyle[1][0] = $table1->cellstyle[1][1] = 'background: #373737; color: #FFF;'; + $table1->cellstyle[1][0] = 'background: #373737; color: #FFF;'; + $table1->cellstyle[1][1] = 'background: #373737; color: #FFF;'; $table1->data[1][0] = $module_item['name']; if (($count_columns - 1) > 0) { $table1->colspan[1][0] = ($count_columns - 1); @@ -1405,16 +1456,34 @@ function reporting_html_inventory($table, $item) $table1->data[2] = array_keys($first); if (($count_columns - 1) == 0) { $table1->colspan[2][0] = ($count_columns + 1); - // + columm date; } - $table1->data = array_merge($table1->data, $module_item['data']); + $table1->data = array_merge( + $table1->data, + $module_item['data'] + ); - $table->colspan[$module_item['name'].'_'.$module_item['id_agente']]['cell'] = 3; - $table->data[$module_item['name'].'_'.$module_item['id_agente']]['cell'] = html_print_table($table1, true); + if ($pdf === 0) { + $table->colspan[$module_item['name'].'_'.$module_item['id_agente']]['cell'] = 3; + $table->data[$module_item['name'].'_'.$module_item['id_agente']]['cell'] = html_print_table( + $table1, + true + ); + } else { + $table1->title = $item['title']; + $table1->titleclass = 'title_table_pdf'; + $table1->titlestyle = 'text-align:left;'; + $return_pdf .= html_print_table( + $table1, + true + ); + } } } + if ($pdf !== 0) { + return $return_pdf; + } } From 5816320effe68eb3ba1ccdeb7913439e712da461 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 18 Feb 2019 14:00:38 +0100 Subject: [PATCH 149/249] new token. autoconfiguration_enabled. discovery tasks Former-commit-id: d19c86696b73335b6977d11d5ea683131780097e --- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 1 + pandora_console/pandoradb.sql | 1 + 2 files changed, 2 insertions(+) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 6140297ef8..c86c9bf7d6 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1408,6 +1408,7 @@ ALTER TABLE trecon_task ADD `snmp_enabled` int(2) unsigned default '0'; ALTER TABLE trecon_task ADD `vlan_enabled` int(2) unsigned default '0'; ALTER TABLE trecon_task ADD `wmi_enabled` tinyint(1) unsigned DEFAULT '0'; ALTER TABLE trecon_task ADD `auth_strings` text; +ALTER TABLE trecon_task ADD `autoconfiguration_enabled` tinyint(1) unsigned default '0'; -- --------------------------------------------------------------------- -- Table `twidget` AND Table `twidget_dashboard` diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index 4271269fd7..ae780a5470 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -784,6 +784,7 @@ CREATE TABLE IF NOT EXISTS `trecon_task` ( `snmp_security_level` varchar(25) NOT NULL default '', `wmi_enabled` tinyint(1) unsigned DEFAULT '0', `auth_strings` text, + `autoconfiguration_enabled` tinyint(1) unsigned default '0', PRIMARY KEY (`id_rt`), KEY `recon_task_daemon` (`id_recon_server`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; From 46af41a2cc3663e26258fb867a993c5ad058de7a Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 18 Feb 2019 14:00:55 +0100 Subject: [PATCH 150/249] support for autoconfiguration Former-commit-id: 034ed513ed9cf7efbe22720b61e8ff431ebbbc84 --- .../godmode/wizards/HostDevices.class.php | 263 +++++++----------- .../lib/PandoraFMS/DiscoveryServer.pm | 9 + pandora_server/lib/PandoraFMS/Recon/Base.pm | 1 + 3 files changed, 103 insertions(+), 170 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 07f8e1ee7b..c537ae3c8d 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -109,6 +109,7 @@ class HostDevices extends Wizard ] ); + $this->printGoBackButton(); return; } @@ -202,6 +203,7 @@ class HostDevices extends Wizard $server_id = get_parameter('id_recon_server', ''); $network = get_parameter('network', ''); $id_group = get_parameter('id_group', ''); + $interval = get_parameter('interval', 0); if (isset($task_id) === true) { // We're updating this task. @@ -265,6 +267,7 @@ class HostDevices extends Wizard $this->task['subnet'] = $network; $this->task['id_recon_server'] = $server_id; $this->task['id_group'] = $id_group; + $this->task['interval_sweep'] = $interval; if (isset($this->task['id_rt']) === false) { // Create. @@ -343,42 +346,6 @@ class HostDevices extends Wizard $this->task['snmp_security_level'] = $snmp_security_level; $this->task['auth_strings'] = $auth_strings; - // Update. - $res = db_process_sql_update( - 'trecon_task', - $this->task, - ['id_rt' => $this->task['id_rt']] - ); - - return true; - } - - if ($this->page == 3) { - // Interval and schedules. - // By default manual if not defined. - $id_rt = get_parameter('task', -1); - - $task = db_get_row( - 'trecon_task', - 'id_rt', - $id_rt - ); - - if ($task !== false) { - $this->task = $task; - } else { - $this->msg = __('Failed to find network scan task.'); - return false; - } - - $interval = get_parameter('interval', 0); - $id_os = get_parameter('id_os', 0); - $recon_ports = get_parameter('recon_ports', ''); - - $this->task['id_os'] = $id_os; - $this->task['interval_sweep'] = $interval; - $this->task['recon_ports'] = $recon_ports; - if ($this->task['disabled'] == 2) { // Wizard finished. $this->task['disabled'] = 0; @@ -394,7 +361,7 @@ class HostDevices extends Wizard return true; } - if ($this->page == 4) { + if ($this->page == 3) { // Wizard ended. Load data and return control to Discovery. $id_rt = get_parameter('task', -1); @@ -472,7 +439,7 @@ class HostDevices extends Wizard // Check ACL. If user is not able to manage target task, // redirect him to main page. - if (users_is_admin() || check_acl( + if (users_is_admin() !== true && check_acl( $config['id_usuario'], $this->task['id_group'], 'PM' @@ -485,7 +452,7 @@ class HostDevices extends Wizard return null; } - if (isset($this->page) + if (isset($this->page) === true && $this->page != 0 && isset($this->task['id_rt']) === false ) { @@ -526,7 +493,7 @@ class HostDevices extends Wizard // -------------------------------. // Page 0. wizard starts HERE. // -------------------------------. - if (!isset($this->page) || $this->page == 0) { + if (isset($this->page) === true || $this->page == 0) { if (isset($this->page) === false || $this->page == 0 ) { @@ -614,6 +581,44 @@ class HostDevices extends Wizard ], ]; + // Interval and schedules. + $interv_manual = 0; + if ((int) $this->task['interval_sweep'] == 0) { + $interv_manual = 1; + } + + // Schedule. + $form['inputs'][] = [ + 'label' => ''.__('Interval').''.ui_print_help_tip( + __('Manual interval means that it will be executed only On-demand'), + true + ), + 'arguments' => [ + 'type' => 'select', + 'selected' => $interv_manual, + 'fields' => [ + 0 => __('Defined'), + 1 => __('Manual'), + ], + 'name' => 'interval_manual_defined', + 'return' => true, + ], + 'extra' => ''.html_print_extended_select_for_time( + 'interval', + $this->task['interval_sweep'], + '', + '', + '0', + false, + true, + false, + false + ).ui_print_help_tip( + __('The minimum recomended interval for Recon Task is 5 minutes'), + true + ).'', + ]; + $str = __('Next'); if (isset($this->task['id_rt']) === true) { @@ -641,6 +646,21 @@ class HostDevices extends Wizard 'action' => $this->url.'&mode=netscan&page='.($this->page + 1).$task_url, ]; + $form['js'] = ' +$("select#interval_manual_defined").change(function() { + if ($("#interval_manual_defined").val() == 1) { + $("#interval_manual_container").hide(); + $("#text-interval_text").val(0); + $("#hidden-interval").val(0); + } + else { + $("#interval_manual_container").show(); + $("#text-interval_text").val(10); + $("#hidden-interval").val(600); + $("#interval_units").val(60); + } +}).change();'; + // XXX: Could be improved validating inputs before continue (JS) // Print NetScan page 0. $this->printForm($form); @@ -679,17 +699,38 @@ class HostDevices extends Wizard $form['inputs'][] = [ 'label' => __('Module template'), 'arguments' => [ - 'name' => 'id_network_profile', - 'type' => 'select_from_sql', - 'sql' => 'SELECT id_np, name + 'name' => 'id_network_profile', + 'type' => 'select_from_sql', + 'sql' => 'SELECT id_np, name FROM tnetwork_profile ORDER BY name', - 'return' => true, - 'selected' => $this->task['id_network_profile'], + 'return' => true, + 'selected' => $this->task['id_network_profile'], + 'nothing_value' => 0, + 'nothing' => __('None'), ], ]; + if (enterprise_installed() === true) { + // Input: Enable auto configuration. + $form['inputs'][] = [ + 'label' => __('Apply autoconfiguration rules').ui_print_help_tip( + __( + 'System is able to auto configure detected host & devices by applying your defined configuration rules.' + ), + true + ), + 'arguments' => [ + 'name' => 'autoconfiguration_enabled', + 'type' => 'switch', + 'return' => true, + 'value' => (isset($this->task['autoconfiguration_enabled'])) ? $this->task['autoconfiguration_enabled'] : 0, + + ], + ]; + } + // Feature configuration. // Input: SNMP enabled. $form['inputs'][] = [ @@ -879,7 +920,12 @@ class HostDevices extends Wizard 'hidden' => 1, 'block_content' => [ [ - 'label' => __('WMI Auth. strings'), + 'label' => ''.__('WMI Auth. strings').''.ui_print_help_tip( + __( + 'Auth strings must be defined as user%pass, comma separated as many you need.' + ), + true + ), 'arguments' => [ 'name' => 'auth_strings', 'type' => 'text', @@ -950,7 +996,7 @@ class HostDevices extends Wizard $form['inputs'][] = [ 'arguments' => [ 'name' => 'submit', - 'label' => __('Next'), + 'label' => __('Finish'), 'type' => 'submit', 'attributes' => 'class="sub next"', 'return' => true, @@ -1017,129 +1063,6 @@ $(function() { } if ($this->page == 2) { - // Interval and schedules. - $interv_manual = 0; - if ((int) $this->task['interval_sweep'] == 0) { - $interv_manual = 1; - } - - // Filter: OS. - $form['inputs'][] = [ - 'label' => ''.__('Filter by OS').'', - 'arguments' => [ - 'type' => 'select_from_sql', - 'sql' => 'SELECT id_os, name - FROM tconfig_os - ORDER BY name', - 'name' => 'id_os', - 'return' => 'true', - 'nothing' => __('Any'), - 'selected' => $this->task['id_os'], - ], - ]; - - // Filter: Ports. - $form['inputs'][] = [ - 'label' => ''.__('Filter by ports').''.ui_print_help_tip( - __('Ports defined like: 80 or 80,443,512 or even 0-1024 (Like Nmap command line format). If dont want to do a sweep using portscan, left it in blank'), - true - ), - 'arguments' => [ - 'type' => 'text', - 'name' => 'recon_ports', - 'return' => 'true', - 'recon_ports' => $this->task['recon_ports'], - ], - ]; - - // Schedule. - $form['inputs'][] = [ - 'label' => ''.__('Interval').''.ui_print_help_tip( - __('Manual interval means that it will be executed only On-demand'), - true - ), - 'arguments' => [ - 'type' => 'select', - 'selected' => $interv_manual, - 'fields' => [ - 0 => __('Defined'), - 1 => __('Manual'), - ], - 'name' => 'interval_manual_defined', - 'return' => true, - ], - 'extra' => ''.html_print_extended_select_for_time( - 'interval', - $this->task['interval_sweep'], - '', - '', - '0', - false, - true, - false, - false - ).ui_print_help_tip( - __('The minimum recomended interval for Recon Task is 5 minutes'), - true - ).'', - ]; - - // Hidden, id_rt. - $form['inputs'][] = [ - 'arguments' => [ - 'name' => 'task', - 'value' => $this->task['id_rt'], - 'type' => 'hidden', - 'return' => true, - ], - ]; - - // Hidden, page. - $form['inputs'][] = [ - 'arguments' => [ - 'name' => 'page', - 'value' => ($this->page + 1), - 'type' => 'hidden', - 'return' => true, - ], - ]; - - // Submit button. - $form['inputs'][] = [ - 'arguments' => [ - 'name' => 'submit', - 'label' => __('Next'), - 'type' => 'submit', - 'attributes' => 'class="sub next"', - 'return' => true, - ], - ]; - - $form['form'] = [ - 'method' => 'POST', - 'action' => $this->url.'&mode=netscan&page='.($this->page + 1).'&task='.$this->task['id_rt'], - ]; - - $form['js'] = ' -$("select#interval_manual_defined").change(function() { - if ($("#interval_manual_defined").val() == 1) { - $("#interval_manual_container").hide(); - $("#text-interval_text").val(0); - $("#hidden-interval").val(0); - } - else { - $("#interval_manual_container").show(); - $("#text-interval_text").val(10); - $("#hidden-interval").val(600); - $("#interval_units").val(60); - } -}).change();'; - - $this->printForm($form); - return null; - } - - if ($this->page == 3) { if ($this->task['id_rt']) { // 0 - Is OK. $this->result = 0; diff --git a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm index 7b6fa7c0ea..b6423a8506 100644 --- a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -190,6 +190,7 @@ sub data_consumer ($$) { vlan_cache_enabled => $task->{'vlan_enabled'}, wmi_enabled => $task->{'wmi_enabled'}, auth_strings_array => \@auth_strings, + autoconfigure_agent => $task->{'autoconfiguration_enabled'} %{$pa_config} ); @@ -445,6 +446,14 @@ sub PandoraFMS::Recon::Base::create_agent($$) { $location->{'longitude'}, $location->{'latitude'} ); return undef unless defined ($agent_id) and ($agent_id > 0); + + # Autoconfigure agent + if (defined($self->{'autoconfiguration_enabled'}) && $self->{'autoconfiguration_enabled'} == 1) { + my $agent_data = PandoraFMS::DB::get_db_single_row($self->{'dbh'}, 'SELECT * FROM tagente WHERE id_agente = ?', $agent_id); + # Update agent configuration once, after create agent. + enterprise_hook('autoconfigure_agent', [$self->{'pa_config'}, $host_name, $agent_id, $agent_data, $self->{'dbh'}]); + } + pandora_event($self->{'pa_config'}, "[RECON] New " . safe_output($self->get_device_type($device)) . " found (" . join(',', safe_output($self->get_addresses($device))) . ").", $self->{'group_id'}, $agent_id, 2, 0, 0, 'recon_host_detected', 0, $self->{'dbh'}); $agent_learning = 1; diff --git a/pandora_server/lib/PandoraFMS/Recon/Base.pm b/pandora_server/lib/PandoraFMS/Recon/Base.pm index e819b06476..ec3eb0d853 100644 --- a/pandora_server/lib/PandoraFMS/Recon/Base.pm +++ b/pandora_server/lib/PandoraFMS/Recon/Base.pm @@ -166,6 +166,7 @@ sub new { snmp_timeout => 2, snmp_version => 1, subnets => [], + autoconfiguration_enabled => 0, @_, }; From 34cf0bd837e3e1758a0cfc467de4be1827262ccf Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 18 Feb 2019 14:01:17 +0100 Subject: [PATCH 151/249] minor fix acl check in notifications Former-commit-id: 3ee0004f0c8ab507ed2301b77117ca945fb4e826 --- pandora_console/godmode/setup/setup_notifications.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/pandora_console/godmode/setup/setup_notifications.php b/pandora_console/godmode/setup/setup_notifications.php index 14a29c4bb2..28c336aa92 100644 --- a/pandora_console/godmode/setup/setup_notifications.php +++ b/pandora_console/godmode/setup/setup_notifications.php @@ -32,12 +32,6 @@ require_once $config['homedir'].'/include/functions_notifications.php'; check_login(); -if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { - db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); - include 'general/noaccess.php'; - return; -} - // AJAX actions. $source = get_parameter('source', ''); $users = get_parameter('users', ''); From 7b2e0342c1c8a95e79bedd092d1737ef17dab92c Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 18 Feb 2019 14:18:58 +0100 Subject: [PATCH 152/249] Fix. notification did not reach ALL target Former-commit-id: 237e5dac34bcbe50453e0b56f0964a9d74aa7c04 --- pandora_console/include/functions_messages.php | 4 ++-- pandora_console/include/functions_notifications.php | 2 +- pandora_console/operation/messages/message_edit.php | 7 ++++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/pandora_console/include/functions_messages.php b/pandora_console/include/functions_messages.php index f633866f65..a67bcb56e1 100644 --- a/pandora_console/include/functions_messages.php +++ b/pandora_console/include/functions_messages.php @@ -384,7 +384,7 @@ function messages_get_count( AND up.id_grupo=ng.id_group ) ON tm.id_mensaje=ng.id_mensaje WHERE utimestamp_erased is null - AND (nu.id_user="%s" OR (up.id_usuario="%s" AND ng.id_group=0)) + AND (nu.id_user="%s" OR up.id_usuario="%s" OR ng.id_group=0) ) t %s', $source_sql, @@ -496,7 +496,7 @@ function messages_get_overview( ) ON tm.id_mensaje=ng.id_mensaje %s WHERE utimestamp_erased is null - AND (nu.id_user="%s" OR (up.id_usuario="%s" AND ng.id_group=0)) + AND (nu.id_user="%s" OR up.id_usuario="%s" OR ng.id_group=0) ) t %s %s diff --git a/pandora_console/include/functions_notifications.php b/pandora_console/include/functions_notifications.php index 0e35b7ea37..23b1a90e70 100644 --- a/pandora_console/include/functions_notifications.php +++ b/pandora_console/include/functions_notifications.php @@ -145,7 +145,7 @@ function check_notification_readable(int $id_message) AND up.id_grupo=ng.id_group ) ON tm.id_mensaje=ng.id_mensaje WHERE utimestamp_erased is null - AND (nu.id_user="%s" OR (up.id_usuario="%s" AND ng.id_group=0))', + AND (nu.id_user="%s" OR up.id_usuario="%s" OR ng.id_group=0)', $config['id_user'], $id_message, $config['id_user'], diff --git a/pandora_console/operation/messages/message_edit.php b/pandora_console/operation/messages/message_edit.php index 6c100d7c00..f116e6609d 100644 --- a/pandora_console/operation/messages/message_edit.php +++ b/pandora_console/operation/messages/message_edit.php @@ -106,7 +106,12 @@ if ($read_message) { $dst_name = $message['id_usuario_destino']; } - echo '

    Conversation with '.$user_name.'

    '; + if (isset($user_name) !== true || empty($user_name) === true) { + echo '

    Notification

    '; + } else { + echo '

    Conversation with '.$user_name.'

    '; + } + echo '

    Subject: '.$message['subject'].'

    '; $conversation = []; From cb94692491b1d0100ce3dbe6e89170a08955d142 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Mon, 18 Feb 2019 14:30:03 +0100 Subject: [PATCH 153/249] Added function addBreadcrum in Wizard main Former-commit-id: ac40c2fd49ff02a84dc6752c4ea99309a3d4440f --- pandora_console/godmode/servers/discovery.php | 10 + .../godmode/wizards/Cloud.class.php | 267 ------------------ .../godmode/wizards/Wizard.main.php | 18 ++ 3 files changed, 28 insertions(+), 267 deletions(-) delete mode 100755 pandora_console/godmode/wizards/Cloud.class.php diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 235ae01e78..489293c862 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -49,6 +49,16 @@ function get_wiz_class($str) // Dynamic class loader. $classes = glob($config['homedir'].'/godmode/wizards/*.class.php'); +if (enterprise_installed()) { + $ent_classes = glob( + $config['homedir'].'/enterprise/godmode/wizards/*.class.php' + ); + if ($ent_classes === false) { + $ent_classes = []; + } + $classes = array_merge($classes, $ent_classes); +} + foreach ($classes as $classpath) { include_once $classpath; } diff --git a/pandora_console/godmode/wizards/Cloud.class.php b/pandora_console/godmode/wizards/Cloud.class.php deleted file mode 100755 index 1de88c2ca7..0000000000 --- a/pandora_console/godmode/wizards/Cloud.class.php +++ /dev/null @@ -1,267 +0,0 @@ -setBreadcrum([]); - - $this->task = []; - $this->msg = $msg; - $this->icon = $icon; - $this->label = $label; - $this->page = $page; - $this->url = ui_get_full_url( - 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=cloud' - ); - - return $this; - } - - - /** - * Run AmazonWS class. Entry point. - * - * @return void - */ - public function run() - { - global $config; - - // Load styles. - parent::run(); - - $mode = get_parameter('mode', null); - - if ($mode === null) { - $this->setBreadcrum(['Cloud']); - $this->printHeader(); - - echo 'Amazon WS'; - - return; - } - - if ($mode == 'amazonws') { - $this->setBreadcrum( - [ - 'Cloud', - 'Amazon AWS', - ] - ); - $this->printHeader(); - return $this->runAmazonAWS(); - } - - return null; - } - - - /** - * Checks if environment is ready, - * returns array - * icon: icon to be displayed - * label: label to be displayed - * - * @return array With data. - **/ - public function load() - { - return [ - 'icon' => $this->icon, - 'label' => $this->label, - 'url' => $this->url, - ]; - } - - - // ///////////////////////////////////////////////////////////////////////// - // Extra methods. - // ///////////////////////////////////////////////////////////////////////// - - - /** - * Amazon AWS pages manager. - * - * @return void - */ - public function runAmazonAWS() - { - global $config; - - check_login(); - - if (! check_acl($config['id_user'], 0, 'PM')) { - db_pandora_audit( - 'ACL Violation', - 'Trying to access Agent Management' - ); - include 'general/noaccess.php'; - return; - } - - // -------------------------------. - // Page 0. wizard starts HERE. - // -------------------------------. - if (!isset($this->page) || $this->page == 0) { - if (isset($this->page) === false - || $this->page == 0 - ) { - $this->printForm( - [ - 'form' => [ - 'action' => '#', - 'method' => 'POST', - ], - 'inputs' => [ - [ - 'label' => __('AWS access key ID'), - 'arguments' => [ - 'name' => 'aws_id', - 'value' => '', - 'type' => 'text', - ], - ], - [ - 'label' => __('AWS secret access key'), - 'arguments' => [ - 'name' => 'aws_id', - 'value' => '', - 'type' => 'text', - ], - ], - [ - 'arguments' => [ - 'name' => 'page', - 'value' => ($this->page + 1), - 'type' => 'hidden', - 'return' => true, - ], - ], - [ - 'arguments' => [ - 'name' => 'submit', - 'label' => __('Validate'), - 'type' => 'submit', - 'attributes' => 'class="sub wand"', - 'return' => true, - ], - ], - ], - ] - ); - } - } - - if ($this->page == 1) { - echo 'TODO'; - // TODOS. - } - - if ($this->page == 100) { - return [ - 'result' => $this->result, - 'id' => $this->id, - 'msg' => $this->msg, - ]; - } - } - - -} diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 709e601fa5..288a32fc47 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -78,6 +78,22 @@ class Wizard { return $this->breadcrum; } + + + /** + * Add an element to breadcrum array. + * + * @param string $string Element to add to breadcrum. + * + * @return void + */ + protected function addBreadcrum($string) { + if (empty($string)) { + return; + } + + array_push($this->breadcrum, $string); + } /** @@ -507,4 +523,6 @@ class Wizard array_map('self::printBigButtonElement', $list_data); echo ''; } + + } From 27602d8e49500cd7694f43c6be5b5775073dc61e Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 18 Feb 2019 15:14:24 +0100 Subject: [PATCH 154/249] Recovered notification editor for user Former-commit-id: a4fbf05912c974ab388cde9e9237022f2bcc3277 --- pandora_console/operation/users/user_edit.php | 49 ++----------------- 1 file changed, 3 insertions(+), 46 deletions(-) diff --git a/pandora_console/operation/users/user_edit.php b/pandora_console/operation/users/user_edit.php index 1552f2f57c..0449902172 100644 --- a/pandora_console/operation/users/user_edit.php +++ b/pandora_console/operation/users/user_edit.php @@ -14,51 +14,8 @@ // Load global vars global $config; -check_login(); - -enterprise_hook('open_meta_frame'); - -require_once $config['homedir'].'/include/functions_profile.php'; -require_once $config['homedir'].'/include/functions_users.php'; -require_once $config['homedir'].'/include/functions_groups.php'; -require_once $config['homedir'].'/include/functions_visual_map.php'; - -$meta = false; -if (enterprise_installed() && defined('METACONSOLE')) { - $meta = true; -} - -$id = get_parameter_get('id', $config['id_user']); -// ID given as parameter -$status = get_parameter('status', -1); -// Flag to print action status message -$user_info = get_user_info($id); -$id = $user_info['id_user']; -// This is done in case there are problems with uppercase/lowercase (MySQL auth has that problem) -if ((!check_acl($config['id_user'], users_get_groups($id), 'UM')) - and ($id != $config['id_user']) -) { - db_pandora_audit('ACL Violation', 'Trying to view a user without privileges'); - include 'general/noaccess.php'; - exit; -} - -// If current user is editing himself or if the user has UM (User Management) rights on any groups the user is part of AND the authorization scheme allows for users/admins to update info -if (($config['id_user'] == $id || check_acl($config['id_user'], users_get_groups($id), 'UM')) && $config['user_can_update_info']) { - $view_mode = false; -} else { - $view_mode = true; -} - -// Header -if ($meta) { - user_meta_print_header(); - $url = 'index.php?sec=advanced&sec2=advanced/users_setup&tab=user_edit'; -} else { - ui_print_page_header(__('User detail editor'), 'images/op_workspace.png', false, '', false, ''); - $url = 'index.php?sec=workspace&sec2=operation/users/user_edit'; -} - +// Load the header +require $config['homedir'].'/operation/users/user_edit_header.php'; // Update user info if (isset($_GET['modified']) && !$view_mode) { @@ -535,7 +492,7 @@ $table->rowclass[] = ''; $table->rowstyle[] = ''; $table->data[] = $data; -echo '
    '; +echo ''; html_print_table($table); From 37f6da9aa8df93525b87bd37968a30eb6f9a6dba Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 18 Feb 2019 15:36:51 +0100 Subject: [PATCH 155/249] recovered. changes from 0b72571c7cb47056711365750f9035012ab88af6 [formerly f3a8cdd6923834443ed7223d1e6ad7776b861184] Former-commit-id: 591e002043d2bae2382c8a91c437057fd2b809c7 --- pandora_console/include/db/mysql.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/db/mysql.php b/pandora_console/include/db/mysql.php index 49ffb2d101..66366c1289 100644 --- a/pandora_console/include/db/mysql.php +++ b/pandora_console/include/db/mysql.php @@ -706,6 +706,7 @@ function mysql_db_format_array_where_clause_sql($values, $join='AND', $prefix=fa $i = 1; $max = count($values); foreach ($values as $field => $value) { + $negative = false; if (is_numeric($field)) { // User provide the exact operation to do $query .= $value; @@ -718,6 +719,11 @@ function mysql_db_format_array_where_clause_sql($values, $join='AND', $prefix=fa continue; } + if ($field[0] == '!') { + $negative = true; + $field = substr($field, 1); + } + if ($field[0] != '`') { // If the field is as ., don't scape. if (strstr($field, '.') === false) { @@ -732,7 +738,8 @@ function mysql_db_format_array_where_clause_sql($values, $join='AND', $prefix=fa } else if (is_float($value) || is_double($value)) { $query .= sprintf('%s = %f', $field, $value); } else if (is_array($value)) { - $query .= sprintf('%s IN ("%s")', $field, implode('", "', $value)); + $not = $negative ? ' NOT ' : ''; + $query .= sprintf('%s %sIN ("%s")', $field, $not, implode('", "', $value)); } else { if ($value === '') { // Search empty string From 43ddd9d4823a77cd85ad5ec0fdd2b4ed5bf95ba5 Mon Sep 17 00:00:00 2001 From: daniel Date: Mon, 18 Feb 2019 16:34:48 +0100 Subject: [PATCH 156/249] fixed pdf Former-commit-id: e220052501d8f1b4c3d8f392cc9665876671e7ae --- pandora_console/include/chart_generator.php | 6 +----- pandora_console/include/functions_graph.php | 14 +++++++------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/pandora_console/include/chart_generator.php b/pandora_console/include/chart_generator.php index 96124afa4c..e7133fd79e 100644 --- a/pandora_console/include/chart_generator.php +++ b/pandora_console/include/chart_generator.php @@ -88,16 +88,13 @@ if (file_exists('languages/'.$user_language.'.mo')) { $params['menu'] = false; if ((!isset($params['width']) || ($params['width'] <= 0))) { - $params['width'] = 1048; + $params['width'] = 650; } $params_combined = json_decode($_REQUEST['data_combined'], true); $module_list = json_decode($_REQUEST['data_module_list'], true); $type_graph_pdf = $_REQUEST['type_graph_pdf']; - $aux_font_size = $config['font_size']; - $config['font_size'] = ($config['font_size'] + 3); - echo '
    '; switch ($type_graph_pdf) { case 'combined': @@ -216,7 +213,6 @@ if (file_exists('languages/'.$user_language.'.mo')) { echo '
    '; - $config['font_size'] = $aux_font_size; ?> '; From 819910923f4c5c4070411f381d801a486a924d57 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 19 Feb 2019 18:29:59 +0100 Subject: [PATCH 182/249] Added callback to print forms Former-commit-id: 8e95ba3ae518a750d421fcce41238ca7f47b46c2 --- .../godmode/wizards/Wizard.main.php | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 78ea5d7be3..5c7fbb60a5 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -476,13 +476,11 @@ class Wizard $cb_function = $data['cb_function']; $cb_args = $data['cb_args']; - $output = ''; + $output_head = ''; - $output .= '
      '; - - foreach ($inputs as $input) { - $output .= $this->printBlock($input, true); + if ($return === false) { + echo $output_head; } try { @@ -496,6 +494,12 @@ class Wizard error_log('Error executing wizard callback: ', $e->getMessage()); } + $output = '
        '; + + foreach ($inputs as $input) { + $output .= $this->printBlock($input, true); + } + $output .= '
      '; $output .= ''; $output .= ''; @@ -504,7 +508,7 @@ class Wizard echo $output; } - return $output; + return $output_head.$output; } From 422708c04a59af4bcf118dab6a9b42f02239d54a Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Tue, 19 Feb 2019 18:33:17 +0100 Subject: [PATCH 183/249] Revert "Wiz.Applications SQL updates" Identification using recon_script This reverts commit e7abe4ad4372158206e47b628c9f17f8cfea2ac4 [formerly e0f547a0f35b338705a14df6477bf3a5461d8e49]. Former-commit-id: 5b112c7d889d98c2040514556849ce4e408ab444 --- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 1 - pandora_console/pandoradb.sql | 1 - 2 files changed, 2 deletions(-) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 2352cf2a66..c86c9bf7d6 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1409,7 +1409,6 @@ ALTER TABLE trecon_task ADD `vlan_enabled` int(2) unsigned default '0'; ALTER TABLE trecon_task ADD `wmi_enabled` tinyint(1) unsigned DEFAULT '0'; ALTER TABLE trecon_task ADD `auth_strings` text; ALTER TABLE trecon_task ADD `autoconfiguration_enabled` tinyint(1) unsigned default '0'; -ALTER TABLE trecon_task ADD `task_type` tinyint(2) NOT NULL default '0'; -- --------------------------------------------------------------------- -- Table `twidget` AND Table `twidget_dashboard` diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index 34d843bb44..ae780a5470 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -785,7 +785,6 @@ CREATE TABLE IF NOT EXISTS `trecon_task` ( `wmi_enabled` tinyint(1) unsigned DEFAULT '0', `auth_strings` text, `autoconfiguration_enabled` tinyint(1) unsigned default '0', - `task_type` tinyint(2) NOT NULL default '0', PRIMARY KEY (`id_rt`), KEY `recon_task_daemon` (`id_recon_server`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; From 55af128cd599cc49274e9a4873b2a61fd848a6b7 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Tue, 19 Feb 2019 20:14:14 +0100 Subject: [PATCH 184/249] Modified snmp browser to work with wizard Former-commit-id: c8d37e06967ed43867320ae89fd3dc2bede7b0ce --- pandora_console/godmode/wizards/Wizard.main.php | 2 +- pandora_console/include/functions_snmp_browser.php | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 5c7fbb60a5..b191223770 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -485,7 +485,7 @@ class Wizard try { if (isset($cb_function) === true) { - call_user_func( + call_user_func_array( $cb_function, (isset($cb_args) === true) ? $cb_args : [] ); diff --git a/pandora_console/include/functions_snmp_browser.php b/pandora_console/include/functions_snmp_browser.php index 57bc416c76..714d394b4a 100644 --- a/pandora_console/include/functions_snmp_browser.php +++ b/pandora_console/include/functions_snmp_browser.php @@ -27,7 +27,7 @@ $nfdump_date_format = 'Y/m/d.H:i:s'; * @param id string Level ID. Do not set, used for recursion. * @param depth string Branch depth. Do not set, used for recursion. */ -function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[]) +function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[], $sufix=false) { static $url = false; @@ -106,7 +106,9 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] echo ''; } - echo html_print_checkbox("create_$sub_id", 0, false, true, false, '').' '.$level.''; + $checkbox_name_sufix = ($sufix) ? '' : '_'.$level; + $checkbox_name = 'create_'.$sub_id.$checkbox_name_sufix; + echo html_print_checkbox($checkbox_name, 0, false, true, false, '').' '.$level.''; if (isset($sub_level['__VALUE__'])) { echo ''; } @@ -114,7 +116,7 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] echo ''; // Recursively print sub levels - snmp_browser_print_tree($sub_level, $sub_id, ($depth + 1), ($count == $total ? 1 : 0), $last_array); + snmp_browser_print_tree($sub_level, $sub_id, ($depth + 1), ($count == $total ? 1 : 0), $last_array, $sufix); $count++; } @@ -838,7 +840,7 @@ function snmp_browser_print_container($return=false, $width='100%', $height='500 if ($(this).is(':checked') ) { $('input[name*=create_network_component]').show(); var id_input = $(this).attr("id"); - id_input = id_input.split("checkbox-create_"); + id_input = id_input.match("checkbox-create_([0-9]+)"); var checks = $('#ul_'+id_input[1]).find('input').map(function(){ if(this.id.indexOf('checkbox-create_')!=-1){ return this.id; @@ -851,7 +853,7 @@ function snmp_browser_print_container($return=false, $width='100%', $height='500 } else { var id_input = $(this).attr("id"); - id_input = id_input.split("checkbox-create_"); + id_input = id_input.match("checkbox-create_([0-9]+)"); var checks = $('#ul_'+id_input[1]).find('input').map(function(){ if(this.id.indexOf('checkbox-create_')!=-1){ return this.id; From fa3f548cdd35b607e1605d7ee5c6107449258404 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Tue, 19 Feb 2019 20:27:05 +0100 Subject: [PATCH 185/249] Several changes for Wiz.App support Former-commit-id: 7c86d2e601771686a69d3f1b846638a427a25d6e --- .../wizards/DiscoveryTaskList.class.php | 27 ++++++++++- .../godmode/wizards/Wizard.main.php | 46 +++++++++++++++++++ .../include/class/ConsoleSupervisor.php | 3 +- 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index d0c5da17fb..e135c80672 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -292,8 +292,13 @@ class DiscoveryTaskList extends Wizard $data[7] = ui_print_timestamp($task['utimestamp'], true); if (check_acl($config['id_user'], $task['id_group'], 'PM')) { + // Check if is a H&D, Cloud or Application. $data[8] = ''.html_print_image( 'images/wrench_orange.png', true @@ -348,4 +353,24 @@ class DiscoveryTaskList extends Wizard } + /** + * Return target url sub-string to edit target task. + * + * @param array $task With all data. + * + * @return string + */ + public function getTargetWiz($task) + { + // TODO: Do not use description. Use recon_script ID instead. + switch ($task['description']) { + case 'Discovery.Application.VMware': + return 'wiz=app&mode=vmware'; + + default: + return 'wiz=hd&mode=netscan'; + } + } + + } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 2f58bea91e..31e494a737 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -80,6 +80,52 @@ class Wizard } + /** + * Setter for label + * + * @param string $str Label. + * + * @return void + */ + public function setLabel(string $str) + { + $this->label = $str; + } + + + /** + * Getter for label + * + * @return array Breadcrum. + */ + public function getLabel() + { + return $this->label; + } + + + /** + * Builder for breadcrum + * + * @param array $urls Array of urls to be stored in breadcrum. + * + * @return void + */ + public function prepareBreadcrum(array $urls) + { + $bc = []; + $i = 0; + foreach ($urls as $url) { + $bc[$i] = ''; + $bc[$i] .= '
      '.$url['label'].'
      '; + $bc[$i++] .= '
      '; + } + + $this->setBreadcrum($bc); + + } + + /** * To be overwritten. * diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index 88dbf0f11f..fa40994962 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -2101,7 +2101,7 @@ class ConsoleSupervisor $message_conf_cron = __('DiscoveryConsoleTasks is not running properly'); if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { $message_conf_cron .= __('Discovery relies on a proper setup of cron, the time-based scheduling service'); - $message_conf_cron .= ' '.__('Please, add the following line to your crontab file:'); + $message_conf_cron .= '. '.__('Please, add the following line to your crontab file:'); $message_conf_cron .= '
      * * * * * <user> wget -q -O - --no-check-certificate ';
                       $message_conf_cron .= str_replace(
                           ENTERPRISE_DIR.'/meta/',
      @@ -2116,6 +2116,7 @@ class ConsoleSupervisor
                   if (isset($config['cron_last_run']) === true) {
                       $message_conf_cron .= __('Last execution').': ';
                       $message_conf_cron .= date('Y/m/d H:i:s', $config['cron_last_run']);
      +                $message_conf_cron .= __('Please check process is no locked.');
                   }
       
                   $this->notify(
      
      From 53a41a7a56f441a73b4eee30e7c52344557dc346 Mon Sep 17 00:00:00 2001
      From: artica 
      Date: Wed, 20 Feb 2019 00:01:26 +0100
      Subject: [PATCH 186/249] Auto-updated build strings.
      
      Former-commit-id: f44eb5d91d85be5ebfaf5fe25cea0fdb40b874f3
      ---
       pandora_agents/unix/DEBIAN/control             | 2 +-
       pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +-
       pandora_agents/unix/pandora_agent              | 2 +-
       pandora_agents/unix/pandora_agent.redhat.spec  | 2 +-
       pandora_agents/unix/pandora_agent.spec         | 2 +-
       pandora_agents/unix/pandora_agent_installer    | 2 +-
       pandora_agents/win32/installer/pandora.mpi     | 2 +-
       pandora_agents/win32/pandora.cc                | 2 +-
       pandora_agents/win32/versioninfo.rc            | 2 +-
       pandora_console/DEBIAN/control                 | 2 +-
       pandora_console/DEBIAN/make_deb_package.sh     | 2 +-
       pandora_console/include/config_process.php     | 2 +-
       pandora_console/install.php                    | 2 +-
       pandora_console/pandora_console.redhat.spec    | 2 +-
       pandora_console/pandora_console.spec           | 2 +-
       pandora_server/DEBIAN/control                  | 2 +-
       pandora_server/DEBIAN/make_deb_package.sh      | 2 +-
       pandora_server/lib/PandoraFMS/Config.pm        | 2 +-
       pandora_server/lib/PandoraFMS/PluginTools.pm   | 2 +-
       pandora_server/pandora_server.redhat.spec      | 2 +-
       pandora_server/pandora_server.spec             | 2 +-
       pandora_server/pandora_server_installer        | 2 +-
       pandora_server/util/pandora_db.pl              | 2 +-
       pandora_server/util/pandora_manage.pl          | 2 +-
       24 files changed, 24 insertions(+), 24 deletions(-)
      
      diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control
      index 43f8a477da..a386a52e45 100644
      --- a/pandora_agents/unix/DEBIAN/control
      +++ b/pandora_agents/unix/DEBIAN/control
      @@ -1,5 +1,5 @@
       package: pandorafms-agent-unix
      -Version: 7.0NG.731-190219
      +Version: 7.0NG.731-190220
       Architecture: all
       Priority: optional
       Section: admin
      diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh
      index 47e51c22e1..b1c6ee397e 100644
      --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh
      +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh
      @@ -14,7 +14,7 @@
       # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       # GNU General Public License for more details.
       
      -pandora_version="7.0NG.731-190219"
      +pandora_version="7.0NG.731-190220"
       
       echo "Test if you has the tools for to make the packages."
       whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null
      diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent
      index 6d3983758e..3107ac2198 100755
      --- a/pandora_agents/unix/pandora_agent
      +++ b/pandora_agents/unix/pandora_agent
      @@ -42,7 +42,7 @@ my $Sem = undef;
       my $ThreadSem = undef;
       
       use constant AGENT_VERSION => '7.0NG.731';
      -use constant AGENT_BUILD => '190219';
      +use constant AGENT_BUILD => '190220';
       
       # Agent log default file size maximum and instances
       use constant DEFAULT_MAX_LOG_SIZE => 600000;
      diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec
      index 076a9ef928..de2c0f3449 100644
      --- a/pandora_agents/unix/pandora_agent.redhat.spec
      +++ b/pandora_agents/unix/pandora_agent.redhat.spec
      @@ -3,7 +3,7 @@
       #
       %define name        pandorafms_agent_unix
       %define version     7.0NG.731
      -%define release     190219
      +%define release     190220
       
       Summary:            Pandora FMS Linux agent, PERL version
       Name:               %{name}
      diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec
      index 394ac97c05..e046351d49 100644
      --- a/pandora_agents/unix/pandora_agent.spec
      +++ b/pandora_agents/unix/pandora_agent.spec
      @@ -3,7 +3,7 @@
       #
       %define name        pandorafms_agent_unix
       %define version     7.0NG.731
      -%define release     190219
      +%define release     190220
       
       Summary:            Pandora FMS Linux agent, PERL version
       Name:               %{name}
      diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer
      index c16a74273a..ded90e67b6 100755
      --- a/pandora_agents/unix/pandora_agent_installer
      +++ b/pandora_agents/unix/pandora_agent_installer
      @@ -10,7 +10,7 @@
       # **********************************************************************
       
       PI_VERSION="7.0NG.731"
      -PI_BUILD="190219"
      +PI_BUILD="190220"
       OS_NAME=`uname -s`
       
       FORCE=0
      diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi
      index fb99d6c15f..d082626f9d 100644
      --- a/pandora_agents/win32/installer/pandora.mpi
      +++ b/pandora_agents/win32/installer/pandora.mpi
      @@ -186,7 +186,7 @@ UpgradeApplicationID
       {}
       
       Version
      -{190219}
      +{190220}
       
       ViewReadme
       {Yes}
      diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc
      index 2abbc0a7b3..6409b7f2d0 100644
      --- a/pandora_agents/win32/pandora.cc
      +++ b/pandora_agents/win32/pandora.cc
      @@ -30,7 +30,7 @@ using namespace Pandora;
       using namespace Pandora_Strutils;
       
       #define PATH_SIZE    _MAX_PATH+1
      -#define PANDORA_VERSION ("7.0NG.731(Build 190219)")
      +#define PANDORA_VERSION ("7.0NG.731(Build 190220)")
       
       string pandora_path;
       string pandora_dir;
      diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc
      index bc770967dd..889216ad1a 100644
      --- a/pandora_agents/win32/versioninfo.rc
      +++ b/pandora_agents/win32/versioninfo.rc
      @@ -11,7 +11,7 @@ BEGIN
             VALUE "LegalCopyright", "Artica ST"
             VALUE "OriginalFilename", "PandoraAgent.exe"
             VALUE "ProductName", "Pandora FMS Windows Agent"
      -      VALUE "ProductVersion", "(7.0NG.731(Build 190219))"
      +      VALUE "ProductVersion", "(7.0NG.731(Build 190220))"
             VALUE "FileVersion", "1.0.0.0"
           END
         END
      diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control
      index a7a372a3dd..9463042f31 100644
      --- a/pandora_console/DEBIAN/control
      +++ b/pandora_console/DEBIAN/control
      @@ -1,5 +1,5 @@
       package: pandorafms-console
      -Version: 7.0NG.731-190219
      +Version: 7.0NG.731-190220
       Architecture: all
       Priority: optional
       Section: admin
      diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh
      index fd52973ced..4dff45a12a 100644
      --- a/pandora_console/DEBIAN/make_deb_package.sh
      +++ b/pandora_console/DEBIAN/make_deb_package.sh
      @@ -14,7 +14,7 @@
       # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       # GNU General Public License for more details.
       
      -pandora_version="7.0NG.731-190219"
      +pandora_version="7.0NG.731-190220"
       
       package_pear=0
       package_pandora=1
      diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php
      index ab56a9f6e4..1519fbde36 100644
      --- a/pandora_console/include/config_process.php
      +++ b/pandora_console/include/config_process.php
      @@ -20,7 +20,7 @@
       /**
        * Pandora build version and version
        */
      -$build_version = 'PC190219';
      +$build_version = 'PC190220';
       $pandora_version = 'v7.0NG.731';
       
       // Do not overwrite default timezone set if defined.
      diff --git a/pandora_console/install.php b/pandora_console/install.php
      index be416f5b40..ad9889d1b3 100644
      --- a/pandora_console/install.php
      +++ b/pandora_console/install.php
      @@ -129,7 +129,7 @@
               
      [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 0e83289792..e64e4cb345 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190219 +%define release 190220 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 3696930e4d..acb121e249 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190219 +%define release 190220 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index 6ef203a875..069e8311c9 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190219" +PI_BUILD="190220" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index ab35080dc9..67e58019af 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190219"; +my $version = "7.0NG.731 PS190220"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index aaafd6978c..3046097bbd 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190219"; +my $version = "7.0NG.731 PS190220"; # save program name for logging my $progname = basename($0); From 3d2ae475431b63b87bd42bec933af670a86ce1b0 Mon Sep 17 00:00:00 2001 From: manuel Date: Wed, 20 Feb 2019 08:41:15 +0100 Subject: [PATCH 187/249] Added prepareBreadcrum function Former-commit-id: caf781a20bdd16bed7347bf755e2bf0da6ae7e99 --- .../godmode/wizards/HostDevices.class.php | 74 ++++++++++++++++--- 1 file changed, 63 insertions(+), 11 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index f7a9b22e21..83f5d21b4c 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -92,7 +92,15 @@ class HostDevices extends Wizard $mode = get_parameter('mode', null); if ($mode === null) { - $this->setBreadcrum(['
          Host & devices
      ']); + $this->prepareBreadcrum( + [ + [ + 'link' => $this->url.'&wiz=hd', + 'label' => __('    Host & devices'), + ], + ] + ); + $this->printHeader(); $this->printBigButtonsList( [ @@ -115,10 +123,16 @@ class HostDevices extends Wizard if (enterprise_installed()) { if ($mode == 'importcsv') { - $this->setBreadcrum( + $this->prepareBreadcrum( [ - '
          Host & devices
      ', - '
            Import CSV
      ', + [ + 'link' => $this->url.'&wiz=hd', + 'label' => __('    Host & devices'), + ], + [ + 'link' => $this->url.'&wiz=hd&mode=importcsv', + 'label' => __('      Import CSV'), + ], ] ); $this->printHeader(); @@ -130,18 +144,34 @@ class HostDevices extends Wizard if ($mode == 'netscan') { if ($this->page != 2) { // Do not paint breadcrum in last page. Redirected. - $this->setBreadcrum( + $this->prepareBreadcrum( [ - '
          Host & devices
      ', - '
          Net scan definition
      ', + [ + 'link' => $this->url.'&wiz=hd', + 'label' => __('    Host & devices'), + ], + [ + 'link' => $this->url.'&wiz=hd&mode=netscan', + 'label' => __('      Net scan definition'), + ], ] ); + if ($this->page == 1) { - $this->setBreadcrum( + $this->prepareBreadcrum( [ - '
          Host & devices
      ', - '
          Net scan definition
      ', - '
          Net scan features
      ', + [ + 'link' => $this->url.'&wiz=hd', + 'label' => __('    Host & devices'), + ], + [ + 'link' => $this->url.'&wiz=hd&mode=netscan', + 'label' => __('      Net scan definition'), + ], + [ + 'link' => $this->url.'&wiz=hd&mode=netscan&page=1', + 'label' => __('      Net scan features'), + ], ] ); } @@ -1096,4 +1126,26 @@ $(function() { } + /** + * Builder for breadcrum + * + * @param array $urls Array of urls to be stored in breadcrum. + * + * @return void + */ + public function prepareBreadcrum(array $urls) + { + $bc = []; + $i = 0; + foreach ($urls as $url) { + $bc[$i] = ''; + $bc[$i] .= '
      '.$url['label'].'
      '; + $bc[$i++] .= '
      '; + } + + $this->setBreadcrum($bc); + + } + + } From ca243c46fbdfc35198d2561e8709288e3d0a6feb Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 20 Feb 2019 08:52:29 +0100 Subject: [PATCH 188/249] Minor fix Former-commit-id: f3c550c07a38df24b5de84200190583437586720 --- pandora_console/include/functions_snmp_browser.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/pandora_console/include/functions_snmp_browser.php b/pandora_console/include/functions_snmp_browser.php index 714d394b4a..9354d4adfd 100644 --- a/pandora_console/include/functions_snmp_browser.php +++ b/pandora_console/include/functions_snmp_browser.php @@ -52,13 +52,13 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] } foreach ($tree['__LEAVES__'] as $level => $sub_level) { - // Id used to expand leafs + // Id used to expand leafs. $sub_id = time().rand(0, getrandmax()); - // Display the branch + // Display the branch. echo "
    • "; - // Indent sub branches + // Indent sub branches. for ($i = 1; $i <= $depth; $i++) { if ($last_array[$i] == 1) { echo ''; @@ -67,7 +67,7 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] } } - // Branch + // Branch. if (! empty($sub_level['__LEAVES__'])) { echo ""; if ($depth == 0 && $count == 0) { @@ -84,7 +84,7 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] echo ''; } - // Leave + // Leave. else { if ($depth == 0 && $count == 0) { if ($count == $total) { @@ -106,7 +106,7 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] echo ''; } - $checkbox_name_sufix = ($sufix) ? '' : '_'.$level; + $checkbox_name_sufix = ($sufix === true) ? '_'.$level : ''; $checkbox_name = 'create_'.$sub_id.$checkbox_name_sufix; echo html_print_checkbox($checkbox_name, 0, false, true, false, '').' '.$level.''; if (isset($sub_level['__VALUE__'])) { @@ -115,7 +115,7 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] echo '
    • '; - // Recursively print sub levels + // Recursively print sub levels. snmp_browser_print_tree($sub_level, $sub_id, ($depth + 1), ($count == $total ? 1 : 0), $last_array, $sufix); $count++; From c36241de4fbd12c6038cbb81adea195141cb8678 Mon Sep 17 00:00:00 2001 From: Ramon Novoa Date: Wed, 20 Feb 2019 09:04:15 +0100 Subject: [PATCH 189/249] Add additional help icons. Former-commit-id: 9641eb9ceaefde1c24503fcfb4c7965afedf8fbc --- .../modules/manage_network_components_form_network.php | 8 ++++---- .../modules/manage_network_components_form_wmi.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pandora_console/godmode/modules/manage_network_components_form_network.php b/pandora_console/godmode/modules/manage_network_components_form_network.php index 329d8d1405..8befa28555 100755 --- a/pandora_console/godmode/modules/manage_network_components_form_network.php +++ b/pandora_console/godmode/modules/manage_network_components_form_network.php @@ -57,16 +57,16 @@ $data = []; $data[0] = __('SNMP Enterprise String'); $data[1] = html_print_input_text('snmp_oid', $snmp_oid, '', 30, 400, true); // $table->colspan['snmp_2'][1] = 3; -$data[2] = __('SNMP community'); +$data[2] = __('SNMP community').ui_print_help_icon('column_macros', true); $data[3] = html_print_input_text('snmp_community', $snmp_community, '', 15, 60, true); push_table_row($data, 'snmp_2'); $data = []; -$data[0] = __('Auth user'); +$data[0] = __('Auth user').ui_print_help_icon('column_macros', true); $data[1] = html_print_input_text('snmp3_auth_user', $snmp3_auth_user, '', 15, 60, true); -$data[2] = __('Auth password'); +$data[2] = __('Auth password').ui_print_help_icon('column_macros', true); $data[3] = html_print_input_password('snmp3_auth_pass', $snmp3_auth_pass, '', 15, 60, true); $data[3] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_mncfn', true); push_table_row($data, 'field_snmpv3_row1'); @@ -74,7 +74,7 @@ push_table_row($data, 'field_snmpv3_row1'); $data = []; $data[0] = __('Privacy method'); $data[1] = html_print_select(['DES' => __('DES'), 'AES' => __('AES')], 'snmp3_privacy_method', $snmp3_privacy_method, '', '', '', true); -$data[2] = __('Privacy pass'); +$data[2] = __('Privacy pass').ui_print_help_icon('column_macros', true); $data[3] = html_print_input_password('snmp3_privacy_pass', $snmp3_privacy_pass, '', 15, 60, true); push_table_row($data, 'field_snmpv3_row2'); diff --git a/pandora_console/godmode/modules/manage_network_components_form_wmi.php b/pandora_console/godmode/modules/manage_network_components_form_wmi.php index 35b846250e..f88441f5d5 100755 --- a/pandora_console/godmode/modules/manage_network_components_form_wmi.php +++ b/pandora_console/godmode/modules/manage_network_components_form_wmi.php @@ -44,9 +44,9 @@ $data[3] = html_print_input_text('tcp_send', $tcp_send, '', 25, 255, true); push_table_row($data, 'wmi_2'); $data = []; -$data[0] = __('Username'); +$data[0] = __('Username').ui_print_help_icon('column_macros', true); $data[1] = html_print_input_text('plugin_user', $plugin_user, '', 15, 255, true); -$data[2] = __('Password'); +$data[2] = __('Password').ui_print_help_icon('column_macros', true); $data[3] = html_print_input_password('plugin_pass', $plugin_pass, '', 25, 255, true); push_table_row($data, 'wmi_3'); From e9d97e8010d1eb73a43d487e6503e78a725ce70d Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 10:53:54 +0100 Subject: [PATCH 190/249] Wiz. Added option url to printGoBackButton Former-commit-id: 31c9c56da3475f9b1510904ad7237f993c0a6ccf --- pandora_console/godmode/wizards/Wizard.main.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 31e494a737..ebee7c9c03 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -402,13 +402,17 @@ class Wizard * * @return void */ - public function printGoBackButton() + public function printGoBackButton($url) { + if (isset($url) === false) { + $url = 'index.php?sec=gservers&sec2=godmode/servers/discovery'; + } + $form = [ 'form' => [ 'method' => 'POST', 'action' => ui_get_full_url( - 'index.php?sec=gservers&sec2=godmode/servers/discovery' + $url ), ], 'inputs' => [ From 65db8482c1645191f16b1d730b7b4ed75ef2dd80 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 10:58:56 +0100 Subject: [PATCH 191/249] Wiz. Added option url to printGoBackButton Former-commit-id: fd0c76ce5efef9902cbda2817b13e59e6672c972 --- pandora_console/godmode/wizards/Wizard.main.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index ebee7c9c03..d2ee440a67 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -405,15 +405,15 @@ class Wizard public function printGoBackButton($url) { if (isset($url) === false) { - $url = 'index.php?sec=gservers&sec2=godmode/servers/discovery'; + $url = ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery' + ); } $form = [ 'form' => [ 'method' => 'POST', - 'action' => ui_get_full_url( - $url - ), + 'action' => $url, ], 'inputs' => [ [ From a63e497497e60fc5ed91872832a88de1a043bb1c Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 11:11:26 +0100 Subject: [PATCH 192/249] Wiz. Added textarea input Former-commit-id: 319ab37377e6649c1cd6c6adea1e956e934f2e23 --- pandora_console/godmode/wizards/Wizard.main.php | 11 +++++++++++ pandora_console/include/styles/wizard.css | 6 ++++++ 2 files changed, 17 insertions(+) diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index d2ee440a67..21731a4bf8 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -388,6 +388,17 @@ class Wizard case 'switch': return html_print_switch($data); + case 'textarea': + return html_print_textarea( + $data['name'], + $data['rows'], + $data['columns'], + ((isset($data['value']) === true) ? $data['value'] : ''), + ((isset($data['attributes']) === true) ? $data['attributes'] : ''), + ((isset($data['return']) === true) ? $data['return'] : false), + ((isset($data['class']) === true) ? $data['class'] : '') + ); + default: // Ignore. break; diff --git a/pandora_console/include/styles/wizard.css b/pandora_console/include/styles/wizard.css index 912f5d5a4f..869ea85f2c 100644 --- a/pandora_console/include/styles/wizard.css +++ b/pandora_console/include/styles/wizard.css @@ -10,6 +10,12 @@ ul.wizard li { } ul.wizard li > label:not(.p-switch) { + width: 250px; + vertical-align: top; + display: inline-block; +} + +ul.wizard li > textarea { width: 250px; display: inline-block; } From af2954d3923b86cdac6f5551ef6b130e7737f67a Mon Sep 17 00:00:00 2001 From: manuel Date: Wed, 20 Feb 2019 11:46:32 +0100 Subject: [PATCH 193/249] Changed controls in static graph vs Former-commit-id: 4db156a5abd372d0d50c252936a00d00416dc475 --- .../reporting/visual_console_builder.editor.js | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/pandora_console/godmode/reporting/visual_console_builder.editor.js b/pandora_console/godmode/reporting/visual_console_builder.editor.js index 457c80d7a4..6744d2fb2d 100755 --- a/pandora_console/godmode/reporting/visual_console_builder.editor.js +++ b/pandora_console/godmode/reporting/visual_console_builder.editor.js @@ -475,14 +475,6 @@ function update_button_palette_callback() { dialog_message("#message_alert_max_height"); return false; } - if (values["module"] == 0) { - dialog_message("#message_alert_no_module"); - return false; - } - if (values["agent"] == "") { - dialog_message("#message_alert_no_agent"); - return false; - } if ( (values["image"] == "" || values["image"] == "none") && values["label"] == "" @@ -1311,14 +1303,6 @@ function create_button_palette_callback() { dialog_message("#message_alert_max_width"); validate = false; } - if (values["module"] == 0) { - dialog_message("#message_alert_no_module"); - validate = false; - } - if (values["agent"] == "") { - dialog_message("#message_alert_no_agent"); - validate = false; - } if ( (values["image"] == "" || values["image"] == "none") && values["label"] == false From f19bdf956e800c31ceaf12790ae0e1e4da502d02 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 12:32:12 +0100 Subject: [PATCH 194/249] Wiz. minor fix default value url in goback button Former-commit-id: 434b2acb09290f11c8804024adb8834b86eeda73 --- pandora_console/godmode/wizards/Wizard.main.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 21731a4bf8..65a526cc58 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -413,7 +413,7 @@ class Wizard * * @return void */ - public function printGoBackButton($url) + public function printGoBackButton($url=null) { if (isset($url) === false) { $url = ui_get_full_url( From e088b412cd831bd669850c690984f1ae6ffc2f9a Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 20 Feb 2019 13:55:21 +0100 Subject: [PATCH 195/249] Added preload schecked values into snmp browser treeview Former-commit-id: d8a3317d849263ff732cbf3a7a7714f4b41917d5 --- pandora_console/include/functions_snmp_browser.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pandora_console/include/functions_snmp_browser.php b/pandora_console/include/functions_snmp_browser.php index 9354d4adfd..4920816c89 100644 --- a/pandora_console/include/functions_snmp_browser.php +++ b/pandora_console/include/functions_snmp_browser.php @@ -27,7 +27,7 @@ $nfdump_date_format = 'Y/m/d.H:i:s'; * @param id string Level ID. Do not set, used for recursion. * @param depth string Branch depth. Do not set, used for recursion. */ -function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[], $sufix=false) +function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[], $sufix=false, $checked=[]) { static $url = false; @@ -108,7 +108,8 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] $checkbox_name_sufix = ($sufix === true) ? '_'.$level : ''; $checkbox_name = 'create_'.$sub_id.$checkbox_name_sufix; - echo html_print_checkbox($checkbox_name, 0, false, true, false, '').' '.$level.''; + $status = (!empty($checked) && isset($checked[$level])); + echo html_print_checkbox($checkbox_name, 0, $status, true, false, '').' '.$level.''; if (isset($sub_level['__VALUE__'])) { echo ''; } @@ -116,7 +117,7 @@ function snmp_browser_print_tree($tree, $id=0, $depth=0, $last=0, $last_array=[] echo ''; // Recursively print sub levels. - snmp_browser_print_tree($sub_level, $sub_id, ($depth + 1), ($count == $total ? 1 : 0), $last_array, $sufix); + snmp_browser_print_tree($sub_level, $sub_id, ($depth + 1), ($count == $total ? 1 : 0), $last_array, $sufix, $checked); $count++; } From 4834561e873d6117197ef697eaa7c683f30a2359 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 14:38:00 +0100 Subject: [PATCH 196/249] Wiz. minor fixes Former-commit-id: b3963bf5994a8f9829922e0a1b0be3a20fc54fba --- .../godmode/wizards/HostDevices.class.php | 12 ++++- .../godmode/wizards/Wizard.main.php | 44 ++++++++++++++++++- pandora_console/include/styles/discovery.css | 10 ++++- 3 files changed, 60 insertions(+), 6 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 83f5d21b4c..b5f635eb40 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -690,6 +690,14 @@ class HostDevices extends Wizard 'action' => $this->url.'&mode=netscan&page='.($this->page + 1).$task_url, ]; + // Default. + $interval = 600; + $unit = 60; + if (isset($this->task['interval_sweep']) === true) { + $interval = $this->task['interval_sweep']; + $unit = $this->getTimeUnit($interval); + } + $form['js'] = ' $("select#interval_manual_defined").change(function() { if ($("#interval_manual_defined").val() == 1) { @@ -700,8 +708,8 @@ $("select#interval_manual_defined").change(function() { else { $("#interval_manual_container").show(); $("#text-interval_text").val(10); - $("#hidden-interval").val(600); - $("#interval_units").val(60); + $("#hidden-interval").val('.$interval.'); + $("#interval_units").val('.$unit.'); } }).change();'; diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 65a526cc58..638228c365 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -104,6 +104,40 @@ class Wizard } + /** + * Return units associated to target interval (in seconds). + * + * @param integer $interval Target interval. + * + * @return integer Unit. + */ + public function getTimeUnit($interval) + { + $units = [ + 1, + 60, + 3600, + 86400, + 604800, + 2592000, + 31104000, + ]; + + $size = count($units); + for ($i = 0; $i < $size; $i++) { + if ($interval < $units[$i]) { + if (($i - 1) < 0) { + return 1; + } + + return $units[($i - 1)]; + } + } + + return $units[-1]; + } + + /** * Builder for breadcrum * @@ -116,9 +150,15 @@ class Wizard $bc = []; $i = 0; foreach ($urls as $url) { + if ($url['selected'] == 1) { + $class = 'selected'; + } else { + $class = ''; + } + $bc[$i] = ''; - $bc[$i] .= '
      '.$url['label'].'
      '; - $bc[$i++] .= '
      '; + $bc[$i] .= '
      '.$url['label']; + $bc[$i++] .= '
      '; } $this->setBreadcrum($bc); diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css index 7c5933aba9..aebb0a3d0d 100644 --- a/pandora_console/include/styles/discovery.css +++ b/pandora_console/include/styles/discovery.css @@ -60,7 +60,7 @@ div.data_container:hover { .arrow_box { display: inline-block; position: relative; - background: #82b92e; + background: #ccc; padding: 14px; margin-left: 20px; margin-bottom: 10px; @@ -75,6 +75,9 @@ div.data_container:hover { position: absolute; pointer-events: none; } +.arrow_box.selected { + background: #82b92e; +} .arrow_box:after { left: 0%; @@ -84,7 +87,10 @@ div.data_container:hover { } .arrow_box:before { left: 100%; - border-left-color: #82b92e; + border-left-color: #ccc; border-width: 20px; margin-top: -20px; } +.arrow_box.selected:before { + border-left-color: #82b92e; +} From f49b26692e796b3d6859c0f73f50953cafd9b5bb Mon Sep 17 00:00:00 2001 From: fermin831 Date: Wed, 20 Feb 2019 16:47:29 +0100 Subject: [PATCH 197/249] Fixes on wizards Former-commit-id: 98804bde49e19a7ecb3e2749a8955ac656da54a8 --- .../godmode/wizards/HostDevices.class.php | 22 ------------------ .../godmode/wizards/Wizard.main.php | 23 ++++++++++++------- 2 files changed, 15 insertions(+), 30 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 83f5d21b4c..538969e6ef 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -1126,26 +1126,4 @@ $(function() { } - /** - * Builder for breadcrum - * - * @param array $urls Array of urls to be stored in breadcrum. - * - * @return void - */ - public function prepareBreadcrum(array $urls) - { - $bc = []; - $i = 0; - foreach ($urls as $url) { - $bc[$i] = ''; - $bc[$i] .= '
      '.$url['label'].'
      '; - $bc[$i++] .= '
      '; - } - - $this->setBreadcrum($bc); - - } - - } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index c0ae95504c..de6ed6b525 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -83,17 +83,17 @@ class Wizard /** * Add an element to breadcrum array. * - * @param string $string Element to add to breadcrum. + * @param string $breads Elements to add to breadcrum. * * @return void */ - protected function addBreadcrum($string) + protected function addBreadcrum($breads) { - if (empty($string)) { + if (empty($breads)) { return; } - array_push($this->breadcrum, $string); + $this->breadcrum = array_merge($this->breadcrum, $breads); } @@ -124,21 +124,28 @@ class Wizard /** * Builder for breadcrum * - * @param array $urls Array of urls to be stored in breadcrum. + * @param array $urls Array of urls to be stored in breadcrum. + * @param boolean $add True if breadcrum should be added instead of + * overwrite it. * * @return void */ - public function prepareBreadcrum(array $urls) + public function prepareBreadcrum(array $urls, bool $add=false) { $bc = []; $i = 0; foreach ($urls as $url) { - $bc[$i] = ''; + $href = (isset($url['link']) === true) ? 'href="'.$url['link'].'"' : ''; + $bc[$i] = ''; $bc[$i] .= '
      '.$url['label'].'
      '; $bc[$i++] .= '
      '; } - $this->setBreadcrum($bc); + if ($add === true) { + $this->addBreadcrum($bc); + } else { + $this->setBreadcrum($bc); + } } From eb3adfb6fb016e5e7fedd5385aa789efb9dfc9ae Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 17:17:24 +0100 Subject: [PATCH 198/249] Data update. added recon scripts app.vmware and cloud Former-commit-id: 1fa41a16848794846fee6b5da510bd49aa7b51b1 --- .../extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 6 ++++++ pandora_console/pandoradb_data.sql | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index c86c9bf7d6..6827938b42 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1997,3 +1997,9 @@ CREATE TABLE `tnotification_source_group_user` ( -- Add alert command 'Generate notification' -- ---------------------------------------------------------------------- INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fields_descriptions`, `fields_values`) VALUES ('Generate Notification','Internal type','This command allows you to send an internal notification to any user or group.',1,'[\"Destination user\",\"Destination group\",\"Title\",\"Message\",\"Link\",\"Criticity\",\"\",\"\",\"\",\"\",\"\"]','[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]'); + +-- ---------------------------------------------------------------------- +-- Add custom internal recon scripts +-- ---------------------------------------------------------------------- +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware_plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index a8e378042c..8fa08b7074 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1130,9 +1130,11 @@ INSERT INTO `treport_custom_sql` (`id`, `name`, `sql`) VALUES (2, 'Monitoring&#x INSERT INTO `treport_custom_sql` (`id`, `name`, `sql`) VALUES (3, 'Monitoring Report Alerts', 'select t1.alias as agent_name, t2.nombre as module_name, (select talert_templates.name from talert_templates where talert_templates.id = t3.id_alert_template) as template, (select group_concat(t02.name) from talert_template_module_actions as t01 inner join talert_actions as t02 on t01.id_alert_action = t02.id where t01.id_alert_template_module = t3.id group by t01.id_alert_template_module) as actions from tagente as t1 inner join tagente_modulo as t2 on t1.id_agente = t2.id_agente inner join talert_template_modules as t3 on t2.id_agente_modulo = t3.id_agent_module order by agent_name, module_name;'); INSERT INTO `treport_custom_sql` (`id`, `name`, `sql`) VALUES (4, 'Group view', 'select t1.nombre, (select count(t3.id_agente) from tagente as t3 where t1.id_grupo = t3.id_grupo) as agents, (SELECT COUNT(t4.id_agente) FROM tagente as t4 WHERE t4.id_grupo = t1.id_grupo AND t4.disabled = 0 AND t4.ultimo_contacto < NOW() - (intervalo / (1/2))) as agent_unknown, (SELECT COUNT(tagente_estado.id_agente_estado) FROM tagente_estado, tagente, tagente_modulo WHERE tagente.id_grupo = t1.id_grupo AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 AND utimestamp > 0 AND tagente_modulo.id_tipo_modulo NOT IN(21,22,23,24,100) AND (UNIX_TIMESTAMP(NOW()) - tagente_estado.utimestamp) >= (tagente_estado.current_interval / (1/2))) as monitor_unknow, (SELECT COUNT(tagente_estado.id_agente_estado) FROM tagente_estado, tagente, tagente_modulo WHERE tagente.id_grupo = t1.id_grupo AND tagente.disabled = 0 AND tagente.id_agente = tagente_estado.id_agente AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 AND tagente_modulo.id_tipo_modulo NOT IN (21,22,23,24) AND utimestamp = 0) as monitor_no_init, (SELECT COUNT(tagente_estado.id_agente_estado) FROM tagente_estado, tagente, tagente_modulo WHERE tagente.id_grupo = t1.id_grupo AND tagente.disabled = 0 AND tagente_estado.id_agente = tagente.id_agente AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 AND estado = 0 AND ((UNIX_TIMESTAMP(NOW()) - tagente_estado.utimestamp) < (tagente_estado.current_interval / (1/2)) OR (tagente_modulo.id_tipo_modulo IN(21,22,23,24,100))) AND (utimestamp > 0 OR (tagente_modulo.id_tipo_modulo IN(21,22,23,24)))) as monitor_ok, (SELECT COUNT(tagente_estado.id_agente_estado) FROM tagente_estado, tagente, tagente_modulo WHERE tagente.id_grupo = t1.id_grupo AND tagente.disabled = 0 AND tagente_estado.id_agente = tagente.id_agente AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 AND estado = 1 AND ((UNIX_TIMESTAMP(NOW()) - tagente_estado.utimestamp) < (tagente_estado.current_interval / (1/2)) OR (tagente_modulo.id_tipo_modulo IN(21,22,23,24,100))) AND utimestamp > 0) as monitor_critical, (SELECT COUNT(talert_template_modules.id) FROM talert_template_modules, tagente_modulo, tagente_estado, tagente WHERE tagente.id_grupo = t1.id_grupo AND tagente_modulo.id_agente = tagente.id_agente AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 AND tagente.disabled = 0 AND talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo AND times_fired > 0) as monitor_alert_fired from tgrupo as t1 where 0 < (select count(t2.id_agente) from tagente as t2 where t1.id_grupo = t2.id_grupo)'); +-- trecon scripts INSERT INTO `trecon_script` VALUES (2,'IPMI Recon','Specific Pandora FMS Intel DCM Discovery (c) Artica ST 2011 <info@artica.es> Usage: ./ipmi-recon.pl <task_id> <group_id> <create_incident_flag> <custom_field1> <custom_field2> <custom_field3> <custom_field4> * custom_field1 = Network i.e.: 192.168.100.0/24 * custom_field2 = Username * custom_field3 = Password * custom_field4 = Additional parameters i.e.: -D LAN_2_0','/usr/share/pandora_server/util/recon_scripts/ipmi-recon.pl','{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Network\",\"help\":\"i.e.: 192.168.100.0/24\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"Username\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"3\":{\"macro\":\"_field3_\",\"desc\":\"Password\",\"help\":\"\",\"value\":\"\",\"hide\":\"1\"},\"4\":{\"macro\":\"_field4_\",\"desc\":\"Additional parameters\",\"help\":\"Optional additional parameters such as -D LAN_2_0 to use IPMI ver 2.0 instead of 1.5. These options will also be passed to the IPMI plugin when the current values are read.\",\"value\":\"\",\"hide\":\"\"}}'); - INSERT INTO `trecon_script` VALUES (5,'WMI Recon Script','This script is used to automatically gather host information via WMI. Available parameters: * Network = network to scan (e.g. 192.168.100.0/24). * WMI auth = comma separated list of WMI authentication tokens in the format username%password (e.g. Administrador%pass). See the documentation for more information.','/usr/share/pandora_server/util/recon_scripts/wmi-recon.pl','{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Network\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"WMI auth\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware_plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); INSERT INTO `tplugin` (`id`, `name`, `description`, `max_timeout`, `execute`, `plugin_type`, `macros`, `parameters`) VALUES (1,'IPMI Plugin','Plugin to get IPMI monitors from a IPMI Device.',0,'/usr/share/pandora_server/util/plugin/ipmi-plugin.pl',0,'{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Target IP\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"Username\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"3\":{\"macro\":\"_field3_\",\"desc\":\"Password\",\"help\":\"\",\"value\":\"\",\"hide\":\"true\"},\"4\":{\"macro\":\"_field4_\",\"desc\":\"Sensor\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"5\":{\"macro\":\"_field5_\",\"desc\":\"Additional Options\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"}}','-h _field1_ -u _field2_ -p _field3_ -s _field4_ -- _field5_'); From 08c6d782a4bfc1b463ebf31ce4daa5e3ac4e9639 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 18:24:32 +0100 Subject: [PATCH 199/249] Add menuentry discovery Former-commit-id: bc40f0bda89947a88a912484642aa3c89ded64f8 --- pandora_console/godmode/menu.php | 21 +++++++++++++----- pandora_console/images/discovery-100.png | Bin 0 -> 1403 bytes .../images/discovery_green-100.png | Bin 0 -> 1493 bytes pandora_console/images/gm_discovery.menu.png | Bin 0 -> 311 bytes .../images/gm_discovery_green.menu.png | Bin 0 -> 381 bytes pandora_console/include/styles/menu.css | 3 +++ .../lib/PandoraFMS/DiscoveryServer.pm | 14 +++++++++++- 7 files changed, 31 insertions(+), 7 deletions(-) create mode 100644 pandora_console/images/discovery-100.png create mode 100644 pandora_console/images/discovery_green-100.png create mode 100644 pandora_console/images/gm_discovery.menu.png create mode 100644 pandora_console/images/gm_discovery_green.menu.png diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index 1c369db688..0ed041d680 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -21,6 +21,21 @@ require_once 'include/functions_menu.php'; $menu_godmode = []; $menu_godmode['class'] = 'godmode'; + +if (check_acl($config['id_user'], 0, 'PM')) { + $sub = []; + $sub['godmode/servers/discovery']['text'] = __('Discover'); + $sub['godmode/servers/discovery']['id'] = 'Discover'; + $sub['godmode/servers/discovery']['subsecs'] = ['godmode/servers/discovery']; + + // Add to menu. + $menu_godmode['discover']['text'] = __('Discovery'); + $menu_godmode['discover']['sec2'] = 'godmode/servers/discovery'; + $menu_godmode['discover']['id'] = 'god-discovery'; + $menu_godmode['discover']['sub'] = $sub; +} + + $sub = []; if (check_acl($config['id_user'], 0, 'AW') || check_acl($config['id_user'], 0, 'AD')) { $sub['godmode/agentes/modificar_agente']['text'] = __('Manage agents'); @@ -200,18 +215,12 @@ if (check_acl($config['id_user'], 0, 'AW') || check_acl($config['id_user'], 0, ' $menu_godmode['gservers']['id'] = 'god-servers'; $sub = []; - if (check_acl($config['id_user'], 0, 'PM')) { - $sub['godmode/servers/discovery']['text'] = __('Discover'); - $sub['godmode/servers/discovery']['id'] = 'Discover'; - } if (check_acl($config['id_user'], 0, 'AW')) { $sub['godmode/servers/modificar_server']['text'] = __('Manage servers'); $sub['godmode/servers/modificar_server']['id'] = 'Manage servers'; } - - // This subtabs are only for Pandora Admin if (check_acl($config['id_user'], 0, 'PM')) { enterprise_hook('ha_cluster'); diff --git a/pandora_console/images/discovery-100.png b/pandora_console/images/discovery-100.png new file mode 100644 index 0000000000000000000000000000000000000000..7ec755e7eb6e72b7367a0e04122f49cc7248cffb GIT binary patch literal 1403 zcmV->1%&#EP)#DY#GL>-L7WMw)XH~`gRy@5y=Q%QK3@{Y!us^RUzS81 z5ybI$Ot60Tm>?Mwc6w#!VHD6g8AEow9slDo^ho!FY>yu?3%$}E8QJkO-Z1+U?1b!( zr|}$|x_>g3?9`+LuAD^}vK~X+iX(3V8q-BVA!~NDg}6g;T|ftp{2V5s*W42Fsz}H_ zm@Ic>@Ejvm{I^5|009m&a#etK@K_bHXmR94i-W%l!`iPp))GodfiDhLR8IH(siN;Ss~XN|5GQV@YF7C zLPVmbGgALpaPXZvcc=={wdHk%yc+})fsjh5JF!H_!SjG1sgQ|ksOx}`q^tTCL_)Mj z=ZW_qhb}$`8A8OU)E$|H1VO4w?Y%-wMrAHblx*hS#Z1Q-kUEBjqq0yWN(NVbR)~o+ z=XjBH^x(}F6oou$&O%(bl{>iU5zF0lW;;&$NJgSa!dADVG|1WZk&uOC=U7|rEC#_| zW&re&kXJ>8EOm(yL~MiEvSY5aiP0pYe`ZU;T%99k($dD#w2eN6y{7LUKD~G6kyq`S zk!c&gYFlyF=E|T{ax(c7OQ07H?EZBh6k@B>-YeODIjL@4@h>kH+Q|Aqh^$W??FBZ`D%hzZGD zPNefrhzLWI2sbiH3ZYQS9#JA>M1T-d3dsl%l9C`ql(0$cIPGd3NgUJx>sfpg0?B{y z?0y&N&)XUWg_wgEA#d4nIT#GSv4fXEF8R;w*g)|k-tv!QcX*bu`FvfY;(b%h3h6=} z+#HRC5_WADvuhp{m4cd(@1Dt6adV_vnPu1CM)EJTtoxBK1Qo)a_0+ILK4r&VB1A{6 z5Fbu(Cmgm38Rc#eQ?e$@(_;LM@D+uPn+Z}^zMm~7qK>(+{Z_&5xs2Ku{G=EOxp3$& zeu(JE8QDIA70e1LL)zTs2N(B0XSx!MNuh0c{aQS+n|9+`5>yItFxxK|$|!shBHEgt zdBzlz$x1MjQH#2EuAk8dAsKcuBpf^{giEE+!YqViqApWf!A2N($LHE}^@`Pn%BN_2}96VIPso zb7s&L(w4#IOd0bCKkjX*q)U^?yH literal 0 HcmV?d00001 diff --git a/pandora_console/images/discovery_green-100.png b/pandora_console/images/discovery_green-100.png new file mode 100644 index 0000000000000000000000000000000000000000..bcda80e4dd59f97c041d7377194ace1635ab5c08 GIT binary patch literal 1493 zcmV;`1uFW9P)tf;+&Ec`~lRN*aJv5ZpoT#&#; zyL)?kG9eM#_n%)ftmoc~5XO{l-srZUfcS^OApD>&u}wfc+ls?rHl={(*e>8KB6Z|+ z^HTZqk-o0Jef@n%3UP0zTogLj)r&+O4|G$PS>^Qo+vKv`rnqmV*m26xxULu!vTA`L zT-Pco#7`h^vKdv$HYvoeI&AKrfGDVgjWLFbAIo?GkX)995&2#scAyLJSQTRVOGFafcv4%tjg*i8bWHtv`! zd_*T}3T9k_K_R-6OR8XQ5)hbCd0m#Jqmq6C(()q_#R4K7gBubNI)i;v}cx0|h2Mh;suUH;&wyxwX02nInN*jzO2D88;ye$7i}~Q!oYOCf;ZmHd|Z>0 zpsw*qa2;E7cLRCe52XFkP@of5y-3utfQG@9@<7@b{D5AYDAuSVsvh7rLK0saxQ%j(Ah zqml+6ZDd+jffzIbh>C59FzQs&$D$A&7-Izgm9wgn90QPC6Gjm@455W;*1OVb_#SG~Pa1@Q)z6d^05Y%>Ja+aSy)5K;YHhW0

      sO>r literal 0 HcmV?d00001 diff --git a/pandora_console/images/gm_discovery.menu.png b/pandora_console/images/gm_discovery.menu.png new file mode 100644 index 0000000000000000000000000000000000000000..0f396c08c688a8b396bd2f6817ed999fa71774dc GIT binary patch literal 311 zcmeAS@N?(olHy`uVBq!ia0vp^q9Dw{1|(OCFP#RYBuiW)N`mv#O3D+9QW+dm@{>{( zJaZG%Q-e|yQz{EjrrH1%-Sl*E45_%4l%OE==l}nDTLEc<0B#1};vf8s&sS!?`1_yZ zf&(wJ@V~`P-yL)ubi;#=Z_QYjqZA?>Clm#>#Hovg#Y+4)fs#he|H*gVLa==%*0pWpOffQ zVx93L literal 0 HcmV?d00001 diff --git a/pandora_console/images/gm_discovery_green.menu.png b/pandora_console/images/gm_discovery_green.menu.png new file mode 100644 index 0000000000000000000000000000000000000000..f4a387c201e5a8b4bdba6ee670bf1a5df143496d GIT binary patch literal 381 zcmV-@0fPRCP)Ixn)RBi~Vu?8?cEZ)r!rAPEN`UtT5`}n9*;_IFKS`W#o zz4)tE!iKsxDJ(Jy75P*W(pI%?O1I=W2ULKJ5Np^t>f5KKvg0zxts!vX5%t@12P!_53d^a7i0_@vjLr*?kmceM=NL-AQm2i~Wq^9a~ zN=VwQcEmeLrGv1vgYZJhxul78{"value"} . '"'; } } + + my $args = "$task->{'id_rt'} $task->{'id_group'} $task->{'create_incident'} $macros_parameters"; + + # Depending of the recon_script type (name) should be invoked + # in different ways: + if ($script->{'name'} =~ /Discovery.App/i) { + # Discovery Application recon script. Imported from heavy server plugins. + # Instantiate configuration file. + + + } if (-x $command) { - `$command $task->{'id_rt'} $task->{'id_group'} $task->{'create_incident'} $macros_parameters`; + `$command $args`; } else { logger ($pa_config, "Cannot execute recon task command $command."); } From 6a43536b3363f79406eb3afab4e148ffc8ad4b14 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Wed, 20 Feb 2019 19:30:25 +0100 Subject: [PATCH 200/249] Discovery. Added App.VMw Former-commit-id: 18a9300f37163048bd99109c08c1228231426a59 --- .../lib/PandoraFMS/DiscoveryServer.pm | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm index 89f1c6919a..e43f1ca05a 100644 --- a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -234,7 +234,13 @@ sub exec_recon_script ($$$) { # \r and \n should be escaped for decode_json(). $macros =~ s/\n/\\n/g; $macros =~ s/\r/\\r/g; - my $decoded_macros = decode_json (encode_utf8($macros)); + my $decoded_macros; + + if ($macros) { + eval { + $decoded_macros = decode_json(encode_utf8($macros)); + }; + } my $macros_parameters = ''; @@ -254,15 +260,12 @@ sub exec_recon_script ($$$) { } } - my $args = "$task->{'id_rt'} $task->{'id_group'} $task->{'create_incident'} $macros_parameters"; - - # Depending of the recon_script type (name) should be invoked - # in different ways: - if ($script->{'name'} =~ /Discovery.App/i) { - # Discovery Application recon script. Imported from heavy server plugins. - # Instantiate configuration file. - - + my $ent_script = 0; + my $args = enterprise_hook('discovery_custom_recon_scripts',[$pa_config, $dbh, $task, $script]); + if (!$args) { + $args = "$task->{'id_rt'} $task->{'id_group'} $task->{'create_incident'} $macros_parameters"; + } else { + $ent_script = 1; } if (-x $command) { @@ -273,6 +276,10 @@ sub exec_recon_script ($$$) { # Only update the timestamp in case something went wrong. The script should set the status. db_do ($dbh, 'UPDATE trecon_task SET utimestamp = ? WHERE id_rt = ?', time (), $task->{'id_rt'}); + + if ($ent_script == 1) { + enterprise_hook('discovery_clean_custom_recon',[$pa_config, $dbh, $task, $script]); + } logger($pa_config, 'Done executing recon script ' . safe_output($script->{'name'}), 10); return 0; From 1156b29743ef6be428b4c14e778f50fd0b5795f2 Mon Sep 17 00:00:00 2001 From: artica Date: Thu, 21 Feb 2019 00:01:55 +0100 Subject: [PATCH 201/249] Auto-updated build strings. Former-commit-id: f760ca3d8b53ad47017d82e6bc2fbb298a69312b --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index a386a52e45..f2e2716ce1 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190220 +Version: 7.0NG.731-190221 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index b1c6ee397e..94f34a4668 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190220" +pandora_version="7.0NG.731-190221" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 3107ac2198..62bdfa27c4 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190220'; +use constant AGENT_BUILD => '190221'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index de2c0f3449..1da259f475 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190220 +%define release 190221 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index e046351d49..29f52b8786 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190220 +%define release 190221 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index ded90e67b6..77d78eedc4 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190220" +PI_BUILD="190221" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index d082626f9d..9bf66cb5c5 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190220} +{190221} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 6409b7f2d0..0dcf04a6c3 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190220)") +#define PANDORA_VERSION ("7.0NG.731(Build 190221)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 889216ad1a..7fd8ea3934 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190220))" + VALUE "ProductVersion", "(7.0NG.731(Build 190221))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 9463042f31..b98caca698 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190220 +Version: 7.0NG.731-190221 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 4dff45a12a..49e1bea485 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190220" +pandora_version="7.0NG.731-190221" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 1519fbde36..204a7e4ee2 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190220'; +$build_version = 'PC190221'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index ad9889d1b3..862e7088e8 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@

      [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index e64e4cb345..edbec0e764 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190220 +%define release 190221 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index acb121e249..1981838514 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190220 +%define release 190221 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index 069e8311c9..d6f5c866f8 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190220" +PI_BUILD="190221" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 67e58019af..fece0dc080 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190220"; +my $version = "7.0NG.731 PS190221"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 3046097bbd..9bbf4896cd 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190220"; +my $version = "7.0NG.731 PS190221"; # save program name for logging my $progname = basename($0); From ad3e2b88bf7d5ead87f43e2d741fbae7126f48e0 Mon Sep 17 00:00:00 2001 From: manuel Date: Thu, 21 Feb 2019 11:19:38 +0100 Subject: [PATCH 202/249] Minor fixes Wiz.Discovery Former-commit-id: 750cd3ab1902ed3eda9806aa9b505d5e4a1175be --- pandora_console/godmode/servers/discovery.php | 48 +++- .../godmode/wizards/ConsoleTasks.class.php | 133 +++++++++++ .../godmode/wizards/HostDevices.class.php | 218 +++++++++--------- pandora_console/include/styles/discovery.css | 8 + .../include/styles/hostdevices.css | 3 + 5 files changed, 298 insertions(+), 112 deletions(-) create mode 100644 pandora_console/godmode/wizards/ConsoleTasks.class.php create mode 100644 pandora_console/include/styles/hostdevices.css diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 1ac048a9ed..261cdd0696 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -19,10 +19,11 @@ ui_print_page_header(__('Discover'), '', false, '', true); /** - * Undocumented function + * Mask class names. * - * @param [type] $str - * @return void + * @param string $str Wiz parameter. + * + * @return string Classname. */ function get_wiz_class($str) { @@ -39,6 +40,9 @@ function get_wiz_class($str) case 'app': return 'Applications'; + case 'ctask': + return 'ConsoleTasks'; + default: // Ignore. return null; @@ -46,6 +50,31 @@ function get_wiz_class($str) } +/** + * Aux. function to compare classpath names. + * + * @param string $a Classpath A. + * @param string $b Classpath B. + * + * @return string Matching one. + */ +function cl_load_cmp($a, $b) +{ + $str_a = basename($a, '.class.php'); + $str_b = basename($b, '.class.php'); + if ($str_a == $str_b) { + return 0; + } + + if ($str_a < $str_b) { + return -1; + } + + return 1; + +} + + /* * CLASS LOADER. */ @@ -79,8 +108,13 @@ if (enterprise_installed() === true) { } } +// Combine class paths. $classes = array_merge($classes, $enterprise_classes); +// Sort output. +uasort($classes, 'cl_load_cmp'); + +// Check user action. $wiz_in_use = get_parameter('wiz', null); $page = get_parameter('page', 0); @@ -110,7 +144,13 @@ if ($classname_selected === null) { foreach ($classes as $classpath) { $classname = basename($classpath, '.class.php'); $obj = new $classname(); - $wiz_data[] = $obj->load(); + + // DiscoveryTaskList must be first button. + if ($classname == 'DiscoveryTaskList') { + array_unshift($wiz_data, $obj->load()); + } else { + $wiz_data[] = $obj->load(); + } } Wizard::printBigButtonsList($wiz_data); diff --git a/pandora_console/godmode/wizards/ConsoleTasks.class.php b/pandora_console/godmode/wizards/ConsoleTasks.class.php new file mode 100644 index 0000000000..9c9e060fdf --- /dev/null +++ b/pandora_console/godmode/wizards/ConsoleTasks.class.php @@ -0,0 +1,133 @@ +setBreadcrum([]); + + $this->task = []; + $this->msg = $msg; + $this->icon = $icon; + $this->label = __($label); + $this->page = $page; + $this->url = ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=ctask' + ); + + return $this; + } + + + /** + * Implements run method. + * + * @return mixed Returns null if wizard is ongoing. Result if done. + */ + public function run() + { + global $config; + + // Load styles. + parent::run(); + echo 'hola'; + + for ($i = 0; $i < $this->MAXPAGES; $i++) { + $breadcrum[] = [ + 'link' => 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=app&mode=vmware&page='.$i.'&task='.$this->task['id_rt'], + 'label' => $this->label.' '.$this->pageLabels[$i], + 'selected' => (($i == $this->page) ? 1 : 0), + ]; + } + + if ($this->page < $this->MAXPAGES) { + // Avoid to print header out of wizard. + $this->prepareBreadcrum($breadcrum); + $this->printHeader(); + } + + $this->printGoBackButton(); + return null; + + } + + + /** + * Implements load method. + * + * @return mixed Skeleton for button. + */ + public function load() + { + return [ + 'icon' => $this->icon, + 'label' => $this->label, + 'url' => $this->url, + + ]; + } + + +} diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index d9765cf5c2..b7a41afa58 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -38,6 +38,24 @@ enterprise_include('include/class/CSVImportAgents.class.php'); class HostDevices extends Wizard { + /** + * Number of pages to control breadcrum. + * + * @var integer + */ + public $maxPagesNetScan = 2; + + /** + * Labels for breadcrum. + * + * @var array + */ + public $pageLabelsNetScan = [ + 'NetScan definition', + 'NetScan features', + + ]; + /** * Stores all needed parameters to create a recon task. * @@ -92,16 +110,6 @@ class HostDevices extends Wizard $mode = get_parameter('mode', null); if ($mode === null) { - $this->prepareBreadcrum( - [ - [ - 'link' => $this->url.'&wiz=hd', - 'label' => __('    Host & devices'), - ], - ] - ); - - $this->printHeader(); $this->printBigButtonsList( [ [ @@ -123,62 +131,12 @@ class HostDevices extends Wizard if (enterprise_installed()) { if ($mode == 'importcsv') { - $this->prepareBreadcrum( - [ - [ - 'link' => $this->url.'&wiz=hd', - 'label' => __('    Host & devices'), - ], - [ - 'link' => $this->url.'&wiz=hd&mode=importcsv', - 'label' => __('      Import CSV'), - ], - ] - ); - $this->printHeader(); $csv_importer = new CSVImportAgents($this->page, $this->breadcrum); return $csv_importer->runCSV(); } } if ($mode == 'netscan') { - if ($this->page != 2) { - // Do not paint breadcrum in last page. Redirected. - $this->prepareBreadcrum( - [ - [ - 'link' => $this->url.'&wiz=hd', - 'label' => __('    Host & devices'), - ], - [ - 'link' => $this->url.'&wiz=hd&mode=netscan', - 'label' => __('      Net scan definition'), - ], - ] - ); - - if ($this->page == 1) { - $this->prepareBreadcrum( - [ - [ - 'link' => $this->url.'&wiz=hd', - 'label' => __('    Host & devices'), - ], - [ - 'link' => $this->url.'&wiz=hd&mode=netscan', - 'label' => __('      Net scan definition'), - ], - [ - 'link' => $this->url.'&wiz=hd&mode=netscan&page=1', - 'label' => __('      Net scan features'), - ], - ] - ); - } - - $this->printHeader(); - } - return $this->runNetScan(); } @@ -257,53 +215,77 @@ class HostDevices extends Wizard } } - if (isset($this->task['id_rt']) === false) { - // Disabled 2 Implies wizard non finished. - $this->task['disabled'] = 2; - } - - if ($taskname == '') { - $this->msg = __('You must provide a task name.'); - return false; - } - - if ($server_id == '') { - $this->msg = __('You must select a Discovery Server.'); - return false; - } - - if ($network == '') { - // XXX: Could be improved validating provided network. - $this->msg = __('You must provide a valid network.'); - return false; - } - - if ($id_group == '') { - $this->msg = __('You must select a valid group.'); - return false; - } - - // Assign fields. - $this->task['name'] = $taskname; - $this->task['description'] = $comment; - $this->task['subnet'] = $network; - $this->task['id_recon_server'] = $server_id; - $this->task['id_group'] = $id_group; - $this->task['interval_sweep'] = $interval; - - if (isset($this->task['id_rt']) === false) { - // Create. - $this->task['id_rt'] = db_process_sql_insert( - 'trecon_task', - $this->task - ); + if ($task_id !== null + && $taskname == null + && $server_id == null + && $id_group == null + && $server == null + && $datacenter == '' + && $user == '' + && $pass == '' + && $encrypt == null + && $interval == 0 + ) { + // Default values, no data received. + // User is accesing directly to this page. + if (users_is_admin() !== true && check_acl( + $config['id_usuario'], + $this->task['id_group'], + 'PM' + ) !== true + ) { + $this->msg = __('You have no access to edit this task.'); + return false; + } } else { - // Update. - db_process_sql_update( - 'trecon_task', - $this->task, - ['id_rt' => $this->task['id_rt']] - ); + if (isset($this->task['id_rt']) === false) { + // Disabled 2 Implies wizard non finished. + $this->task['disabled'] = 2; + } + + if ($taskname == '') { + $this->msg = __('You must provide a task name.'); + return false; + } + + if ($server_id == '') { + $this->msg = __('You must select a Discovery Server.'); + return false; + } + + if ($network == '') { + // XXX: Could be improved validating provided network. + $this->msg = __('You must provide a valid network.'); + return false; + } + + if ($id_group == '') { + $this->msg = __('You must select a valid group.'); + return false; + } + + // Assign fields. + $this->task['name'] = $taskname; + $this->task['description'] = $comment; + $this->task['subnet'] = $network; + $this->task['id_recon_server'] = $server_id; + $this->task['id_group'] = $id_group; + $this->task['interval_sweep'] = $interval; + + if (isset($this->task['id_rt']) === false) { + // Create. + $this->task['id_rt'] = db_process_sql_insert( + 'trecon_task', + $this->task + ); + } else { + // Update. + db_process_sql_update( + 'trecon_task', + $this->task, + ['id_rt' => $this->task['id_rt']] + ); + } } return true; @@ -408,7 +390,6 @@ class HostDevices extends Wizard } return false; - } @@ -478,6 +459,25 @@ class HostDevices extends Wizard return null; } + $task_url = ''; + if (isset($this->task['id_rt'])) { + $task_url = '&task='.$this->task['id_rt']; + } + + for ($i = 0; $i < $this->maxPagesNetScan; $i++) { + $breadcrum[] = [ + 'link' => 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=hd&mode=netscan&page='.$i.$task_url, + 'label' => $this->pageLabelsNetScan[$i], + 'selected' => (($i == $this->page) ? 1 : 0), + ]; + } + + if ($this->page < $this->maxPagesNetScan) { + // Avoid to print header out of wizard. + $this->prepareBreadcrum($breadcrum); + $this->printHeader(); + } + if (isset($this->page) === true && $this->page != 0 && isset($this->task['id_rt']) === false @@ -698,7 +698,9 @@ $("select#interval_manual_defined").change(function() { // XXX: Could be improved validating inputs before continue (JS) // Print NetScan page 0. $this->printForm($form); - $this->printGoBackButton(); + $this->printGoBackButton( + $this->url.'&page='.($this->page - 1).$task_url + ); } } diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css index aebb0a3d0d..2bc41163b6 100644 --- a/pandora_console/include/styles/discovery.css +++ b/pandora_console/include/styles/discovery.css @@ -94,3 +94,11 @@ div.data_container:hover { .arrow_box.selected:before { border-left-color: #82b92e; } +.arrow_box { + display: inline-block; + position: relative; + padding: 14px; + margin-left: 20px; + margin-bottom: 10px; + padding-left: 3em; +} diff --git a/pandora_console/include/styles/hostdevices.css b/pandora_console/include/styles/hostdevices.css new file mode 100644 index 0000000000..461327705e --- /dev/null +++ b/pandora_console/include/styles/hostdevices.css @@ -0,0 +1,3 @@ +/* + * TODO: This may be at hostdevices.css + */ From c385a3191f5ff71ccece04a8f8cbf68902f6ef55 Mon Sep 17 00:00:00 2001 From: manuel Date: Thu, 21 Feb 2019 11:21:56 +0100 Subject: [PATCH 203/249] minor fixes Former-commit-id: ffb62390a5edaa158507f253cf7fb23c690f8fcf --- .../godmode/wizards/ConsoleTasks.class.php | 133 ------------------ 1 file changed, 133 deletions(-) delete mode 100644 pandora_console/godmode/wizards/ConsoleTasks.class.php diff --git a/pandora_console/godmode/wizards/ConsoleTasks.class.php b/pandora_console/godmode/wizards/ConsoleTasks.class.php deleted file mode 100644 index 9c9e060fdf..0000000000 --- a/pandora_console/godmode/wizards/ConsoleTasks.class.php +++ /dev/null @@ -1,133 +0,0 @@ -setBreadcrum([]); - - $this->task = []; - $this->msg = $msg; - $this->icon = $icon; - $this->label = __($label); - $this->page = $page; - $this->url = ui_get_full_url( - 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=ctask' - ); - - return $this; - } - - - /** - * Implements run method. - * - * @return mixed Returns null if wizard is ongoing. Result if done. - */ - public function run() - { - global $config; - - // Load styles. - parent::run(); - echo 'hola'; - - for ($i = 0; $i < $this->MAXPAGES; $i++) { - $breadcrum[] = [ - 'link' => 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=app&mode=vmware&page='.$i.'&task='.$this->task['id_rt'], - 'label' => $this->label.' '.$this->pageLabels[$i], - 'selected' => (($i == $this->page) ? 1 : 0), - ]; - } - - if ($this->page < $this->MAXPAGES) { - // Avoid to print header out of wizard. - $this->prepareBreadcrum($breadcrum); - $this->printHeader(); - } - - $this->printGoBackButton(); - return null; - - } - - - /** - * Implements load method. - * - * @return mixed Skeleton for button. - */ - public function load() - { - return [ - 'icon' => $this->icon, - 'label' => $this->label, - 'url' => $this->url, - - ]; - } - - -} From 4148387c506a19ac2ff0d1afacf440b5ed669dac Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 13:05:48 +0100 Subject: [PATCH 204/249] Updates discovery Former-commit-id: e99072a2b7a1ddd528698e12bdfe75b0b56ba25b --- .../wizards/DiscoveryTaskList.class.php | 2 +- .../godmode/wizards/HostDevices.class.php | 30 +++++++++--------- pandora_console/images/wizard/csv_image.svg | 4 --- pandora_console/images/wizard/hostdevices.png | Bin 0 -> 1152 bytes pandora_console/images/wizard/hostdevices.svg | 4 --- pandora_console/images/wizard/netscan.png | Bin 0 -> 9083 bytes pandora_console/images/wizard/tasklist.png | Bin 0 -> 855 bytes pandora_console/images/wizard/tasklist.svg | 3 -- .../images/wizard/verde/hostdevices.png | Bin 0 -> 8256 bytes .../images/wizard/verde/tasklist.png | Bin 0 -> 1038 bytes pandora_console/include/styles/discovery.css | 1 + 11 files changed, 17 insertions(+), 27 deletions(-) delete mode 100644 pandora_console/images/wizard/csv_image.svg create mode 100644 pandora_console/images/wizard/hostdevices.png delete mode 100644 pandora_console/images/wizard/hostdevices.svg create mode 100644 pandora_console/images/wizard/netscan.png create mode 100644 pandora_console/images/wizard/tasklist.png delete mode 100644 pandora_console/images/wizard/tasklist.svg create mode 100644 pandora_console/images/wizard/verde/hostdevices.png create mode 100644 pandora_console/images/wizard/verde/tasklist.png diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index e135c80672..0a7fa9b8e5 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -49,7 +49,7 @@ class DiscoveryTaskList extends Wizard public function __construct( int $page=0, string $msg='Default message. Not set.', - string $icon='images/wizard/tasklist.svg', + string $icon='images/wizard/tasklist.png', string $label='Task list' ) { $this->setBreadcrum([]); diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index b7a41afa58..ef98b09d3a 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -77,7 +77,7 @@ class HostDevices extends Wizard public function __construct( int $page=0, string $msg='Default message. Not set.', - string $icon='images/wizard/hostdevices.svg', + string $icon='images/wizard/hostdevices.png', string $label='Host & Devices' ) { $this->setBreadcrum([]); @@ -110,21 +110,21 @@ class HostDevices extends Wizard $mode = get_parameter('mode', null); if ($mode === null) { - $this->printBigButtonsList( - [ - [ - 'url' => $this->url.'&mode=importcsv', - 'icon' => 'images/wizard/csv_image.svg', - 'label' => __('Import CSV'), - ], - [ - 'url' => $this->url.'&mode=netscan', - 'icon' => 'images/wizard/csv_image.svg', - 'label' => __('Net Scan'), - ], - ] - ); + $buttons = []; + $buttons[] = [ + 'url' => $this->url.'&mode=netscan', + 'icon' => 'images/wizard/netscan.png', + 'label' => __('Net Scan'), + ]; + if (enterprise_installed()) { + $buttons[] = [ + 'url' => $this->url.'&mode=importcsv', + 'icon' => ENTERPRISE_DIR.'/images/wizard/csv.png', + 'label' => __('Import CSV'), + ]; + } + $this->printBigButtonsList($buttons); $this->printGoBackButton(); return; } diff --git a/pandora_console/images/wizard/csv_image.svg b/pandora_console/images/wizard/csv_image.svg deleted file mode 100644 index 1e82511472..0000000000 --- a/pandora_console/images/wizard/csv_image.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/pandora_console/images/wizard/hostdevices.png b/pandora_console/images/wizard/hostdevices.png new file mode 100644 index 0000000000000000000000000000000000000000..bc60d6125c71058f0691fef3a4382fe649848f2d GIT binary patch literal 1152 zcmV-`1b_R9P)B_~< zyBEz)TK*ke$MM9M*?>&J%gL1Gj~;Y!nA<+QGiCX(cMYuHs4QG(patM7)?8nDFJn!Q zkr~>7Ox7b2#;M+f>zdL9)gJ#M3t?*Vj!R63M;HRO@k|e&Zg>3hepgCgZ%1x&lKB84JBS1wzQCr7GtfH767`%2w3L&snH^?#UpnV z?p*1~bd5CaC1}?#;<84=-oZx$GytW)P01!w`7vblq2ca+plEca69TIj5WKSj4o(9nXId(lVIvons9jy(HA z(TY@jd9EH!kc)d=CQ@DCm#(H+-0^|*R$jL@Q4+p)9RB80N2*&gunjt4(1~P)uDtVI z6<2%mwaGn=yyJc=%dZ7`+R`5@+MwhQ_tkAQt}5CFoqLGRK+8IqN|p$qElY=d0veQb zxCA<^XaU+%tSef8wiK~s^JI-q2E>epA5&pz@13!zq-wG+y&eQ?$%ku|OHsZ1KPlO9 zhFcYT0ey2W=}_&QYV%x&ys8QLZ@EF|Zs4}1L$-N+kdC?1Y4VcqsM6Ru=#Xn2vaMV9 z)ZU$(>xpk2Il$gI8n%11YUi}8cU;3Zs+qVr>zHlOeu+lw*t^KWc1&CYjjP~21zl$A z>Sj=bEwkE|j#IX-c)v1}656_G=zq7~+v(y4-=o8d7SaKG*Dufs>ujvNPR0(}sz$Sa zT}ZE8o6+D!dfJy9zG;L|(hoY_3Xn%4#&A*WY8c2(Mbx90BC>)Xaqn5Gy - - - diff --git a/pandora_console/images/wizard/netscan.png b/pandora_console/images/wizard/netscan.png new file mode 100644 index 0000000000000000000000000000000000000000..c90f4ddc5da30015144d716d5611d9bf2be96c69 GIT binary patch literal 9083 zcmch7cTkhh*Ka_Oj_{=;2sV1Jp@Rqrk{}=*DIyX;AP^8j2T@eoS5b)}(tB43JyZda zlF+3$Nk9lKKI{QIN7OzC0AuT@e0_yP@V11TolAK>MzrC>FB8{0b-vjjbF6Zaxf3c?ZVC-Aj`}Y14Y(W09%U~@m zdQ({iXla`q`z=$S1MsspvsQ1)DbGigb}h2}h2n(N)=JxkS|ngJOXT<#?P`{F`{zp} z*K9uS=+L(d;c_Ve3=~>`n=zFQ9;w}^2Rwicy@A}MU9H+(=*P;{y@hGFhLblR?QBd| zFP+J@0uurK8)WBjbH}FVL`|K>Oz+GT38q2Kyx)sb=zj9nJWuCh)gi%5hpUqlSs8UY zWKOqm=LS&cXm6x*Lei!JRd~>#?M;{S`Gw+3JVpTNaePF`Oqi&27JBvDOk9pCODavq zSw{QpcWS5b*)0rM{8i-)>b9l_;~*z;NU7=hIN9J{OZbsR`9IMw4_9+j-a2GPSkKh^ z=hg?V4cpDPWOl+znGOyfrTzs%fAZ7nmRrs*EFfMPv|0JeSj@xqW^L~z(s{k?T_fRa2Hn&M@@#N? zu3oooub^8Y)1c$D=02UF}NC58gkQrg+icaE5 zz*dbtfv$Q~W!bev#2zqp%ii4W?JrNs_l09Xo1U}1dF3H$+#QbH^5AdrM9+3Oxh69a ziI2N`IlB8T_ZS0Tu*Wkf{vq+pfu+2s2B2o_B2j3%LA|&e?&U**!sR5t0C2nZ1m0G! zinE2gJ}_cU=4)kTs;q&W_rUCi1LyXm#jh6);mMpCy*9y{D36!E0E8IQj_}UP+`Ktx zecaRe_^@U{)5X^O!pN zCWpw89XAR9WsT(kJl%E$Y4;dT9SE=j2HC0)%NPc8Y4zy_=>Q^XK;WwEu_B~|7SPTB zpvcmQ0_ed2HWVOwf#(0+#l5L-0ND19I^6Ax3|(6x275a2k;iK}r?bJiDe#PFvZ}R>$=GSnT5ok}35f^jwI*ujxD28D>H9@! zECMY;5!xiuj4K0W3QtJI3T{JrBR9n>Q!+Vcfu=}8scyK>`bF^dj&rNcA8`vbV$yQU za6Boe@w$k+{orB){s+Yei#v+31wgMq&r+oq#eq~m*^~!rwRt!*DDSC24}@e)`W^Xd zkGkH2Quk9rR%FcM<(BJ_@v4L#91V+qI;tS_9Fk^)^=C%`6yu-9{jjDBj<`)cDNxj< zC`foAG0B@J5pJ5aqHR*>0s16#GEe6xMLo)x#q>sFhKNHugB-|5(F^&?U7#WTXKo=c zjcD5~GFN-6l;o9m2B@`q9#FV7O%KO5k# zEwY%8jU}&-DF^a;i>!}1sR>#8g;8fcz%?Y9U$l+EidKJg%C`_8fFkqcWeRq0-9xw8 zE?WfTR?^}9OOW{g=n?=e%8{N_{rJvCjkzWZrvmCo#3s3QaU0tdXUKI z^@Sd+n^etd#$98k!CFcQ`Tft!sytjSO@A8@$0SAUb~XK_cq=Hi(m+Q?-;<44j_66E zICVQi+uo=;ttdcoRg%)c-6|;1hf)(QcA0^FYh<#0y)(tm&Y!Hc2DHBjtmTx6JI~%n zUF3{c)|{p-&>$*x!jD$0xs(S>(!EDc%B`!MAO8LuFk!iquAyODtDw0zyS+s) zp+ygzH9zBv<$!p)w16&VB)D}76z-6$>=r*qZCRUdn#j5?^#6m>ZMsx#lbcd&VHkp+ zx3MCTm^^IJfvnU&8T;r{RzabyMZqb<<{=eP7kg`S0tZc*P8l{2MwsQv<+R^uMRBoh ziLCO$l8haZm#PLwW;niRaB*A-L9^*uO(6z&vIJ6JZ{|3JHE;*akXig@2f~4nZ%EgilLly+MQA*1l_GB*U0`{0zq<8j}Ms1g7gC6w# zTCE9ARDG3933ubigRMxOOEoWhf@(gDH!VS0evN&))<_T1H=_}iDWe|s*Q&F0VBJ+b zjF)D5kSz`@UV9mI+ZlQ+IK6Kk-A$TKs@?xiG;vA(4OXlhiS*+ht9WVm$;dNP#W9;k zbic7mhQQR1N#-$_k!vXUJ=PDwpvu;8=YDDpb1f*4W-F`HXTuM3f!WqLqng!aCrdFOL?ht}EW~ z9nW8Wu&LH4B8Rm)N%Y8^Hi)ne<>T(=Vgh?zMf$({W$_Q;pG8ir)&vhc#(QnpDW486 zPQ~wvz6RQ1YNmRVUe!Zw3ALEV%}8ltQSrRB!==X!g>6#Gx~ec~rJpLul|F$BHDuZ1 zS6X_?>ah-#cPw?1DDzc5lox*FV$GjpPMVf+g*X4g4!sY)6r~-@kv(bU{goSHw>UZ6 zHY3AdwH*-2+Gr_owIkrM-oZSGeq{EPAKja6pTBSyVi6F6XA0Ex^BxQI2hsN{c02^J zw~H$kTZYsIO80luiO>&j#^Lp|?cgDsnI78aF$}S(UGYz83f4#^!LlFEbP5FRaUE?l z*q9?*mm5G&3rM%YFW^Aen{0_rV{GScjbE?>HzFk=mrK)>J$@n2JbO|y**eDMYeu1) z|JjrB()`B?c%O$yy3DhGrzlDJg97yx@AwK%Q#)+fXCi(tq=Z~wLycDsg5upbc98_gz zYN&r=9zIA}g520R+`^;^f&&!yieRATNJjxJ)lpbT%aZN)JX(#n)HELH-s#>3)uBU% zx`rwJ?KPzazl8;VUud?NbeXW?G+t(W=V9rm6OpBBpL~gP^u6Z;t5F(pBuEXkU!Bf% zyYE+C@`jP(QX;Gpf8Bf%a3t_!U0hc+pkan9>#t#=-s!>Kr|fkjwdVVPqtnRr;_z!L zQ-{cE1DDu^yg~FpCvrYVc2G?>_cA}$(kv_>RZZ=?TZuvdn0l*MoJ(!5)4# zlp`*u@YnR_13SOqQ`<|imQW`gIISSC@1${L$c=@5aQrYNX6r2H#mZSu?qB)xudCPp zc~t$M!ByGS2y!D(^Trm*sV7-k82I@`OavVpD(Tz8BE!Whbm$^Cw?}}|uKSU&TGhFt zy|F4!M3N#FSGTTqsPr^vp1%1vK4RvwzALz3?P7VN+@NrM<@^vOG1(Y3hdV{M|P1pS119 z7;jXrJpsc#p|UkrR;vc?htz!359~uV3Iq9;PYTU$0(rE$w<52mGm*5F%MAsU2hlZ{ zpP+_xWPl!Y*Fi(M-qsIYYR|0QR zZFnxG`4UfS;F7G)iBVADr16;6DjxFiG!0=K_n{h~2KOYQbwJufg2(7oQ19#M)1&$FEV>J`zwa9~)R?)?Xvd zzKO<;&|32$&X$Un@6Uf$ATRTS=7!>~-kKIi{8=HI$ipL-U8m+&CNTU` zS6(mNnoytcIz3vt!J)`v0M$0;Nv4#xh+vwhx2<;%G^s8H6vJpQ|s9l_rR(&f4hp;pJ|=vWI>)JOf~W}pfJ}Q zTnE*|EAL!qQi}&YA>*SgE@7_4ukE1VsC4B+-bjOsJDbgk}wgnyu~| z@|29Z@l@W3Up*I}FV#1xP8?@RDwr{s?93{NfmdEu&5U39=-_^h9)}+;tyNoWcqA2> zy$*NMJr-5To^(V%QdQDv4Nvv{9OT)sx&nyseixt&{#ob5yWs3`a>UEBo76@yAZPR) z1l*ey3gVUI#(hYC5ms6hEc(r=)u>xal7&> z4_&0zhFH&{=RST^UNO`qR5|&&@EIIEJGLy*0ig#tl@WC>MW!2nVS9d;rDq(r&`%h_ zUk}XYpcdJJxMS4F1v4{LVj^U}9RQ~{YwtyMDk9HnKYs6cmJ(J0A6!;5oqoFcAh0^OM}-<% z(p5)N2=H+VvkDpi;DH*rg53`fp0nZq$p7I;Kw{!C9egPvgf+BobK zLp0bEfn9WL?=pvJd!hQxl}MlIs@1~`46q0i?o-jEli3BI!z?$jvZF|x46ksVlWbI0 zc@FY(Xg6lynOG|FGz+ojK&tY{+iC@iP5lsjd!s&BAbGIfFWbNU%{C{JM`KQ-N1f9E zwuxKx#7JW`Xhl0LAx@_Vqxc-727Pm-6AYdn@;zp%|kkKc$@j2-R!9A~PC-p(Kv8lT}GNeV4y?LAB!VrD2nRvd?!plXE@KLj|SYy0*NT%D_qNR8Gu1X+-+nE0wBr>R-`V zgxvsshDk4nX57*^|J8I{_C&{7SV&DWazuToD@cDi{1-y`bwJAc;b$W4DJa5eb=yh} z3v7yrNlaKCOFm!h(st%TddxowdNPZ{glj*;F8Y=HG`?qD_$Zd8z4ufm@ucVSK=5^4 zqnL)dysw{?)oi93eOFzLis4_bG#C{A+}_Zj1TCRKjMd>TBmiN3{lDh^611 z=RbK%9d`E8g1>x>O+BW8jKqs?5F*$RD_>+^Ts9-AN|`tk6yga)#`9O!N)y)i3Bui% zA^uA1511`&CC@P-(3@WDo?+Q_uK9$%9aaT@_7s@NtNWuzu}-0|h*QD*-Ph1aC%y6! zDOWGl=xR=V#AAk1^>K;IN7V+z-CCSuNU6bWdO%$%^7oA^B=Hl>c>k@uZsQ2=>|9sI z9iu6;>7-NpeFP4(H2-3RPW^cF0QJUA=^mlaaA)glb`Y=5sSDNCgzOGkmJlEaT&L8` z7-7Q)#NR$j^x?Oi1u8g=K!K#j2Y2roLN0DP^B&N+-^8XB!IO~zMsE6HOou=XE1j+6 ztFLS3J9E-GOz6P~sH*_#c~80wZ_lN@GPzmVWRRbTu)}nKd}!pgMLsNcLgJKOmb+%% zjB(@lY(&y;5EwV;Zl}QfiRj}6UYPn^%UHz#bmR2 z#CbIG^P~|4C$Vrsg|Q!-I76vFRTB4Asg;85(j8{x!*h2((vt|mfD^CHz=6`&N)9kaHrbsKs5uTcFz7+?3%dMqE zqu^@=J!^WID(4GIL<+|F&}9`V4&nd))EjW1V1^IZH@u*CIfyq4DYz~of1D5Wu}-6Y zz4MMGnu7g#glq;$-DUOTE{nbaq>}k3W7;5iJZnZy|6hu*QAkCwu;v5_L>clz_lS?tFgb_>srL=2^9|_tO zi!Yd~W^vI1XZb9`f6W|GD&1y^_sb2A%PAUC$r&Cc?j`=zQkuF#D^rB$Af3ljEYBZ7 zC|#rF2MrlsnO6dcu=2}7lCd*Sh!kvjoJw7jJ1ZC#Z9N&MVV@Z0;6gE>fEL2+FnRBK zBhqOruiW|Z>uv>zEVC?S3;WOyeGzzOz&I4iio5FR(4hM->)Tw{+f7I0n?NdizML0J zzt}!;=3(}R(-rP66AoBzQ`x*jB( zq;Z}6rDsyKk5^SME+|x#Bu3L8h^TJ45k1~;9hg$K!UFIrA1;`p5IB&M)q@Mwu2~2i8Rm7O!0{%5=6^k^J^#4y$tE7S2sP7XhYy`gEC&j_zGipJ=NF z^(KWW>5u4fD|EXQt&VuGERcNe|E>5rp=PVafBDrgP1cw;a^_f#mj@*aKG`&fNds!E zYATXTePpDizc?+MI=|*8oO|j7tyg0|NC3)}vx9=5r#j$uD~;NQgJD$IFKS)EyQN+f zm7S%sh4Anxvqz1A#fKZ?()mof>!;@lvfUA$I(6O2R|fZ3!bD5+Zw@)G+lc~vN`1hP zf-{ihMm+;t_qcj%Bg{zr5{}>F_tcBxSVf!rWbnz9XlA%VF@YVRWcb_e_f-89erK-6 zV+`2YT`wDcwm*S=*daX#kn7bGM4wFvQyxyPVvcs zCwidT3zb`=73AmVU;Eq{UcPa=GQ&{iajmv>&0CQ5Dc%`iYO@&=m38oc4P9Q-(oX-;J@nZRW2< zs}yc7{e<5WAXgfa#~Y*8b?;x^SUAjrgV^7$c0VMUdXKV!x|$Yo?=EF24BfgK0|)jT zA39a{una#BL*h_sKo1t|_U3F;Cw|(tDim=}R1*V`IMKbf(dyKSB8mwAj2PbM-?aO# zNPQvbl8Z zG7f77*ghaC;2omgPkhcuzd|@OP63V7y}J{5n+{UO#(!}j#TorAR)IP|Rl=Xd+Gp{C zboccpSI_u|O^ieK9|p1PLLHfy8Q-=PS8 zTH#tibUh|GWE;Oo@;#j^Ai=Htg@NMIN+W%x^=>x&HFr@X*pUWIz8K^L1hAt}lE9lvCxsC{ z!NFuXrEE``M=g%wqyg2gkCJYLp*E*SFQ>&94{)lJz-I+G!1*3BU z*-#&XVyFnpv8iB~eeiO}6Fm&KfSn|C$+M zcc2QXe{VuOHYL2CFJuCjDNup92wQREsjk`=i**x*25q+}>E3(I-Fs%D^<=YYiIVZf z#Q1L_Jz9_dlvewmj$1-~C8cRZ2`pIK>+T!6+X&;;sOQ0=14j%@JSn`a-k&ogREps$ z%odQjhmYyOGXJ31kzZv9pGQ&*Ublpi2XAeUc3)tg6XlddrG%cN49eJ1{nDBfZy7+f zIBIsJswLzPC}H7lNG$G&(_V@DaZ_3D;6D>gBmWM`422z(;O;^#tV1?ew!{D38qO|0 z2#_Wn9{?mFa*bVX3^a%ALH35c=Mh$gTO(_`r^y?HHE+28A9 j+^POw_fd)}FJ#*Qy#aZ7?Ra4NUnye)@ZE|#F0ua$3gD^8 literal 0 HcmV?d00001 diff --git a/pandora_console/images/wizard/tasklist.png b/pandora_console/images/wizard/tasklist.png new file mode 100644 index 0000000000000000000000000000000000000000..3250311b69cd02e87ea89b967c4579c3635a3c77 GIT binary patch literal 855 zcmV-d1E~CoP)4Z;B|L3iDS72Em-?YuG;7P8F@p0ODGeUgQQ6wG`K z&u`=(6QuwE0Kh-v@pvQ$CJub?EI82*Z~7=Cr&*TG(5%#_fRcsLU@-W#+wFe$UG&F* zk_(2+XQe&|mYnP3)up!UhaVC9l<_Wfx!hQb)`OOrI4#xM?HQ6MRe#rjyjBwVJj+*?}Yrt1A$_v~KUT$nQ0^Qp&(Y zA1?tU7w5i<*|Hw{%0+b3jBUCQw36J*1&firwrtOk+-7BHYVyko+1@1U^WE!*$B6v> z)Z>0_EjsXpuj*WXBJ4bFY+BfpD?|Mvxw!ytIw%*(wU!R6C3s2ps@#19sL6}iS~~GHE9;gvdwBUGqEh6!~aFh}_4CY|2N!pE2N8l6%+Qm9lm@k~>%# zny<0VFQvRlHb1L)ipZbWeDo>V-ez*7`RFfIt*`US&_r|V%82iB5#vSBYH?+oj~3at z>JUbkE9)dcO^z)eo$|XK00000000000002+gWP0|eg8V&gx)`TlV#a0n#1oO{gr(5 zo-Xpy3G?|f^U=={`;_s{UGvd$F?&>p&8N3#NS@e)OG-RPK5@l|ghNxS(osq$$rhF} z%evY>x_34DzT%VWV*lvH6*!$+w|5P-QY1c@uLm>PM<1nA3ZglP7MG4NxCq}M=x88?z+3s=lUDrWQ}tF=zcH3OR|ebd=*IY%zPzdSp~9x hGynhqTp0fZ7yvEOZlM7Km}CF|002ovPDHLkV1hJ7m8Spz literal 0 HcmV?d00001 diff --git a/pandora_console/images/wizard/tasklist.svg b/pandora_console/images/wizard/tasklist.svg deleted file mode 100644 index bac9f75f6f..0000000000 --- a/pandora_console/images/wizard/tasklist.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/pandora_console/images/wizard/verde/hostdevices.png b/pandora_console/images/wizard/verde/hostdevices.png new file mode 100644 index 0000000000000000000000000000000000000000..8b8fa022ecc04430bae4c1a71e1644de599fc660 GIT binary patch literal 8256 zcmd6NcT`i`*KNQ^2MZz!A~uRhQ9wX26j2m`fb@=tA@nLBAYHMbq9P?Efb(AG}zYz>#CqGsWQT^piWLPYm4cpZM8&As}jx-5(*&X}a1X5&8(*$NrwJ zh?@|I;JD^(HN&Sv^CN0+1$>ePm*lxGx(Lb14PA>%>Uyv6JriL^`xO_F#&PZCb&+l8 zJ+qguPqDsc_gJ=Ex_@O_TA6|OQidAeZ7z=N>F3nYrhMa;5)(TSjalU{KDs?8Ct5?l zmVWh9!>-ahZ{i%cd`$YW^vXOk^f-@dsj2Cz@(L>SLpZ{P*jVs5rFn)88^C9|52VZ${g1 zp6NKo(d|R|1NGI(MwP|g`EeQe)pH7SpCx{jU{dpB&+j)im^`k*4@n8qOje9$#Gx$sL~LhXsROkz zc_zuCQ1)~YM#eHOi-i_*COn}%*ycuBb%07VO}vKLd9uZ=xDy$A{xPX z-wf6A>HKYB+VBo>4>naIF2e{#a@sGd=x=#TyCk%|?EJX0AH~)`gRf1EkXDax}p&# zbo7i`?5y41FMmQLlUaVTFRsux7-GPSp}R`#Ggjubs-=tX;C5bg;9a*d3aTE)4{*yZ zM+@~S}OU`z&FdW77e-_9qYt&pZtoZP?{`xrulvDa@G2nomA;R=1r2aWBC|7;;5hB};PgP>j&)LpYu`1IchC~! zwV~zh)yc9QCRGn#a@a`p8rK2aZH#flZKQ6L!R|icq!W=dt1Yq{5+0+WbU^0rm&sV4 z_WbAWWUt}pNV)gMF94B@wbHk^Lw1%;=?NWQxszF`-t5TjSW!rLsgYOR@?@iw3Ew9H zA=MPX-F@pnN_7EhYplgw?GN}a$=Ia?O^&>doW5UiWNU{`k*bm44;_6xE^V3Eb%xsI z(*1@$)2Ol#q5@&T|BAGaM4~TIqL-jYF}Dn!f*a%7YC5tar`wi>^8*XPGZsx*+xMz_ zBc8gg*O&m1rjl>2&PEn2Ctjc+Yi%I;6T>GQ6+dK(_}uFam-Qy_b;K@OaaBEg$5A@) zSDDw_XB5HUtWgXq36>UyeYY^cC+)5(tc|l_r_SyDV(l~*luHn zkEGuCkV?)QyR5)a-})Qj>l_=1KAl*gBx@3hjP1;qF~nYG1cR}}k>>j$@VJD>ral;a zXG+1hcfa?nUhe9Ht2R33#p;X(FAZo5%W@}YhMcvC2DkQX?XoALa!x1LtP`7FKMO&` z;W+yGe}DvDqT#WKJz*d71d+QlSULs>csdHjMnA+WV(7|cY0+O&^eWJz$C+2v10Lqt znNc88B`udE$ zhQT3_jNgummxp9(%7fMWBrK3@H1HT6FfA22iaBm1JfdBhITA*TrDbm4X+7@%sn~nduXWwP9O?{jB9Uc@hB`Vb^O(Cj5d;j0ujp$&$@3>1tootbn&(+y?+(?hq$Yw z>LG2++L>oG^cS%=R+yGA(ryJ;-to#L)GW=F@7_9qHE5%CE>>AeXZ(QNuCd7XE2|&n zwd7L-Eg^=)DsEK|ee+0#yTmVwJdYT^wZU4|Ak zSThGP>&C6TS`O4nN2J!<4AHD`K%v`M{Bx>kDS|tgwZ0nh2`-n4-w!eidTo3X#A>_z0)X$vIw$8&DzW0HezrXgn7Ki%%n3XLw5QDy8L<%&q zanf0f6T8tb3<>w{eeAFXlA-bQ9fDNd!&fI&J=|(Liecql^Gn*9xkLsa8E=PaF5}w$ zh6$`X^y@$qCo*PTdSE~QX6tFk&dXp0@{jAgTWyVHQM5XW=lKO;wok!CayGcxfQ9&I z_aWRN@g75lhvsI@#H+aqA-;d1_7n*d%y1L8A`^}9t>GPALlj6CHB6k$Jz_<( z$*4PwGDcZCx!{J#NiveGA9i*q@X_Q#lQaif6@Ser0SsQ@ahR{$zvq6Sc-yNPRz-XZ z^x~S*zABuh6<5Fzh=}a_k;W^=J|Vi0JQ?iC|7BJFwJ87TUj8o~dfR+5J5-WXx~obH zTPUqbBCW6E+=ygSsoj8P7$>0qw;kUa`pm)$@;H(=(66p?A%g{8IX_B{sR6MYAVU|N zc`2la?PUC;k&r3|JYfei-kZPVydhKEHUCpfyYxoUcfZXJC7ya`oNSf1{Cw+bAaSo`g? z>}>Iy;Kaq&o$!g$?1Le(wxkXxUJOJ}&wenCQ0Gkq2@j{ zvnMc+zPvfB7vMx$TMb_FW%elai|@9{LUE6f?_FD`$Icm);ba<3h9%$Xvb|ERtn4Wx zF+5O(!y@1Mhx=t}t_)H!ETZRR?C!dblBZB*kxnz!F11%=Q@`)jY@m-}w7+t6Gfs6- z6lj-N;933S)OZY3bVjhYasm7g+~$9}OxFM1c>bRp>f!@>Idw4oo2}LLTeNxR{jYv* zV=lDmq&avCn+1juGLWxWS2peq2u z3G0V;PrB13_e1v3-4emUx%TuDUP~nUZ1B@A zG6YO*S<>2iFh_YXs{D*Hwy5$Q`Ivb2SQs;$em3Y&MG?9}*E^IA{^hH_ZSu1XL>Tc) zRKjzl&GGlb(#o{UV4o-+R{58u}c8A;9Z*8+nq6yBHm;+WfuX<0b7Kc z_j|+x8T58|;Ltpg>t643@$<7=(mXuK2z8m5OC|PB2nUTwb!ndJ7S7GsX0zP}S(d(M z!%-*ELIij9ZvvGpiQz(G;iaj`TfHXo)ixh^(a`aLC!GwE2E3unKa9_qRtYqM=MAxg7*sY4O(IC9}tXMu-CH^tJ-VL*~x%`R!cs)^?75}aNPc^!Gf<8j(+2-GF7cu<(q#mOnlWQf@2oi6iCY$0=nApN;@E z7y?OG3l{uavBOy?+MC{P0apeBmty$A2i&H&QO3q#iVaLKR}&pofVC`2vTmS*Qtrk3 zm8fu-D=;(fKHCl`26SY#27XK~N4)f5$cn|QapFpvT?TyYajuaD-bcP^M-y#f?%wlI ztaTYg3=co`ZJ?d>@b&$;}B36x#V0AQ^*&fIL)n99|q!T-re=~`E-|c*C6P`7M|Byn?FJ|bV$#}hwH7-&`V!6EUPn|ta6K9$p|xg7)`CN8BF&eF zhR;P`S@Aiz_T$m*rIm~VPA?oJ>%xfcrr9A_5pUBk2xVO_?*meAQusn{8Bfw?nm zz>*^P#EnK9+zE8_nS9GMeO$B4+5I6YsdcVJrA?oxn))sm)W2V*PGcpoxwfpZ)Fqmz zMj*we#0ZJsfd6||AQ9khMN?oUq=9+$Jmn5-R@rJo0hTHOOD zHxgukT0QYTf~Lg9-VD@|P4J?6CBkBtfd$TI0M^_^)R&42f(rvfa=l;~0;L*WA-#PF z7W-Y|#eCntSNjK(_+3Yb!>Fs`(vQ)ZqK)C}ZEF<`rHEcp>nXPU>JMjeVLyKyA{{wl ztt$z<_i94W){?ILGs^)RE{oj-HclQbvTR4xQFCTAuf5c;$cem+c76(VnWiV z+^rtw;8JI2uUVK7EJAII&in7SICla+)E(095dS7d=URTVOY&#`D?@g;LIBVmv3|?9 ze*P!4nurfs+n$fio-K8JuV-I?v;uIvnO#0y@usvs)$DFG@dC`9yWzC8SrGt646lL3 zHoGwTrcYdYB|rNQNxs#BNquWl2cY(mc2O;Z=t!amfH2}s%QS*b5-Rb?jYyKnmVqy#BVWzEmu7_eBmy@wIwpJltm^70J ze@o)@@(%|ui|I{T9VKOQaKJ(`_q|NuKJhL&DUqZRUK+*(vyZx`OM0NJ{DJG%kI9S% zZI#(V*>jqq!Z+9Q5WRimCvfsIt8ICptu&c$Yrx)d9R9azrtTN3*=Ss#~a zfn?>qcX`rbsC`16Zf^~%LpU&(ez<-_Flc$~n|hS^>;8xc)P3e0gdm4!Twa%rRHQA}S!hc!B4$+CTZ(XMGfAs#zeQm_{)7DA~EXNCXL{|_dsc77Xn z{!+q!-#M0fBsNmiW_V;LxR{=WEGS?;j5LsN>*{-0ppsvfv8jf#O|7yado8Ehmf$NL zM80~q6=0qyHt4xt%nTPFvXkqdDK1n&@bPCnsBYr{u{{9%zTO{C$9Q=chjMKK$$Le` zvj>>%DlGmRiNCDbr8~JiPbc)z@Pte8aJse>G5>3aMcms^_Du$%AI@@%|c~(0J$((^fMEy+1p)wk+mo+hWDZQ z={#2t2d+6I(viM!m^~md`l>|F-{I}xvz8#?g>n4N!~%K}rUP0$Rv{JS^+&87Y0a$@ z;%-bwF$IRW_^D#oH*IbjVZ6DdWnW3CQP8=*eR$1# zGSj#y=VJ_>)Gl&N4BAZBk^0GaXV8Z6zgqZLyfz|fJDH{0B(^InwP7zM;GJEG0#B8#j}+FO%hiY zJo(M>vz{Se6V?(C#W}Ot<>PyCP;qhuS%QR4oemk#IK+bYHA!-}dS*X)wv-jW*5K`N zre9d~n)%}On>U$Z_R-2u^HfN_dUu4cMy<0f&@*b32bF?HpMBJT$Dr@6D-OHM+eA4amXP~iC=*?D>MJCc?2Zw^fX$~rWeMQ+D{syPp&&dEyv zv^Qc(mWjUpK4kOH$K*1Ex zaR6T+&&;*$flNU+g=+I}R9B)z3nVLcN|f^mL0m@DJ3Lm)ux&j-=V|TwU^G4cEXRP{ zG{p;ZMaw&&A9TIkPCZ#Qt0|Nbi12kI4Wg^I^iu;9B9hCmkU+23Pmmm{8|B-SjCHA0lZUs<}Co)`o?_pKu|}_OX~#{H`u?_x?(hL z&NE)z=53mtTEE+Iq0PmB38=?s(EYs+-09fxKk94bNHh)sHshBe2EoDqrW1MrOiPWm zI{WAbE9l=iMG2vgaaervDp>WDjb}cJk@!3fy~AH9B0D$~B@?;3ooKtenb{EZx3gLy z_s452Ub6sL)Z!~PQxs+ZawA660GRy>ZN{jo+rtHTE|t2SG>Ik%TaQ=K*cj?;X~bGW z1h7z?1TJ>MO=V|wW-a()us_ysVMQyTzsCs`ws`VTc#M0iGAeyB_Qok(e|(&zW-~Sm zij;)E_&y4C_?9Ms6Rw9=&5WJ>cN^oNu>7K<%@ux9D`H>Vqz$e>cO{uT<-eio(O}rR z)g<2Zd)_P)v3)*b6e=uf>;G(hwQFHg_%i49=OW?U4*5WK=TXzn* z9b$ny*kxXp&0e9CGc=AQ7_k?8&{Po-46g82iH9q(z#odgC+y{XqzndG(BH3a+6?nx zSnvbZo$4_uDKb@D^2>qkyX6lOOrMXsbt} zF)h=dM2sV9A0^UH9?;uvjI83HSL2P49f2u<^BDYb}7Xh;ibvEdi^@3H;ZeY#Uj#L zr%(C38=IP=-FSVyo&1Gp8Yodwgo(bWa5tDC$?*rHopJRklbjMavYFSox#_X&aZDEC za?FOAeBu*?KG?K~({=BR-@_0`qW$G$Tf*4tjyN-tR;tV;=;K*aj14WXMqM)A&cp{D z>x?0LxO!W^Y9~+3FLxRAB5zOA?E6}Ua}~1@8^vueg3S0ke4U{z(1w25qmkDA(@5nn7WYu&cjeNC}jg((D!~jaNOq z^q?iU*NVzp2|Z8JDU!nu%gikc&H#riucF|b^HBQ!XVe#0qi?KR8H+Q*3ZNWr8@%Yq z+WyV8LxUkENA6%tr=D2Ji+&@O;r~cy-07`*yN69|aK8Vs*=0tWVXsbI2%49w=)2TH zakXfaAyCrF1BH3SDvk!NfAk9s*`)5L(|1AwLLPO>F0c6bRr4kc`vU*&GlyhA z<)Y1*?V=;|Ho^Op%8f=u&N^=r>s25L6gWZxjv zyiM9)b8}{Vvb}uA4;A&Yoh-mY=kE>A<&=0z z3T^qwX2eDJfgYNS$*0YT1RPwX%<7#~-6#_J5bPP6+e;z;l(4f?vBt9^d*4yq#O3n8 z4qE;T;r2^sKm#V@EBB_f8@T0y|N`sbDR`p7kArzS$iZU~%!rH4v zckDMc&6{J&=4?@7W8~v9T6DP~-DpOG>cnG-l(<=o*h3Ta5yvgtm2hXJB;WR+ zPEAe*M(rRE4cgcNs# z@FAlNmI#euGyaLN`Po0xx38nFqa|LyWdtc*s2@r0d3`$+zTPm^)?*nG&&?wY{Mnf= zj<#`e_7NJizAJP|syjwrn~McscyBExwXs_0cJC3{AhmK}pIdXE!Q;1VE51LoeWY*_ zv;>ZHqy450??Ma~tN#Dnfc_sh$xqPt51)cyJ(~)>)7KA!p9DZO@4#;t-g+4RUxtnZ AN&o-= literal 0 HcmV?d00001 diff --git a/pandora_console/images/wizard/verde/tasklist.png b/pandora_console/images/wizard/verde/tasklist.png new file mode 100644 index 0000000000000000000000000000000000000000..4c6669e89de9d2c125b9c16940ab3dc54c54d808 GIT binary patch literal 1038 zcmeAS@N?(olHy`uVBq!ia0vp^Q6S901SGegx)utgBuiW)N`mv#O3D+9QW+dm@{>{( zJaZG%Q-e|yQz{EjrrIztFmLd5aSW-r^=6KJhE$-;@#GB)npd7oXm-+{@K7cwNAZ&3 zgoS;6iryIq{cc*_T&g+6r!Z@|LmS_tOBeI>ruk$VI7iEzQxs_LIxEn_$93|;{Msiw zem$>wZ*yPr{cmZPhwtuI&;S1W^SkfW{^#2dO}0ES_Y5;*0RuY{I{xMn$FIZZr_O!a zP*q=8@iwbNV^2^0w@T(Oe^2+DPd&Y;dh6j6O)05`clX}9c(`fF#g)9fXXq(6PqIJf zw)@-WY1?_(d6mUHFR7b)`Oe<3fZK2N&cwGW*S}r8uuR$b|MI0*qeZI=a_oOE`D4sD z>voRj(Oa@7l;ZChAO4kaP}BKArOEpD0q^cG^3GG-aG+_)0@P0$f>YGHi^c049nx^%)HoSjvXWNO?38i1wZ)%CS@V4_sv}N+^ zJ0>fWuYB%gxz*_6^0g^KLnvG|>xHy`&DI?}$u1?UHzp|ee#@VEs@}GS)nuCX+lf<` zTGYnHOx3xseLTWt@rj%MnlJ#ldzR;e6iVGldjt$THHYpt-@Gvg0? zX9=JBa$EI^_B<__^<@D|F1VjNRoKrI7$|n8&G_icyT1;umW@CCzGt(Si_V4_b5A%q zr<$rK>t15wp84C_;(JL%j}CKZ$E(&Se`T-OF3gSmyom3lgvGM^Zof)zK1-EQJ|wbl zL8{AP7G2L5(-zn(H6A@0>Ukx?#^O(_c@$a*0J-IlKU6Yvn*RNFbbWZUQQEsh2RFUa z;asG%&N|3*qpMm_tMT=|cMthrrq6rj+p8Y@bn9GJ+p8++7o*DcLEC zbH&@^a;?@rr#og`EgRiok8MA5?_Z#?$o?H3%=N0pLo0ab@ zpPLu8%U!{D;rvrUcbuNS{PAZ)QRJMc`v+%Rg*nf@?QcJ8LwUGp-!hZ3SmW zx^?3M*%LMvTEF&7t~m6tSInY;83n!T{Ue&daA!4BbF<|xSzrcd@O1TaS?83{1OQP5 B?Mwgw literal 0 HcmV?d00001 diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css index 2bc41163b6..33b1d3c0a9 100644 --- a/pandora_console/include/styles/discovery.css +++ b/pandora_console/include/styles/discovery.css @@ -8,6 +8,7 @@ li.discovery { width: 250px; height: 120px; margin: 15px; + padding-bottom: 50px; } li.discovery > a { From acf3c94642f70f0b890a01692313b96f60f2a2c6 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Thu, 21 Feb 2019 13:16:32 +0100 Subject: [PATCH 205/249] fix bad solved conflict and added changes in bd to migrate and mr Former-commit-id: d52e91d0f2b886620aa9fc07dda48bfeb27ffe0c --- pandora_console/extras/mr/25.sql | 5 + .../pandoradb_migrate_6.0_to_7.0.mysql.sql | 1 + .../operation/agentes/status_monitor.php | 521 +----------------- 3 files changed, 8 insertions(+), 519 deletions(-) create mode 100644 pandora_console/extras/mr/25.sql diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql new file mode 100644 index 0000000000..b8a1eca9ae --- /dev/null +++ b/pandora_console/extras/mr/25.sql @@ -0,0 +1,5 @@ +START TRANSACTION; + +INSERT INTO `tconfig` (`token`, `value`) VALUES ('status_monitor_fields', 'policy,agent,data_type,module_name,server_type,interval,status,graph,warn,data,timestamp'); + +COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index bedb9927cd..99a5dae2be 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1206,6 +1206,7 @@ INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_logo_white_bg_preview', UPDATE tconfig SET value = 'https://licensing.artica.es/pandoraupdate7/server.php' WHERE token='url_update_manager'; DELETE FROM `tconfig` WHERE `token` = 'current_package_enterprise'; INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '731'); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('status_monitor_fields', 'policy,agent,data_type,module_name,server_type,interval,status,graph,warn,data,timestamp'); -- --------------------------------------------------------------------- -- Table `tconfig_os` diff --git a/pandora_console/operation/agentes/status_monitor.php b/pandora_console/operation/agentes/status_monitor.php index 0d34b416a4..fd4d9d050f 100644 --- a/pandora_console/operation/agentes/status_monitor.php +++ b/pandora_console/operation/agentes/status_monitor.php @@ -1068,7 +1068,7 @@ if (!empty($result)) { $table->size = array (); $table->align = array (); -$show_fields = explode (',', $config['status_monitor_fields']); + $show_fields = explode (',', $config['status_monitor_fields']); if (in_array('policy', $show_fields)) { @@ -1131,7 +1131,7 @@ $show_fields = explode (',', $config['status_monitor_fields']); $table->head[9] = __('Data'); $table->align[9] = 'left'; if ( is_metaconsole() ) { - $table->head[9] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . + $table->head[9] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . '' . html_print_image('images/sort_down.png', true, array('style' => $selectStatusDown, 'alt' => 'down')) . ''; } } @@ -1644,523 +1644,6 @@ $show_fields = explode (',', $config['status_monitor_fields']); array_push ($table->data, $data); } - - html_print_table ($table); - - $table->head[2] = __('Data Type'); - $table->head[2] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectTypeUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectTypeDown, 'alt' => 'down']).''; - - $table->align[2] = 'left'; - - $table->head[3] = __('Module name'); - $table->head[3] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectModuleNameUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectModuleNameDown, 'alt' => 'down']).''; - - $table->head[4] = __('Server type'); - $table->head[4] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectModuleNameUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectModuleNameDown, 'alt' => 'down']).''; - - $table->head[5] = __('Interval'); - $table->head[5] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectIntervalUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectIntervalDown, 'alt' => 'down']).''; - $table->align[5] = 'left'; - - $table->head[6] = __('Status'); - $table->head[6] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectStatusUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectStatusDown, 'alt' => 'down']).''; - - $table->align[6] = 'left'; - - $table->head[7] = __('Graph'); - $table->align[7] = 'left'; - - $table->head[8] = __('Warn'); - $table->align[8] = 'left'; - - $table->head[9] = __('Data'); - $table->align[9] = 'left'; - if (is_metaconsole()) { - $table->head[9] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectStatusUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectStatusDown, 'alt' => 'down']).''; - } - - $table->head[10] = __('Timestamp'); - $table->head[10] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectTimestampUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectTimestampDown, 'alt' => 'down']).''; - $table->align[10] = 'left'; - - $id_type_web_content_string = db_get_value( - 'id_tipo', - 'ttipo_modulo', - 'nombre', - 'web_content_string' - ); - - foreach ($result as $row) { - // Avoid unset, null and false value - if (empty($row['server_name'])) { - $row['server_name'] = ''; - } - - $is_web_content_string = (bool) db_get_value_filter( - 'id_agente_modulo', - 'tagente_modulo', - [ - 'id_agente_modulo' => $row['id_agente_modulo'], - 'id_tipo_modulo' => $id_type_web_content_string, - ] - ); - - // Fixed the goliat sends the strings from web - // without HTML entities - if ($is_web_content_string) { - $row['datos'] = io_safe_input($row['datos']); - } - - // Fixed the data from Selenium Plugin - if ($row['datos'] != strip_tags($row['datos'])) { - $row['datos'] = io_safe_input($row['datos']); - } - - $data = []; - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { - if (is_metaconsole()) { - $node = metaconsole_get_connection_by_id($row['server_id']); - if (metaconsole_load_external_db($node) !== NOERR) { - // Restore the default connection. - metaconsole_restore_db(); - $errors++; - break; - } - } - - $policyInfo = policies_info_module_policy($row['id_agente_modulo']); - - if ($policyInfo === false) { - $data[0] = ''; - } else { - $linked = policies_is_module_linked($row['id_agente_modulo']); - - $adopt = false; - if (policies_is_module_adopt($row['id_agente_modulo'])) { - $adopt = true; - } - - if ($linked) { - if ($adopt) { - $img = 'images/policies_brick.png'; - $title = __('(Adopt) ').$policyInfo['name_policy']; - } else { - $img = 'images/policies.png'; - $title = $policyInfo['name_policy']; - } - } else { - if ($adopt) { - $img = 'images/policies_not_brick.png'; - $title = __('(Unlinked) (Adopt) ').$policyInfo['name_policy']; - } else { - $img = 'images/unlinkpolicy.png'; - $title = __('(Unlinked) ').$policyInfo['name_policy']; - } - } - - if (is_metaconsole()) { - $data[0] = ''.html_print_image($img, true, ['title' => $title]).''; - } else { - $data[0] = ''.html_print_image($img, true, ['title' => $title]).''; - } - } - - if (is_metaconsole()) { - metaconsole_restore_db(); - } - } - - $agent_alias = !empty($row['agent_alias']) ? $row['agent_alias'] : $row['agent_name']; - - // TODO: Calculate hash access before to use it more simply like other sections. I.E. Events view - if (defined('METACONSOLE')) { - $agent_link = ''; - $agent_alias = ui_print_truncate_text( - $agent_alias, - 'agent_small', - false, - true, - false, - '[…]', - 'font-size:7.5pt;' - ); - if (can_user_access_node()) { - $data[1] = $agent_link.''.$agent_alias.''; - } else { - $data[1] = $agent_alias; - } - } else { - $data[1] = ''; - $data[1] .= ui_print_truncate_text($agent_alias, 'agent_medium', false, true, false, '[…]', 'font-size:7.5pt;'); - $data[1] .= ''; - } - - - $data[2] = html_print_image('images/'.modules_show_icon_type($row['module_type']), true); - $agent_groups = is_metaconsole() ? $row['groups_in_server'] : agents_get_all_groups_agent($row['id_agent'], $row['id_group']); - if (check_acl_one_of_groups($config['id_user'], $agent_groups, 'AW')) { - $show_edit_icon = true; - if (defined('METACONSOLE')) { - if (!can_user_access_node()) { - $show_edit_icon = false; - } - - $url_edit_module = $row['server_url'].'index.php?'.'sec=gagente&'.'sec2=godmode/agentes/configurar_agente&'.'id_agente='.$row['id_agent'].'&'.'tab=module&'.'id_agent_module='.$row['id_agente_modulo'].'&'.'edit_module=1'.'&loginhash=auto&loginhash_data='.$row['hashdata'].'&loginhash_user='.str_rot13($row['user']); - } else { - $url_edit_module = 'index.php?'.'sec=gagente&'.'sec2=godmode/agentes/configurar_agente&'.'id_agente='.$row['id_agent'].'&'.'tab=module&'.'id_agent_module='.$row['id_agente_modulo'].'&'.'edit_module=1'; - } - - if ($show_edit_icon) { - $data[2] .= ''.html_print_image( - 'images/config.png', - true, - [ - 'alt' => '0', - 'border' => '', - 'title' => __('Edit'), - ] - ).''; - } - } - - $data[3] = ui_print_truncate_text($row['module_name'], 'agent_small', false, true, true); - if ($row['extended_info'] != '') { - $data[3] .= ui_print_help_tip($row['extended_info'], true, '/images/default_list.png'); - } - - if ($row['tags'] != '') { - $data[3] .= html_print_image( - '/images/tag_red.png', - true, - [ - 'title' => $row['tags'], - 'style' => 'width: 20px; margin-left: 3px;', - ] - ); - } - - $data[4] = servers_show_type($row['id_modulo']); - - $data[5] = ($row['module_interval'] == 0) ? human_time_description_raw($row['agent_interval']) : human_time_description_raw($row['module_interval']); - - if ($row['utimestamp'] == 0 && (($row['module_type'] < 21 - || $row['module_type'] > 23) && $row['module_type'] != 100) - ) { - $data[6] = ui_print_status_image( - STATUS_MODULE_NO_DATA, - __('NOT INIT'), - true - ); - } else if ($row['estado'] == 0) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image( - STATUS_MODULE_OK, - __('NORMAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), - true - ); - } else { - $data[6] = ui_print_status_image( - STATUS_MODULE_OK, - __('NORMAL').': '.$row['datos'], - true - ); - } - } else if ($row['estado'] == 1) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image( - STATUS_MODULE_CRITICAL, - __('CRITICAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), - true - ); - } else { - $data[6] = ui_print_status_image( - STATUS_MODULE_CRITICAL, - __('CRITICAL').': '.$row['datos'], - true - ); - } - } else if ($row['estado'] == 2) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image( - STATUS_MODULE_WARNING, - __('WARNING').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), - true - ); - } else { - $data[6] = ui_print_status_image( - STATUS_MODULE_WARNING, - __('WARNING').': '.$row['datos'], - true - ); - } - } else { - $last_status = modules_get_agentmodule_last_status( - $row['id_agente_modulo'] - ); - switch ($last_status) { - case 0: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image( - STATUS_MODULE_UNKNOWN, - __('UNKNOWN').' - '.__('Last status').' '.__('NORMAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), - true - ); - } else { - $data[6] = ui_print_status_image( - STATUS_MODULE_UNKNOWN, - __('UNKNOWN').' - '.__('Last status').' '.__('NORMAL').': '.$row['datos'], - true - ); - } - break; - - case 1: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image( - STATUS_MODULE_UNKNOWN, - __('UNKNOWN').' - '.__('Last status').' '.__('CRITICAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), - true - ); - } else { - $data[6] = ui_print_status_image( - STATUS_MODULE_UNKNOWN, - __('UNKNOWN').' - '.__('Last status').' '.__('CRITICAL').': '.$row['datos'], - true - ); - } - break; - - case 2: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image( - STATUS_MODULE_UNKNOWN, - __('UNKNOWN').' - '.__('Last status').' '.__('WARNING').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), - true - ); - } else { - $data[6] = ui_print_status_image( - STATUS_MODULE_UNKNOWN, - __('UNKNOWN').' - '.__('Last status').' '.__('WARNING').': '.$row['datos'], - true - ); - } - break; - } - } - - $data[7] = ''; - - $acl_graphs = false; - - // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions - if (!is_metaconsole()) { - $acl_graphs = check_acl($config['id_user'], $row['id_group'], 'RR'); - } else { - $acl_graphs = true; - } - - if ($row['history_data'] == 1 && $acl_graphs) { - $graph_type = return_graphtype($row['module_type']); - - $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); - $handle = dechex(crc32($row['id_agente_modulo'].$row['module_name'])); - $win_handle = 'day_'.$handle; - - $graph_params = [ - 'type' => $graph_type, - 'period' => SECONDS_1DAY, - 'id' => $row['id_agente_modulo'], - 'label' => base64_encode($row['module_name']), - 'refresh' => SECONDS_10MINUTES, - ]; - - if (is_metaconsole() && isset($row['server_id'])) { - // Set the server id - $graph_params['server'] = $row['server_id']; - } - - $graph_params_str = http_build_query($graph_params); - - $link = 'winopeng(\''.$url.'?'.$graph_params_str.'\',\''.$win_handle.'\')'; - - $data[7] = get_module_realtime_link_graph($row); - - if (!is_snapshot_data($row['datos'])) { - $data[7] .= ''.html_print_image('images/chart_curve.png', true, ['border' => '0', 'alt' => '']).''; - } - - $data[7] .= ''.html_print_image( - 'images/binary.png', - true, - [ - 'border' => '0', - 'alt' => '', - ] - ).''; - - $data[7] .= ''.$row['module_name'].''; - } - - $data[8] = ui_print_module_warn_value( - $row['max_warning'], - $row['min_warning'], - $row['str_warning'], - $row['max_critical'], - $row['min_critical'], - $row['str_critical'] - ); - - if (is_numeric($row['datos']) && !modules_is_string_type($row['module_type'])) { - if ($config['render_proc']) { - switch ($row['module_type']) { - case 2: - case 6: - case 9: - case 18: - case 21: - case 31: - if ($row['datos'] >= 1) { - $salida = $config['render_proc_ok']; - } else { - $salida = $config['render_proc_fail']; - } - break; - - default: - switch ($row['module_type']) { - case 15: - $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); - if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') { - $salida = human_milliseconds_to_string($row['datos']); - } else { - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - } - break; - - default: - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - } - break; - } - } else { - switch ($row['module_type']) { - case 15: - $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); - if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') { - $salida = human_milliseconds_to_string($row['datos']); - } else { - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - } - break; - - default: - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - } - } - - // Show units ONLY in numeric data types - if (isset($row['unit'])) { - $data_macro = modules_get_unit_macro($row['datos'], $row['unit']); - if ($data_macro) { - $salida = $data_macro; - } else { - $salida .= ' '.''.io_safe_output($row['unit']).''; - if (strlen($salida) > $config['agent_size_text_small']) { - $salida = ui_print_truncate_text($salida, 'agent_small', true, true, false, '[…]', 'font-size:7.5pt;'); - // clean tag - $text_aux = explode(' $row['id_agente_modulo'], - 'interval' => $row['current_interval'], - 'module_name' => $row['module_name'], - 'id_node' => $row['server_id'], - ] - ); - $salida = ui_get_snapshot_image($link, $is_snapshot).'  '; - } else { - $sub_string = substr(io_safe_output($row['datos']), 0, 12); - if ($module_value == $sub_string) { - if ($module_value == 0 && !$sub_string) { - $salida = 0; - } else { - $data_macro = modules_get_unit_macro($row['datos'], $row['unit']); - if ($data_macro) { - $salida = $data_macro; - } else { - $salida = $row['datos']; - } - } - } else { - // Fixed the goliat sends the strings from web - // without HTML entities - if ($is_web_content_string) { - $sub_string = substr($row['datos'], 0, 12); - } else { - // Fixed the data from Selenium Plugin - if ($module_value != strip_tags($module_value)) { - $module_value = io_safe_input($module_value); - $sub_string = substr($row['datos'], 0, 12); - } else { - $sub_string = substr(io_safe_output($row['datos']), 0, 12); - } - } - - if ($module_value == $sub_string) { - $salida = $module_value; - } else { - $salida = '".$module_value.''.'".''.$sub_string.' '."".html_print_image('images/rosette.png', true).''; - } - } - } - } - - $data[9] = $salida; - - if ($row['module_interval'] > 0) { - $interval = $row['module_interval']; - } else { - $interval = $row['agent_interval']; - } - - if ($row['estado'] == 3) { - $option = [ - 'html_attr' => 'class="redb"', - 'style' => 'font-size:7pt;', - ]; - } else { - $option = ['style' => 'font-size:7pt;']; - } - - $data[10] = ui_print_timestamp($row['utimestamp'], true, $option); - - array_push($table->data, $data); - } html_print_table($table); } else { From dc4d5b1bd75c8aec21d5a73c407f5cad651e9a18 Mon Sep 17 00:00:00 2001 From: daniel Date: Thu, 21 Feb 2019 13:21:05 +0100 Subject: [PATCH 206/249] fixed error in widget Former-commit-id: 3b0d2e8641d35f7c339aa4229f0a7108216704e0 --- pandora_console/include/functions_agents.php | 12 +- pandora_console/include/functions_html.php | 2 +- .../operation/agentes/ver_agente.php | 203 ++++++++++-------- 3 files changed, 123 insertions(+), 94 deletions(-) diff --git a/pandora_console/include/functions_agents.php b/pandora_console/include/functions_agents.php index 9aa9cf7dfd..6baf062228 100644 --- a/pandora_console/include/functions_agents.php +++ b/pandora_console/include/functions_agents.php @@ -949,11 +949,11 @@ function agents_get_group_agents( $filter = []; - // check available groups for target user only if asking for 'All' group + // Check available groups for target user only if asking for 'All' group. if (!$noACL && $id_group == 0) { - $id_group = $id_group == 0 ? array_keys(users_get_groups(false, 'AR', false)) : groups_safe_acl($config['id_user'], $id_group, 'AR'); + $id_group = ($id_group == 0) ? array_keys(users_get_groups(false, 'AR', false)) : groups_safe_acl($config['id_user'], $id_group, 'AR'); if (empty($id_group)) { - // An empty array means the user doesn't have access + // An empty array means the user doesn't have access. return []; } } @@ -970,7 +970,7 @@ function agents_get_group_agents( $id_group = groups_get_id_recursive($id_group, true); } - // check available groups for target user only if asking for 'All' group + // Check available groups for target user only if asking for 'All' group. if (!$noACL && $id_group == 0) { $id_group = array_keys( users_get_groups(false, 'AR', true, false, (array) $id_group) @@ -978,7 +978,7 @@ function agents_get_group_agents( } } - // Search for primary and secondary groups + // Search for primary and secondary groups. if (!empty($id_group)) { $filter[] = '('.db_format_array_where_clause_sql( [ @@ -990,7 +990,7 @@ function agents_get_group_agents( } if ($search === true) { - // No added search. Show both disabled and non-disabled + // No added search. Show both disabled and non-disabled. } else if (is_array($search)) { if (!$search['all_agents']) { $filter['disabled'] = 0; diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 9c6819d535..637caacc3f 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -2257,7 +2257,7 @@ function html_print_checkbox_extended($name, $value, $checked, $disabled, $scrip if ($id == '') { $output .= ' id="checkbox-'.$id_aux.'"'; } else { - $output .= ' '.$id.'"'; + $output .= ' id='.$id; } if ($script != '') { diff --git a/pandora_console/operation/agentes/ver_agente.php b/pandora_console/operation/agentes/ver_agente.php index e3171f61f4..585acafcfc 100644 --- a/pandora_console/operation/agentes/ver_agente.php +++ b/pandora_console/operation/agentes/ver_agente.php @@ -1,17 +1,32 @@ $v) { @@ -139,7 +164,7 @@ if (is_ajax()) { $id_agents = get_parameter('id_agents'); $selection = get_parameter('selection'); - // No filter by module group + // No filter by module group. $modules = select_modules_for_agent_group(0, $id_agents, $selection, false, true); echo json_encode($modules); return; @@ -311,28 +336,28 @@ if (is_ajax()) { } if (!empty($module_name)) { - $filter .= " AND t1.nombre COLLATE utf8_general_ci LIKE '%$module_name%'"; + $filter .= " AND t1.nombre COLLATE utf8_general_ci LIKE '%".$module_name."%'"; } - // Status selector + // Status selector. if ($status_modulo == AGENT_MODULE_STATUS_NORMAL) { - // Normal + // Normal. $sql_conditions .= ' estado = 0 AND utimestamp > 0 ) OR (t1.id_tipo_modulo IN(21,22,23,100)) '; } else if ($status_modulo == AGENT_MODULE_STATUS_CRITICAL_BAD) { - // Critical + // Critical. $sql_conditions .= ' estado = 1 AND utimestamp > 0 )'; } else if ($status_modulo == AGENT_MODULE_STATUS_WARNING) { - // Warning + // Warning. $sql_conditions .= ' estado = 2 AND utimestamp > 0 )'; } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_NORMAL) { - // Not normal + // Not normal. $sql_conditions .= ' estado <> 0)'; } else if ($status_modulo == AGENT_MODULE_STATUS_UNKNOWN) { - // Unknown + // Unknown. $sql_conditions .= ' estado = 3 AND utimestamp <> 0 )'; } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_INIT) { - // Not init + // Not init. $sql_conditions .= ' utimestamp = 0 ) AND t1.id_tipo_modulo NOT IN (21,22,23,100)'; } @@ -412,7 +437,7 @@ if (is_ajax()) { foreach ($array_reduced as $server_name => $id_agents) { // Metaconsole db connection - // $server_name can be the server id (ugly hack, I know) + // $server_name can be the server id (ugly hack, I know). if (is_numeric($server_name)) { $connection = metaconsole_get_connection_by_id($server_name); } else { @@ -423,7 +448,7 @@ if (is_ajax()) { continue; } - // Get agent's modules + // Get agent's modules. $sql = sprintf( 'SELECT t1.id_agente, t1.id_agente_modulo, t1.nombre FROM tagente_modulo t1 %s @@ -451,7 +476,7 @@ if (is_ajax()) { $modules_aux = []; foreach ($modules as $key => $module) { - // Don't change this order, is used in the serialization + // Don't change this order, is used in the serialization. $module_data = [ 'id_module' => $module['id_agente_modulo'], 'id_agent' => $module['id_agente'], @@ -466,7 +491,7 @@ if (is_ajax()) { $modules = $modules_aux; - // Build the next array using the common values + // Build the next array using the common values. if (!empty($last_modules_set)) { $modules = array_intersect_key($modules, $last_modules_set); @@ -480,7 +505,7 @@ if (is_ajax()) { $last_modules_set = $modules; - // Restore db connection + // Restore db connection. metaconsole_restore_db(); } @@ -490,7 +515,6 @@ if (is_ajax()) { $module_data_processed = array_map( function ($item) { - // data: -> id_module | id_agent | server_name; return implode('|', $item); }, $module_data @@ -600,16 +624,16 @@ if (is_ajax()) { if ($get_agent_modules_json) { $id_agent = (int) get_parameter('id_agent'); - // Use -1 as not received + // Use -1 as not received. $disabled = (int) get_parameter('disabled', -1); $delete_pending = (int) get_parameter('delete_pending', -1); - // Use 0 as not received + // Use 0 as not received. $id_tipo_modulo = (int) get_parameter('id_tipo_modulo', 0); $status_modulo = (int) get_parameter('status_module', -1); $tags = (array) get_parameter('tags', []); - // Filter + // Filter. $filter = []; if ($disabled !== -1) { $filter['disabled'] = $disabled; @@ -627,30 +651,34 @@ if (is_ajax()) { $filter = false; } - $get_only_string_modules = get_parameter('get_only_string_modules', false); + $get_only_string_modules = get_parameter( + 'get_only_string_modules', + false + ); + if ($get_only_string_modules) { $filter['tagente_modulo.id_tipo_modulo IN'] = '(17,23,3,10,33)'; } - // Status selector + // Status selector. if ($status_modulo == AGENT_MODULE_STATUS_NORMAL) { - // Normal - $sql_conditions .= ' estado = 0 AND utimestamp > 0 ) + // Normal. + $sql_conditions .= ' estado = 0 AND utimestamp > 0 ) OR (tagente_modulo.id_tipo_modulo IN(21,22,23,100)) '; } else if ($status_modulo == AGENT_MODULE_STATUS_CRITICAL_BAD) { - // Critical + // Critical. $sql_conditions .= ' estado = 1 AND utimestamp > 0 )'; } else if ($status_modulo == AGENT_MODULE_STATUS_WARNING) { - // Warning + // Warning. $sql_conditions .= ' estado = 2 AND utimestamp > 0 )'; } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_NORMAL) { - // Not normal + // Not normal. $sql_conditions .= ' estado <> 0 )'; } else if ($status_modulo == AGENT_MODULE_STATUS_UNKNOWN) { - // Unknown + // Unknown. $sql_conditions .= ' estado = 3 AND utimestamp <> 0 )'; } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_INIT) { - // Not init + // Not init. $sql_conditions .= ' utimestamp = 0 ) AND tagente_modulo.id_tipo_modulo NOT IN (21,22,23,100)'; } @@ -663,7 +691,7 @@ if (is_ajax()) { $get_id_and_name = (bool) get_parameter('get_id_and_name'); $get_distinct_name = (bool) get_parameter('get_distinct_name'); - // Fields + // Fields. $fields = '*'; if ($get_id_and_name) { $fields = [ @@ -680,7 +708,8 @@ if (is_ajax()) { $agentName = (string) get_parameter('agent_name', null); $server_name = (string) get_parameter('server_name', null); $server_id = (int) get_parameter('server_id', 0); - // This will force to get local modules although metaconsole is active, by default get all modules from all nodes + // This will force to get local modules although metaconsole is active, + // by default get all modules from all nodes. $force_local_modules = (int) get_parameter('force_local_modules', 0); if ($agentName != null) { @@ -703,7 +732,7 @@ if (is_ajax()) { } if (metaconsole_load_external_db($connection) == NOERR) { - // Get all agents if no agent was given + // Get all agents if no agent was given. if ($id_agent == 0) { $id_agent = array_keys( agents_get_group_agents( @@ -717,11 +746,11 @@ if (is_ajax()) { $agent_modules = agents_get_modules($id_agent, $fields, $filter, $indexed, true, $force_tags); } - // Restore db connection + // Restore db connection. metaconsole_restore_db(); } } else { - // Get all agents if no agent was given + // Get all agents if no agent was given. if ($id_agent == 0) { $id_agent = array_keys( agents_get_group_agents( @@ -765,7 +794,7 @@ if (is_ajax()) { $id_agent = (int) get_parameter('id_agent'); $metaconsole = (bool) get_parameter('metaconsole', false); $id_server = (int) get_parameter('id_server', 0); - // Metaconsole + // Metaconsole. $server = null; if ($metaconsole) { $filter = []; @@ -802,7 +831,7 @@ if (is_ajax()) { echo ''.__('Last remote contact').': '.human_time_comparation($agent['ultimo_contacto_remoto']).'
      '; if (!$metaconsole) { - // Fix : Only show agents with module with tags of user profile + // Fix : Only show agents with module with tags of user profile. $_user_tags = tags_get_user_tags($config['id_user'], 'RR'); $_sql_post = ''; @@ -839,10 +868,10 @@ if (is_ajax()) { if ($bad_modules === false) { $size_bad_modules = 0; } else { - $size_bad_modules = sizeof($bad_modules); + $size_bad_modules = count($bad_modules); } - // Modules down + // Modules down. if ($size_bad_modules > 0) { echo ''.__('Monitors down').': '.$size_bad_modules.' / '.$total_modules; echo '
        '; @@ -855,7 +884,7 @@ if (is_ajax()) { echo '
      '; } - // Alerts (if present) + // Alerts (if present). $sql = sprintf( 'SELECT COUNT(talert_template_modules.id) FROM talert_template_modules, tagente_modulo, tagente @@ -937,8 +966,8 @@ if (is_ajax()) { if ($module['id_tipo_modulo'] == 18) { echo ''.__('Address').': '; - // Get the IP/IPs from the module description - // Always the IP is the last part of the description (after the last space) + // Get the IP/IPs from the module description Always the IP + // is the last part of the description (after the last space). $ips = explode(' ', $module['descripcion']); $ips = $ips[(count($ips) - 1)]; @@ -948,7 +977,7 @@ if (is_ajax()) { } else { echo '
        '; foreach ($ips as $ip) { - echo "
      • $ip
      • "; + echo '
      • '.$ip.'
      • '; } echo '
      '; @@ -1033,7 +1062,7 @@ $agent_a = check_acl($config['id_user'], 0, 'AR'); $agent_w = check_acl($config['id_user'], 0, 'AW'); $access = ($agent_a == true) ? 'AR' : (($agent_w == true) ? 'AW' : 'AR'); $agent = db_get_row('tagente', 'id_agente', $id_agente); -// get group for this id_agente +// Get group for this id_agente. $id_grupo = $agent['id_grupo']; $is_extra = enterprise_hook('policies_is_agent_extra_policy', [$id_agente]); @@ -1053,7 +1082,7 @@ if (! check_acl_one_of_groups($config['id_user'], $all_groups, 'AR') && ! check_ return; } -// Check for Network FLAG change request +// Check for Network FLAG change request. $flag = get_parameter('flag', ''); if ($flag !== '') { if ($flag == 1 && check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { @@ -1067,7 +1096,7 @@ if ($flag !== '') { } } -// Check for Network FLAG change request +// Check for Network FLAG change request. $flag_agent = get_parameter('flag_agent', ''); if ($flag_agent !== '') { if ($flag_agent == 1 && check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { @@ -1082,10 +1111,10 @@ if ($agent['icon_path']) { } -// -------------Code for the tabs in the header of agent page----------- +// Code for the tabs in the header of agent page. $tab = get_parameter('tab', 'main'); -// Manage tab +// Manage tab. $managetab = []; if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') || $is_extra) { @@ -1101,7 +1130,7 @@ if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') || $is_extra) } -// Main tab +// Main tab. $maintab['text'] = ''.html_print_image('images/agent_mc.png', true, ['title' => __('Main')]).''; if ($tab == 'main') { @@ -1112,7 +1141,7 @@ if ($tab == 'main') { -// Alert tab +// Alert tab. $alerttab['text'] = ''.html_print_image('images/op_alerts.png', true, ['title' => __('Alerts')]).''; if ($tab == 'alert') { @@ -1121,27 +1150,27 @@ if ($tab == 'alert') { $alerttab['active'] = false; } -// Inventory +// Inventory. $inventorytab = enterprise_hook('inventory_tab'); if ($inventorytab == -1) { $inventorytab = ''; } -// Collection +// Collection. $collectiontab = enterprise_hook('collection_tab'); if ($collectiontab == -1) { $collectiontab = ''; } -// Policy +// Policy. $policyTab = enterprise_hook('policy_tab'); if ($policyTab == -1) { $policyTab = ''; } -// WUX Console +// WUX Console. $modules_wux = enterprise_hook('get_wux_modules', [$id_agente]); if ($modules_wux) { $wux_console_tab = enterprise_hook('wux_console_tab'); @@ -1158,7 +1187,7 @@ if ($url_route_analyzer) { } } -// GIS tab +// GIS tab. $gistab = []; if ($config['activate_gis']) { $gistab['text'] = ''.html_print_image('images/op_gis.png', true, [ 'title' => __('GIS data')]).''; @@ -1171,7 +1200,7 @@ if ($config['activate_gis']) { } -// Incident tab +// Incident tab. $total_incidents = agents_get_count_incidents($id_agente); if ($total_incidents > 0) { $incidenttab['text'] = ''.html_print_image('images/book_edit.png', true, ['title' => __('Incidents')]).''; @@ -1184,7 +1213,7 @@ if ($total_incidents > 0) { } -// Url address tab +// Url address tab. if ($agent['url_address'] != '') { $urladdresstab['text'] = ''.html_print_image('images/link.png', true, ['title' => __('Url address')]).''; } @@ -1196,7 +1225,7 @@ if ($tab == 'url_address') { } -// Custom fields tab +// Custom fields tab. $custom_fields['text'] = ''.html_print_image('images/custom_field.png', true, ['title' => __('Custom fields')]).''; if ($tab == 'custom_fields') { $custom_fields['active'] = true; @@ -1205,7 +1234,7 @@ if ($tab == 'custom_fields') { } -// Graphs tab +// Graphs tab. $graphs['text'] = ''.html_print_image('images/chart.png', true, ['title' => __('Graphs')]).''; if ($tab == 'graphs') { $graphs['active'] = true; @@ -1214,7 +1243,7 @@ if ($tab == 'graphs') { } -// Log viewer tab +// Log viewer tab. if (enterprise_installed() && $config['log_collector']) { $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; $agent_has_logs = (bool) db_get_value('id_agent', 'tagent_module_log', 'id_agent', $id_agente); @@ -1226,7 +1255,7 @@ if (enterprise_installed() && $config['log_collector']) { } } -// eHorus tab +// EHorus tab. if ($config['ehorus_enabled'] && !empty($config['ehorus_custom_field']) && (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') || is_user_admin($config['id_user'])) ) { @@ -1235,7 +1264,7 @@ if ($config['ehorus_enabled'] && !empty($config['ehorus_custom_field']) $tab_url = 'index.php?sec=estado&sec2=operation/agentes/ver_agente&tab=ehorus&id_agente='.$id_agente; $ehorus_tab['text'] = ''.html_print_image('images/ehorus/ehorus.png', true, [ 'title' => __('eHorus')]).''; - // Hidden subtab layer + // Hidden subtab layer. $ehorus_tab['sub_menu'] = '
        '; $ehorus_tab['sub_menu'] .= ''; $ehorus_tab['sub_menu'] .= '
      • '.html_print_image('images/ehorus/terminal.png', true, [ 'title' => __('Terminal')]); @@ -1279,7 +1308,7 @@ $onheader = [ ]; // Added after it exists -// If the agent has incidents associated +// If the agent has incidents associated. if ($total_incidents) { $onheader['incident'] = $incidenttab; } @@ -1288,23 +1317,23 @@ if ($agent['url_address'] != '') { $onheader['url_address'] = $urladdresstab; } -// If the log viewer tab exists +// If the log viewer tab exists. if (isset($log_viewer_tab) && !empty($log_viewer_tab)) { $onheader['log_viewer'] = $log_viewer_tab; } -// If the ehorus id exists +// If the ehorus id exists. if (isset($ehorus_tab) && !empty($ehorus_tab)) { $onheader['ehorus'] = $ehorus_tab; } -// Tabs for extensions +// Tabs for extensions. foreach ($config['extensions'] as $extension) { if (isset($extension['extension_ope_tab']) && !isset($extension['extension_god_tab'])) { if (check_acl_one_of_groups($config['id_user'], $all_groups, $extension['extension_ope_tab']['acl'])) { - // VMware extension is only available for VMware OS + // VMware extension is only available for VMware OS. if ($extension['extension_ope_tab']['id'] === 'vmware_manager') { - // Check if OS is vmware + // Check if OS is vmware. $id_remote_field = db_get_value( 'id_field', 'tagent_custom_fields', @@ -1326,13 +1355,13 @@ foreach ($config['extensions'] as $extension) { } } - // RHEV extension is only available for RHEV Virtual Machines + // RHEV extension is only available for RHEV Virtual Machines. if ($extension['extension_ope_tab']['id'] === 'rhev_manager') { - // Get id for remote field "rhev_type" + // Get id for remote field "rhev_type". $id_remote_field = db_get_value('id_field', 'tagent_custom_fields', 'name', 'rhev_type'); - // Get rhev type for this agent + // Get rhev type for this agent. $rhev_type = db_get_value_filter('description', 'tagent_custom_data', ['id_field' => $id_remote_field, 'id_agent' => $agent['id_agente']]); - // Check if rhev type is a vm + // Check if rhev type is a vm. if ($rhev_type != 'vm') { continue; } From 698451ee98db45e1245b939cf20ab42ae6c567c7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 13:38:58 +0100 Subject: [PATCH 207/249] MR25 Discovery Former-commit-id: 2685a72781173e3d87363fe0bc2b5dd72961cdce --- pandora_console/extras/mr/25.sql | 115 ++++++++++++++++++ .../pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 +- 2 files changed, 116 insertions(+), 1 deletion(-) create mode 100644 pandora_console/extras/mr/25.sql diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql new file mode 100644 index 0000000000..d6742561eb --- /dev/null +++ b/pandora_console/extras/mr/25.sql @@ -0,0 +1,115 @@ +START TRANSACTION; + +ALTER TABLE `trecon_task` ADD COLUMN `wmi_enabled` tinyint(1) unsigned DEFAULT '0'; +ALTER TABLE `trecon_task` ADD COLUMN `auth_strings` text; +ALTER TABLE `trecon_task` ADD COLUMN `autoconfiguration_enabled` tinyint(1) unsigned default '0'; + + +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware_plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); + +CREATE TABLE IF NOT EXISTS `tevent_extended` ( + `id` serial PRIMARY KEY, + `id_evento` bigint(20) unsigned NOT NULL, + `external_id` bigint(20) unsigned, + `utimestamp` bigint(20) NOT NULL default '0', + `description` text, + FOREIGN KEY `tevent_ext_fk`(`id_evento`) REFERENCES `tevento`(`id_evento`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `tnotification_source` ( + `id` serial, + `description` VARCHAR(255) DEFAULT NULL, + `icon` text, + `max_postpone_time` int(11) DEFAULT NULL, + `enabled` int(1) DEFAULT NULL, + `user_editable` int(1) DEFAULT NULL, + `also_mail` int(1) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- +-- Dumping data for table `tnotification_source` +-- +INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, `enabled`, `user_editable`, `also_mail`) VALUES + ("System status", "icono_info_mr.png", 86400, 1, 1, 0), + ("Message", "icono_info_mr.png", 86400, 1, 1, 0), + ("Pending task", "icono_info_mr.png", 86400, 1, 1, 0), + ("Advertisement", "icono_info_mr.png", 86400, 1, 1, 0), + ("Official communication", "icono_info_mr.png", 86400, 1, 1, 0), + ("Sugerence", "icono_info_mr.png", 86400, 1, 1, 0); + +-- ----------------------------------------------------- +-- Table `tmensajes` +-- ----------------------------------------------------- +ALTER TABLE `tmensajes` ADD COLUMN `url` TEXT; +ALTER TABLE `tmensajes` ADD COLUMN `response_mode` VARCHAR(200) DEFAULT NULL; +ALTER TABLE `tmensajes` ADD COLUMN `citicity` INT(10) UNSIGNED DEFAULT '0'; +ALTER TABLE `tmensajes` ADD COLUMN `id_source` BIGINT(20) UNSIGNED NOT NULL; +ALTER TABLE `tmensajes` ADD COLUMN `subtype` VARCHAR(255) DEFAULT ''; +ALTER TABLE `tmensajes` ADD INDEX (`id_source`); +UPDATE `tmensajes` SET `id_source`=(SELECT `id` FROM `tnotification_source` WHERE `description` = "Message"); +ALTER TABLE `tmensajes` ADD CONSTRAINT `tsource_fk` FOREIGN KEY (`id_source`) REFERENCES `tnotification_source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; + + +CREATE TABLE `tnotification_user` ( + `id_mensaje` INT(10) UNSIGNED NOT NULL, + `id_user` VARCHAR(60) NOT NULL, + `utimestamp_read` BIGINT(20), + `utimestamp_erased` BIGINT(20), + `postpone` INT, + PRIMARY KEY (`id_mensaje`,`id_user`), + FOREIGN KEY (`id_mensaje`) REFERENCES `tmensajes`(`id_mensaje`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `tnotification_group` ( + `id_mensaje` INT(10) UNSIGNED NOT NULL, + `id_group` mediumint(4) UNSIGNED NOT NULL, + PRIMARY KEY (`id_mensaje`,`id_group`), + FOREIGN KEY (`id_mensaje`) REFERENCES `tmensajes`(`id_mensaje`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `tnotification_source_user` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_user` VARCHAR(60), + `enabled` INT(1) DEFAULT NULL, + `also_mail` INT(1) DEFAULT NULL, + PRIMARY KEY (`id_source`,`id_user`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `tnotification_source_group` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL, + PRIMARY KEY (`id_source`,`id_group`), + INDEX (`id_group`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `tnotification_source_group_user` ( + `id_source` BIGINT(20) UNSIGNED NOT NULL, + `id_group` mediumint(4) unsigned NOT NULL, + `id_user` VARCHAR(60), + `enabled` INT(1) DEFAULT NULL, + `also_mail` INT(1) DEFAULT NULL, + PRIMARY KEY (`id_source`,`id_user`), + FOREIGN KEY (`id_source`) REFERENCES `tnotification_source`(`id`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_user`) REFERENCES `tusuario`(`id_user`) + ON UPDATE CASCADE ON DELETE CASCADE, + FOREIGN KEY (`id_group`) REFERENCES `tnotification_source_group`(`id_group`) + ON UPDATE CASCADE ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fields_descriptions`, `fields_values`) VALUES ('Generate Notification','Internal type','This command allows you to send an internal notification to any user or group.',1,'[\"Destination user\",\"Destination group\",\"Title\",\"Message\",\"Link\",\"Criticity\",\"\",\"\",\"\",\"\",\"\"]','[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]'); + +COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 6827938b42..7c1f8e2281 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1918,7 +1918,7 @@ ALTER TABLE `tmensajes` ADD COLUMN `response_mode` VARCHAR(200) DEFAULT NULL; ALTER TABLE `tmensajes` ADD COLUMN `citicity` INT(10) UNSIGNED DEFAULT '0'; ALTER TABLE `tmensajes` ADD COLUMN `id_source` BIGINT(20) UNSIGNED NOT NULL; ALTER TABLE `tmensajes` ADD COLUMN `subtype` VARCHAR(255) DEFAULT ''; -ALTER TABLE `tmensajes` ADD CONSTRAINT `tsource_fk` FOREIGN KEY (`id_source`) REFERENCES `tnotification_source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +ALTER TABLE `tmensajes` ADD CONSTRAINT `tsource_fk` FOREIGN KEY (`id_source`) REFERENCES `tnotification_source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- ---------------------------------------------------------------------- From c12ba3b12e92f82081c5a02476fddc97b9d6be14 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 13:58:29 +0100 Subject: [PATCH 208/249] Minor MR and sql updates - presets Former-commit-id: edf310a362b58c68dcadbb078b899948430f23e3 --- pandora_console/extras/mr/25.sql | 4 ++++ .../extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 6 ++++++ pandora_console/pandoradb_data.sql | 2 ++ 3 files changed, 12 insertions(+) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index d6742561eb..05c5978fed 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -112,4 +112,8 @@ CREATE TABLE `tnotification_source_group_user` ( INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fields_descriptions`, `fields_values`) VALUES ('Generate Notification','Internal type','This command allows you to send an internal notification to any user or group.',1,'[\"Destination user\",\"Destination group\",\"Title\",\"Message\",\"Link\",\"Criticity\",\"\",\"\",\"\",\"\",\"\"]','[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]'); +INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); + +INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); + COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 7c1f8e2281..c9ae871185 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1998,6 +1998,12 @@ CREATE TABLE `tnotification_source_group_user` ( -- ---------------------------------------------------------------------- INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fields_descriptions`, `fields_values`) VALUES ('Generate Notification','Internal type','This command allows you to send an internal notification to any user or group.',1,'[\"Destination user\",\"Destination group\",\"Title\",\"Message\",\"Link\",\"Criticity\",\"\",\"\",\"\",\"\",\"\"]','[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]'); +-- ---------------------------------------------------------------------- +-- Update message references and pre-configure notifications +-- ---------------------------------------------------------------------- +INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); +INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); + -- ---------------------------------------------------------------------- -- Add custom internal recon scripts -- ---------------------------------------------------------------------- diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index 8fa08b7074..bce6c85d1d 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1285,4 +1285,6 @@ INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, ` INSERT INTO `tnotification_source_user`(`id_source`,`id_user`,`enabled`,`also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin",1,0); +INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); + \ No newline at end of file From fd77b94f96c7955fd1612d28c1e9859e3c7b6f20 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 14:16:17 +0100 Subject: [PATCH 209/249] Fix regexp Supervisor Former-commit-id: 7dc32dd119ae78a3158e7c5d20bc5f73a8c94d2f --- pandora_console/include/class/ConsoleSupervisor.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index 29ed623d6e..fa65cd5d1f 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -693,7 +693,7 @@ class ConsoleSupervisor while (false !== ($file = readdir($dir)) && $nitems <= $max_files) { if ($file != '.' && $file != '..') { if (empty($regex) === false) { - if (preg_match($regex, $file) !== 1) { + if (preg_match($regex, $file) === 1) { $nitems++; continue; } @@ -891,7 +891,7 @@ class ConsoleSupervisor $filecount = $this->countFiles( $config['remote_config'], - '/.*BADXML/', + '/^.*BADXML$/', $MAX_BADXML_FILES_DATA_IN ); // If cannot open directory, count is '-1', skip. From e32c4025a4dd1ea2015e1cd3b0f39410654899d5 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 14:18:33 +0100 Subject: [PATCH 210/249] Supervisor. minor fixes Former-commit-id: 036bc6a871db86d7a8925c7d5e2531d9f62ca839 --- pandora_console/include/class/ConsoleSupervisor.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index fa65cd5d1f..4873186d62 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -697,9 +697,9 @@ class ConsoleSupervisor $nitems++; continue; } + } else { + $nitems++; } - - $nitems++; } } From 1167cfcafc4ed17fb9ce25342d4c01b080614843 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 14:27:09 +0100 Subject: [PATCH 211/249] Minor SQL fixes discovery Former-commit-id: 8d27ac99269f228b7fbb0c46b722bc5ea54c86ab --- pandora_console/extras/mr/25.sql | 12 ++++++------ .../extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index 05c5978fed..7e562b188d 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -53,7 +53,7 @@ UPDATE `tmensajes` SET `id_source`=(SELECT `id` FROM `tnotification_source` WHER ALTER TABLE `tmensajes` ADD CONSTRAINT `tsource_fk` FOREIGN KEY (`id_source`) REFERENCES `tnotification_source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -CREATE TABLE `tnotification_user` ( +CREATE TABLE IF NOT EXISTS `tnotification_user` ( `id_mensaje` INT(10) UNSIGNED NOT NULL, `id_user` VARCHAR(60) NOT NULL, `utimestamp_read` BIGINT(20), @@ -66,7 +66,7 @@ CREATE TABLE `tnotification_user` ( ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -CREATE TABLE `tnotification_group` ( +CREATE TABLE IF NOT EXISTS `tnotification_group` ( `id_mensaje` INT(10) UNSIGNED NOT NULL, `id_group` mediumint(4) UNSIGNED NOT NULL, PRIMARY KEY (`id_mensaje`,`id_group`), @@ -74,7 +74,7 @@ CREATE TABLE `tnotification_group` ( ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -CREATE TABLE `tnotification_source_user` ( +CREATE TABLE IF NOT EXISTS `tnotification_source_user` ( `id_source` BIGINT(20) UNSIGNED NOT NULL, `id_user` VARCHAR(60), `enabled` INT(1) DEFAULT NULL, @@ -86,7 +86,7 @@ CREATE TABLE `tnotification_source_user` ( ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -CREATE TABLE `tnotification_source_group` ( +CREATE TABLE IF NOT EXISTS `tnotification_source_group` ( `id_source` BIGINT(20) UNSIGNED NOT NULL, `id_group` mediumint(4) unsigned NOT NULL, PRIMARY KEY (`id_source`,`id_group`), @@ -95,7 +95,7 @@ CREATE TABLE `tnotification_source_group` ( ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -CREATE TABLE `tnotification_source_group_user` ( +CREATE TABLE IF NOT EXISTS `tnotification_source_group_user`( `id_source` BIGINT(20) UNSIGNED NOT NULL, `id_group` mediumint(4) unsigned NOT NULL, `id_user` VARCHAR(60), @@ -113,7 +113,7 @@ CREATE TABLE `tnotification_source_group_user` ( INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fields_descriptions`, `fields_values`) VALUES ('Generate Notification','Internal type','This command allows you to send an internal notification to any user or group.',1,'[\"Destination user\",\"Destination group\",\"Title\",\"Message\",\"Link\",\"Criticity\",\"\",\"\",\"\",\"\",\"\"]','[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]'); INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); - INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); +INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, `id_usuario_destino` FROM `tmensajes` WHERE `id_usuario_destino` != ''; COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index c9ae871185..f2634417fb 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -2003,7 +2003,7 @@ INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fi -- ---------------------------------------------------------------------- INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); - +INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, `id_usuario_destino` FROM `tmensajes` WHERE `id_usuario_destino` != ''; -- ---------------------------------------------------------------------- -- Add custom internal recon scripts -- ---------------------------------------------------------------------- From 8fb84e910af5e9a626b97290fa935b4e9dabc357 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 14:29:59 +0100 Subject: [PATCH 212/249] Minor SQL fixes discovery Former-commit-id: e2513e61ea6038f0bdb8f009619dcb92f07b992e --- pandora_console/extras/mr/25.sql | 2 +- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 +- pandora_console/pandoradb_data.sql | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index 7e562b188d..87a37b3b48 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -113,7 +113,7 @@ CREATE TABLE IF NOT EXISTS `tnotification_source_group_user`( INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fields_descriptions`, `fields_values`) VALUES ('Generate Notification','Internal type','This command allows you to send an internal notification to any user or group.',1,'[\"Destination user\",\"Destination group\",\"Title\",\"Message\",\"Link\",\"Criticity\",\"\",\"\",\"\",\"\",\"\"]','[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]'); INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); -INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); +INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Messages"; INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, `id_usuario_destino` FROM `tmensajes` WHERE `id_usuario_destino` != ''; COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index f2634417fb..e0e92f0a11 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -2002,7 +2002,7 @@ INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fi -- Update message references and pre-configure notifications -- ---------------------------------------------------------------------- INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); -INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); +INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Messages"; INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, `id_usuario_destino` FROM `tmensajes` WHERE `id_usuario_destino` != ''; -- ---------------------------------------------------------------------- -- Add custom internal recon scripts diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index bce6c85d1d..1ceeab65d8 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1285,6 +1285,6 @@ INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, ` INSERT INTO `tnotification_source_user`(`id_source`,`id_user`,`enabled`,`also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin",1,0); -INSERT INTO `tnotification_source_group` ((SELECT `id` FROM `tnotification_source` WHERE `description`="Messages"),0); +INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Messages"; \ No newline at end of file From 6409fc2dddae52a1af7c6d4d3b7efda849ae6804 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 15:07:51 +0100 Subject: [PATCH 213/249] Added discovery name convention to server files Former-commit-id: d432ac2c5526cc05b7cbb29df66aef60a35ab0e7 --- pandora_server/lib/PandoraFMS/Config.pm | 10 +++++++--- pandora_server/lib/PandoraFMS/DiscoveryServer.pm | 8 +++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/pandora_server/lib/PandoraFMS/Config.pm b/pandora_server/lib/PandoraFMS/Config.pm index 096903d6f4..0c959a5cb1 100644 --- a/pandora_server/lib/PandoraFMS/Config.pm +++ b/pandora_server/lib/PandoraFMS/Config.pm @@ -226,7 +226,7 @@ sub pandora_load_config { $pa_config->{"dataserver"} = 1; # default $pa_config->{"networkserver"} = 1; # default $pa_config->{"snmpconsole"} = 1; # default - $pa_config->{"reconserver"} = 1; # default + $pa_config->{"discoveryserver"} = 1; # default $pa_config->{"wmiserver"} = 1; # default $pa_config->{"pluginserver"} = 1; # default $pa_config->{"predictionserver"} = 1; # default @@ -254,6 +254,7 @@ sub pandora_load_config { $pa_config->{"plugin_threads"} = 2; # Introduced on 2.0 $pa_config->{"plugin_exec"} = '/usr/bin/timeout'; # 3.0 $pa_config->{"recon_threads"} = 2; # Introduced on 2.0 + $pa_config->{"discovery_threads"} = 2; # Introduced on 732 $pa_config->{"prediction_threads"} = 1; # Introduced on 2.0 $pa_config->{"plugin_timeout"} = 5; # Introduced on 2.0 $pa_config->{"wmi_threads"} = 2; # Introduced on 2.0 @@ -659,8 +660,8 @@ sub pandora_load_config { elsif ($parametro =~ m/^predictionserver\s+([0-9]*)/i){ $pa_config->{'predictionserver'}= clean_blank($1); } - elsif ($parametro =~ m/^reconserver\s+([0-9]*)/i) { - $pa_config->{'reconserver'}= clean_blank($1); + elsif ($parametro =~ m/^discoveryserver\s+([0-9]*)/i) { + $pa_config->{'discoveryserver'}= clean_blank($1); } elsif ($parametro =~ m/^reconserver\s+([0-9]*)/i) { $pa_config->{'reconserver'}= clean_blank($1); @@ -809,6 +810,9 @@ sub pandora_load_config { elsif ($parametro =~ m/^autocreate_group\s+([0-9*]*)/i) { $pa_config->{'autocreate_group'}= clean_blank($1); } + elsif ($parametro =~ m/^discovery_threads\s+([0-9]*)/i) { + $pa_config->{'discovery_threads'}= clean_blank($1); + } elsif ($parametro =~ m/^recon_threads\s+([0-9]*)/i) { $pa_config->{'recon_threads'}= clean_blank($1); } diff --git a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm index e43f1ca05a..137dffd822 100644 --- a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -100,7 +100,13 @@ sub run ($) { my $pa_config = $self->getConfig (); print_message ($pa_config, " [*] Starting " . $pa_config->{'rb_product_name'} . " Discovery Server.", 1); - $self->setNumThreads ($pa_config->{'recon_threads'}); + my $threads = $pa_config->{'recon_threads'}; + + # Use hightest value + if ($pa_config->{'discovery_threads'} > $pa_config->{'recon_threads'}) { + $threads = $pa_config->{'discovery_threads'}; + } + $self->setNumThreads($threads); $self->SUPER::run (\@TaskQueue, \%PendingTasks, $Sem, $TaskSem); } From e856969a59dd3fe02d934447d633ad7996553067 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Thu, 21 Feb 2019 15:13:27 +0100 Subject: [PATCH 214/249] Minor fix changed vmware_plugin reference to vmware-plugin Former-commit-id: 20e80bfffaf80583c320aa62d35e54f79e6ab03e --- pandora_console/extras/mr/25.sql | 2 +- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 +- pandora_console/pandoradb_data.sql | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index 87a37b3b48..7b3093497c 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -5,7 +5,7 @@ ALTER TABLE `trecon_task` ADD COLUMN `auth_strings` text; ALTER TABLE `trecon_task` ADD COLUMN `autoconfiguration_enabled` tinyint(1) unsigned default '0'; -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware_plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); CREATE TABLE IF NOT EXISTS `tevent_extended` ( diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index e0e92f0a11..ce92813d05 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -2007,5 +2007,5 @@ INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, -- ---------------------------------------------------------------------- -- Add custom internal recon scripts -- ---------------------------------------------------------------------- -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware_plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index 1ceeab65d8..8dd4d3011e 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1133,7 +1133,7 @@ INSERT INTO `treport_custom_sql` (`id`, `name`, `sql`) VALUES (4, 'Group vi -- trecon scripts INSERT INTO `trecon_script` VALUES (2,'IPMI Recon','Specific Pandora FMS Intel DCM Discovery (c) Artica ST 2011 <info@artica.es> Usage: ./ipmi-recon.pl <task_id> <group_id> <create_incident_flag> <custom_field1> <custom_field2> <custom_field3> <custom_field4> * custom_field1 = Network i.e.: 192.168.100.0/24 * custom_field2 = Username * custom_field3 = Password * custom_field4 = Additional parameters i.e.: -D LAN_2_0','/usr/share/pandora_server/util/recon_scripts/ipmi-recon.pl','{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Network\",\"help\":\"i.e.: 192.168.100.0/24\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"Username\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"3\":{\"macro\":\"_field3_\",\"desc\":\"Password\",\"help\":\"\",\"value\":\"\",\"hide\":\"1\"},\"4\":{\"macro\":\"_field4_\",\"desc\":\"Additional parameters\",\"help\":\"Optional additional parameters such as -D LAN_2_0 to use IPMI ver 2.0 instead of 1.5. These options will also be passed to the IPMI plugin when the current values are read.\",\"value\":\"\",\"hide\":\"\"}}'); INSERT INTO `trecon_script` VALUES (5,'WMI Recon Script','This script is used to automatically gather host information via WMI. Available parameters: * Network = network to scan (e.g. 192.168.100.0/24). * WMI auth = comma separated list of WMI authentication tokens in the format username%password (e.g. Administrador%pass). See the documentation for more information.','/usr/share/pandora_server/util/recon_scripts/wmi-recon.pl','{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Network\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"WMI auth\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"}}'); -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware_plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); INSERT INTO `tplugin` (`id`, `name`, `description`, `max_timeout`, `execute`, `plugin_type`, `macros`, `parameters`) VALUES (1,'IPMI Plugin','Plugin to get IPMI monitors from a IPMI Device.',0,'/usr/share/pandora_server/util/plugin/ipmi-plugin.pl',0,'{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Target IP\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"Username\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"3\":{\"macro\":\"_field3_\",\"desc\":\"Password\",\"help\":\"\",\"value\":\"\",\"hide\":\"true\"},\"4\":{\"macro\":\"_field4_\",\"desc\":\"Sensor\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"5\":{\"macro\":\"_field5_\",\"desc\":\"Additional Options\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"}}','-h _field1_ -u _field2_ -p _field3_ -s _field4_ -- _field5_'); From 9e9d915609b6500b8b52aa3b38019d895caeef0a Mon Sep 17 00:00:00 2001 From: fermin831 Date: Thu, 21 Feb 2019 15:35:44 +0100 Subject: [PATCH 215/249] Modified redirection Former-commit-id: 77dd6fee3a71064e790bd020afbcc91edbdfe20c --- .../godmode/wizards/DiscoveryTaskList.class.php | 7 +++++-- pandora_console/godmode/wizards/Wizard.main.php | 3 +++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index 0a7fa9b8e5..e075bb4f9e 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -295,7 +295,7 @@ class DiscoveryTaskList extends Wizard // Check if is a H&D, Cloud or Application. $data[8] = ' Date: Thu, 21 Feb 2019 18:00:50 +0100 Subject: [PATCH 217/249] discovery minor fixes Former-commit-id: 6d7a1a75bcb6844c839f34a2a2bfaf3f96734db8 --- pandora_console/godmode/servers/discovery.php | 5 ++++- .../wizards/DiscoveryTaskList.class.php | 18 ++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 261cdd0696..d7ee26de86 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -134,7 +134,10 @@ if ($classname_selected !== null) { ui_print_error_message($result['msg']); } - $classname_selected = null; + // Redirect to Tasklist. + $classname_selected = 'DiscoveryTaskList'; + $wiz = new $classname_selected($page); + $result = $wiz->run(); } } diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index e075bb4f9e..179d87b2a6 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -125,17 +125,23 @@ class DiscoveryTaskList extends Wizard $task = get_parameter('task', null); if ($task !== null) { - db_process_sql_delete( + $result = db_process_sql_delete( 'trecon_task', ['id_rt' => $task] ); + + if ($result == 1) { + return [ + 'result' => 0, + 'msg' => __('Task successfully deleted'), + 'id' => false, + ]; + } + + // Trick to avoid double execution. + header('Location: '.$this->url); } - return [ - 'result' => 0, - 'msg' => __('Task successfully deleted'), - 'id' => false, - ]; } From 45bba4faa82e6ebee1c3e415be18c5f9f57aa3e4 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Thu, 21 Feb 2019 19:00:47 +0100 Subject: [PATCH 218/249] fix agent name input Former-commit-id: 51b7566719392d1cc43ca04a9ec91ae007e73feb --- pandora_console/godmode/agentes/agent_manager.php | 2 +- pandora_console/godmode/agentes/configurar_agente.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index 059f5fdba6..44ff373089 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -229,7 +229,7 @@ if (!$new_agent) { $table->data[0][1] .= "  ".html_print_image('images/cross.png', true, ['title' => __('Delete agent')]).''; } -$table->data[1][0] = __('Alias').ui_print_help_tip(__('Characters /,\,|,%,#,&,$ are not allowed'), true).''; +$table->data[1][0] = __('Alias').ui_print_help_tip(__('Characters /,\,|,%,#,&,$ will be ignored'), true).''; $table->data[1][1] = html_print_input_text('alias', $alias, '', 50, 100, true); if ($new_agent) { $table->data[1][1] .= html_print_checkbox('alias_as_name', 1, $config['alias_as_name'], true).__('Use alias as name'); diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index 5e68f0140c..4d000e7cb7 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -158,8 +158,8 @@ $module_macros = []; // Create agent if ($create_agent) { $mssg_warning = 0; - $alias = trim (preg_replace('/[\/\\\|%#&$-]/', '', - html_entity_decode( str_replace('`','‘',(string) get_parameter_post ("alias", ""))))); + $alias_safe_output = io_safe_output(get_parameter("alias","")); + $alias = io_safe_input(trim (preg_replace('/[\/\\\|%#&$-]/', '', $alias_safe_output))); $alias_as_name = (int) get_parameter_post('alias_as_name', 0); $direccion_agente = (string) get_parameter_post('direccion', ''); @@ -756,8 +756,8 @@ if ($update_agent) { $mssg_warning = 0; $id_agente = (int) get_parameter_post('id_agente'); $nombre_agente = str_replace('`', '‘', (string) get_parameter_post('agente', '')); - $alias = trim (preg_replace('/[\/\\\|%#&$-]/', '', - html_entity_decode( str_replace('`','‘',(string) get_parameter_post ("alias", ""))))); + $alias_safe_output = io_safe_output(get_parameter("alias","")); + $alias = io_safe_input(trim (preg_replace('/[\/\\\|%#&$-]/', '', $alias_safe_output))); $alias_as_name = (int) get_parameter_post('alias_as_name', 0); $direccion_agente = (string) get_parameter_post('direccion', ''); // safe_output only validate ip From b1149a053b6843d7511ee4f2e1220341b01e7969 Mon Sep 17 00:00:00 2001 From: artica Date: Fri, 22 Feb 2019 00:01:38 +0100 Subject: [PATCH 219/249] Auto-updated build strings. Former-commit-id: f642e8fe029c7df7a017abe433d7768acd8577fd --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index f2e2716ce1..f10b529fae 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190221 +Version: 7.0NG.731-190222 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 94f34a4668..643a45d94b 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190221" +pandora_version="7.0NG.731-190222" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 62bdfa27c4..35e3778268 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190221'; +use constant AGENT_BUILD => '190222'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 1da259f475..f3553ff260 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190221 +%define release 190222 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 29f52b8786..6e8c3e5e17 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190221 +%define release 190222 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index 77d78eedc4..66e4dff894 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190221" +PI_BUILD="190222" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index 9bf66cb5c5..2adedc7f16 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190221} +{190222} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 0dcf04a6c3..fc84e962be 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190221)") +#define PANDORA_VERSION ("7.0NG.731(Build 190222)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 7fd8ea3934..f7c69dbdb2 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190221))" + VALUE "ProductVersion", "(7.0NG.731(Build 190222))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index b98caca698..7909803fb6 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190221 +Version: 7.0NG.731-190222 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 49e1bea485..13c27c15d3 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190221" +pandora_version="7.0NG.731-190222" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 204a7e4ee2..f4275aa61b 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190221'; +$build_version = 'PC190222'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index 862e7088e8..b297466f99 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@
        [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index edbec0e764..432a065155 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190221 +%define release 190222 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 1981838514..16e17d6699 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190221 +%define release 190222 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index d6f5c866f8..246c29ace3 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190221" +PI_BUILD="190222" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index fece0dc080..1c957ce03c 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190221"; +my $version = "7.0NG.731 PS190222"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 9bbf4896cd..3dfb41f520 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190221"; +my $version = "7.0NG.731 PS190222"; # save program name for logging my $progname = basename($0); From 42448cf0d812cfad32c94f84e47eb74c0135319a Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 22 Feb 2019 10:41:54 +0100 Subject: [PATCH 220/249] Updated path for discovery plugins Former-commit-id: 222373efee3c768619d5f301f3ae291009901e64 --- pandora_console/extras/mr/25.sql | 4 ++-- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 4 ++-- pandora_console/pandoradb_data.sql | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index 7b3093497c..2a3eb9a297 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -5,8 +5,8 @@ ALTER TABLE `trecon_task` ADD COLUMN `auth_strings` text; ALTER TABLE `trecon_task` ADD COLUMN `autoconfiguration_enabled` tinyint(1) unsigned default '0'; -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/recon_scripts/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/recon_scripts/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); CREATE TABLE IF NOT EXISTS `tevent_extended` ( `id` serial PRIMARY KEY, diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index ce92813d05..c4f2325bb6 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -2007,5 +2007,5 @@ INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, -- ---------------------------------------------------------------------- -- Add custom internal recon scripts -- ---------------------------------------------------------------------- -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/recon_scripts/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/recon_scripts/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index 8dd4d3011e..2b8245d849 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1133,8 +1133,8 @@ INSERT INTO `treport_custom_sql` (`id`, `name`, `sql`) VALUES (4, 'Group vi -- trecon scripts INSERT INTO `trecon_script` VALUES (2,'IPMI Recon','Specific Pandora FMS Intel DCM Discovery (c) Artica ST 2011 <info@artica.es> Usage: ./ipmi-recon.pl <task_id> <group_id> <create_incident_flag> <custom_field1> <custom_field2> <custom_field3> <custom_field4> * custom_field1 = Network i.e.: 192.168.100.0/24 * custom_field2 = Username * custom_field3 = Password * custom_field4 = Additional parameters i.e.: -D LAN_2_0','/usr/share/pandora_server/util/recon_scripts/ipmi-recon.pl','{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Network\",\"help\":\"i.e.: 192.168.100.0/24\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"Username\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"3\":{\"macro\":\"_field3_\",\"desc\":\"Password\",\"help\":\"\",\"value\":\"\",\"hide\":\"1\"},\"4\":{\"macro\":\"_field4_\",\"desc\":\"Additional parameters\",\"help\":\"Optional additional parameters such as -D LAN_2_0 to use IPMI ver 2.0 instead of 1.5. These options will also be passed to the IPMI plugin when the current values are read.\",\"value\":\"\",\"hide\":\"\"}}'); INSERT INTO `trecon_script` VALUES (5,'WMI Recon Script','This script is used to automatically gather host information via WMI. Available parameters: * Network = network to scan (e.g. 192.168.100.0/24). * WMI auth = comma separated list of WMI authentication tokens in the format username%password (e.g. Administrador%pass). See the documentation for more information.','/usr/share/pandora_server/util/recon_scripts/wmi-recon.pl','{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Network\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"WMI auth\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"}}'); -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/plugin/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); -INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/plugin/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Application.VMware', 'Discovery Application script to monitor VMware technologies (ESXi, VCenter, VSphere)', '/usr/share/pandora_server/util/recon_scripts/vmware-plugin.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); +INSERT INTO `trecon_script` (`name`,`description`,`script`,`macros`) VALUES ('Discovery.Cloud', 'Discovery Cloud script to monitor Cloud technologies (AWS.EC2, AWS.S3, AWS.RDS, RDS,ȊWS.EKS)', '/usr/share/pandora_server/util/recon_scripts/pcm_client.pl', '{"1":{"macro":"_field1_","desc":"Configuration file","help":"","value":"","hide":""}}'); INSERT INTO `tplugin` (`id`, `name`, `description`, `max_timeout`, `execute`, `plugin_type`, `macros`, `parameters`) VALUES (1,'IPMI Plugin','Plugin to get IPMI monitors from a IPMI Device.',0,'/usr/share/pandora_server/util/plugin/ipmi-plugin.pl',0,'{\"1\":{\"macro\":\"_field1_\",\"desc\":\"Target IP\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"2\":{\"macro\":\"_field2_\",\"desc\":\"Username\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"3\":{\"macro\":\"_field3_\",\"desc\":\"Password\",\"help\":\"\",\"value\":\"\",\"hide\":\"true\"},\"4\":{\"macro\":\"_field4_\",\"desc\":\"Sensor\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"},\"5\":{\"macro\":\"_field5_\",\"desc\":\"Additional Options\",\"help\":\"\",\"value\":\"\",\"hide\":\"\"}}','-h _field1_ -u _field2_ -p _field3_ -s _field4_ -- _field5_'); From e65d128b25e1cf8a03f4736995d1e7159bd757d7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 22 Feb 2019 12:40:02 +0100 Subject: [PATCH 221/249] minor fix db schema Former-commit-id: a4f87c1c7fd9da0f16a37f75cb5029ac6694baef --- pandora_console/extras/mr/25.sql | 2 +- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 +- pandora_console/pandoradb_data.sql | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index 2a3eb9a297..bcf6d041d7 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -113,7 +113,7 @@ CREATE TABLE IF NOT EXISTS `tnotification_source_group_user`( INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fields_descriptions`, `fields_values`) VALUES ('Generate Notification','Internal type','This command allows you to send an internal notification to any user or group.',1,'[\"Destination user\",\"Destination group\",\"Title\",\"Message\",\"Link\",\"Criticity\",\"\",\"\",\"\",\"\",\"\"]','[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]'); INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); -INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Messages"; +INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Message"; INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, `id_usuario_destino` FROM `tmensajes` WHERE `id_usuario_destino` != ''; COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index c4f2325bb6..aa71ce277a 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -2002,7 +2002,7 @@ INSERT INTO `talert_commands` (`name`, `command`, `description`, `internal`, `fi -- Update message references and pre-configure notifications -- ---------------------------------------------------------------------- INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin", 1, 0); -INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Messages"; +INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Message"; INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, `id_usuario_destino` FROM `tmensajes` WHERE `id_usuario_destino` != ''; -- ---------------------------------------------------------------------- -- Add custom internal recon scripts diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index 2b8245d849..a9b0b25778 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1285,6 +1285,6 @@ INSERT INTO `tnotification_source`(`description`, `icon`, `max_postpone_time`, ` INSERT INTO `tnotification_source_user`(`id_source`,`id_user`,`enabled`,`also_mail`) VALUES ((SELECT `id` FROM `tnotification_source` WHERE `description`="System status"), "admin",1,0); -INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Messages"; +INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Message"; \ No newline at end of file From 3d2bfa95b5f5af70b830338c8c8446d5b7103366 Mon Sep 17 00:00:00 2001 From: daniel Date: Fri, 22 Feb 2019 12:53:35 +0100 Subject: [PATCH 222/249] add table console task in discovery Former-commit-id: b13571167c063188102a8473fb57fa63c18bece3 --- .../wizards/DiscoveryTaskList.class.php | 542 +++++++++++++++++- pandora_console/include/functions_cron.php | 458 +++++++++++++-- 2 files changed, 942 insertions(+), 58 deletions(-) diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index 179d87b2a6..af6c371b67 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -28,6 +28,8 @@ require_once __DIR__.'/Wizard.main.php'; require_once $config['homedir'].'/include/functions_users.php'; +require_once $config['homedir'].'/include/functions_reports.php'; +require_once $config['homedir'].'/include/functions_cron.php'; /** * Defined as wizard to guide user to explore running tasks. @@ -77,13 +79,22 @@ class DiscoveryTaskList extends Wizard // Load styles. parent::run(); - $delete = (bool) get_parameter('delete', false); + $force_run = (bool) get_parameter('force_run'); + if ($force_run === true) { + return $this->forceConsoleTask(); + } - if ($delete) { + $delete_console_task = (bool) get_parameter('delete_console_task'); + if ($delete_console_task === true) { + return $this->deleteConsoleTask(); + } + + $delete = (bool) get_parameter('delete', false); + if ($delete === true) { return $this->deleteTask(); } - return $this->showList(); + return $this->showListConsoleTask().''.$this->showList(); } @@ -145,6 +156,76 @@ class DiscoveryTaskList extends Wizard } + /** + * Force console task. + * + * @return void + */ + public function forceConsoleTask() + { + global $config; + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access recon task viewer' + ); + include 'general/noaccess.php'; + return; + } + + $id_console_task = (int) get_parameter('id_console_task'); + + if ($id_console_task !== null) { + cron_task_run($id_console_task, true); + // Trick to avoid double execution. + header('Location: '.$this->url); + } + + } + + + /** + * Delete a Console task. + * + * @return void + */ + public function deleteConsoleTask() + { + global $config; + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access recon task viewer' + ); + include 'general/noaccess.php'; + return; + } + + $id_console_task = (int) get_parameter('id_console_task'); + + if ($id_console_task !== null) { + $result = db_process_sql_delete( + 'tuser_task_scheduled', + ['id' => $id_console_task] + ); + + if ($result == 1) { + return [ + 'result' => 0, + 'msg' => __('Console Task successfully deleted'), + 'id' => false, + ]; + } + + // Trick to avoid double execution. + header('Location: '.$this->url); + } + + } + + /** * Show complete list of running tasks. * @@ -203,7 +284,30 @@ class DiscoveryTaskList extends Wizard foreach ($servers as $serverItem) { $id_server = $serverItem['id_server']; $server_name = servers_get_name($id_server); - $recon_tasks = db_get_all_rows_field_filter('trecon_task', 'id_recon_server', $id_server); + $recon_tasks = db_get_all_rows_field_filter( + 'trecon_task', + 'id_recon_server', + $id_server + ); + + $user_groups = implode(',', array_keys(users_get_groups())); + $defined_tasks = db_get_all_rows_filter( + 'tuser_task_scheduled', + 'id_grupo IN ('.$user_groups.')' + ); + + if (isset($tasks_console) === true + && is_array($tasks_console) === true + ) { + foreach ($tasks_console as $key => $value) { + $value['parameters'] = unserialize( + $value['parameters'] + ); + + $value['type'] = 'Cron'; + array_push($recon_tasks, $value); + } + } // Show network tasks for Recon Server. if ($recon_tasks === false) { @@ -265,7 +369,9 @@ class DiscoveryTaskList extends Wizard $data[1] = ''.$task['name'].''; - $data[2] = human_time_description_raw($task['interval_sweep']); + $data[2] = human_time_description_raw( + $task['interval_sweep'] + ); if ($task['id_recon_script'] == 0) { $data[3] = $task['subnet']; @@ -281,23 +387,51 @@ class DiscoveryTaskList extends Wizard if ($task['id_recon_script'] == 0) { // Network recon task. - $data[5] = html_print_image('images/network.png', true, ['title' => __('Network recon task')]).'  '; - $data[5] .= network_profiles_get_name($task['id_network_profile']); + $data[5] = html_print_image( + 'images/network.png', + true, + ['title' => __('Network recon task')] + ).'  '; + $data[5] .= network_profiles_get_name( + $task['id_network_profile'] + ); } else { // APP recon task. - $data[5] = html_print_image('images/plugin.png', true).'  '; - $data[5] .= db_get_sql(sprintf('SELECT name FROM trecon_script WHERE id_recon_script = %d', $task['id_recon_script'])); + $data[5] = html_print_image( + 'images/plugin.png', + true + ).'  '; + $data[5] .= db_get_sql( + sprintf( + 'SELECT name FROM trecon_script WHERE id_recon_script = %d', + $task['id_recon_script'] + ) + ); } if ($task['status'] <= 0 || $task['status'] > 100) { $data[6] = '-'; } else { - $data[6] = progress_bar($task['status'], 100, 20, __('Progress').':'.$task['status'].'%', 1); + $data[6] = progress_bar( + $task['status'], + 100, + 20, + __('Progress').':'.$task['status'].'%', + 1 + ); } - $data[7] = ui_print_timestamp($task['utimestamp'], true); + $data[7] = ui_print_timestamp( + $task['utimestamp'], + true + ); - if (check_acl($config['id_user'], $task['id_group'], 'PM')) { + if (check_acl( + $config['id_user'], + $task['id_group'], + 'PM' + ) + ) { // Check if is a H&D, Cloud or Application. $data[8] = ''.html_print_image( - 'images/wrench_orange.png', + 'images/config.png', true ).''; $data[8] .= ''.html_print_image( + ).'" onClick="if (!confirm(\' '.__('Are you sure?').'\')) return false;">'.html_print_image( 'images/cross.png', true ).''; @@ -325,6 +459,7 @@ class DiscoveryTaskList extends Wizard if (empty($table->data)) { echo '
        '.__('Server').' '.$server_name.' '.__('has no recon tasks assigned').'
        '; } else { + echo '

        '.__('Server task').'

        '; html_print_table($table); } @@ -359,6 +494,385 @@ class DiscoveryTaskList extends Wizard } + /** + * Show complete list of running tasks. + * + * @return boolean Success or not. + */ + public function showListConsoleTask() + { + global $config; + + check_login(); + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access recon task viewer' + ); + include 'general/noaccess.php'; + return false; + } + + $read_perms = check_acl( + $config['id_user'], + 0, + 'RR' + ); + $write_perms = check_acl( + $config['id_user'], + 0, + 'RW' + ); + $manage_perms = check_acl( + $config['id_user'], + 0, + 'RM' + ); + $manage_pandora = check_acl( + $config['id_user'], + 0, + 'PM' + ); + + $url = 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist&'; + + $user_groups = implode( + ',', + array_keys(users_get_groups()) + ); + + $defined_tasks = db_get_all_rows_filter( + 'tuser_task_scheduled', + 'id_grupo IN ('.$user_groups.')' + ); + + if (!check_acl($config['id_user'], 0, 'PM')) { + $read_tasks = []; + foreach ($defined_tasks as $task) { + $function_name = db_get_value( + 'function_name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + if (($function_name != 'cron_task_execute_custom_script') + && ($function_name != 'cron_task_do_backup') + ) { + $read_tasks[] = $task; + } + } + + $defined_tasks = $read_tasks; + + if (empty($defined_tasks)) { + $defined_tasks = false; + } + } + + if ($defined_tasks !== false) { + echo '

        '.__('Console task').'

        '; + + $table = new stdClass(); + $table->class = 'databox data'; + $table->width = '100%'; + $table->data = []; + $table->head = []; + $table->head[0] = ''; + $table->head[1] = __('User'); + $table->head[2] = __('Task'); + $table->head[3] = __('Scheduled'); + $table->head[4] = __('Next execution'); + $table->head[5] = __('Last run'); + $table->head[6] = __('Group'); + $table->head[7] = __('Operations'); + $table->align[7] = 'left'; + + foreach ($defined_tasks as $task) { + $data = []; + + $function_name = db_get_value( + 'function_name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + switch ($function_name) { + case 'cron_task_generate_report': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + $args = unserialize($task['args']); + $report = reports_get_report($args[0]); + + // Check ACL in reports_get_report return false. + if ($report === false) { + continue; + } + + $email = $args[1]; + $data[2] .= '
        - '.__('Report').": "; + $data[2] .= $report['name'].''; + $data[2] .= '
        - '.__('Email').": "; + $data[2] .= ui_print_truncate_text( + $email, + 60, + false + ).''; + break; + + case 'cron_task_generate_report_by_template': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + $args = unserialize($task['args']); + + $filter = []; + $filter['id_report'] = $args[0]; + $template = db_get_row_filter( + 'treport_template', + $filter, + false + ); + + // Check ACL in reports_get_report return false. + if ($template === false) { + continue; + } + + $agents_id = $args[1]; + $id_group = $args[2]; + $report_per_agent = $args[0]; + $report_name = $args[3]; + $email = $args[4]; + $data[2] .= '
        - '.__('Template').": ".$template['name'].''; + $data[2] .= '
        - '.__('Agents').': '.$agents_id.''; + $data[2] .= '
        - '.__('Report per agent').': '.$report_per_agent.''; + $data[2] .= '
        - '.__('Report name').': '.$report_name.''; + $data[2] .= '
        - '.__('Email').": ".$email.''; + break; + + case 'cron_task_execute_custom_script': + if ($manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + $args = unserialize($task['args']); + $data[2] .= '
        - '.__('Custom script').': '.$args[0]; + break; + + case 'cron_task_save_report_to_disk': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + $args = unserialize($task['args']); + $report = reports_get_report($args[0]); + + // Check ACL in reports_get_report return false. + if ($report === false) { + continue; + } + + $path = $args[1]; + $data[2] .= '
        - '.__('Report').": ".$report['name'].''; + $data[2] .= '
        - '.__('Path').': '.$path.''; + break; + + case 'cron_task_save_xml_report_to_disk': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value('name', 'tuser_task', 'id', $task['id_user_task']); + $args = unserialize($task['args']); + $report = reports_get_report($args[0]); + + // Check ACL in reports_get_report return false. + if ($report === false) { + continue; + } + + $path = $args[1]; + $data[2] .= '
        - '.__('Report').": ".$report['name'].''; + $data[2] .= '
        - '.__('Path').': '.$path.''; + break; + + case 'cron_task_do_backup': + if ($manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + $args = unserialize($task['args']); + break; + + default: + // Ignore. + break; + } + + $data[3] = cron_get_scheduled_string($task['scheduled']); + $data[4] = date('Y/m/d H:i:s', $args['first_execution']); + $data[5] = empty($task['last_run']) ? __('Never') : date('Y/m/d H:i:s', $task['last_run']); + + $data[6] = ui_print_group_icon($task['id_grupo'], true); + + if ($function_name == 'cron_task_do_backup' || $function_name == 'cron_task_execute_custom_script') { + if ($manage_pandora) { + $data[7] = ''; + $data[7] .= html_print_image( + 'images/config.png', + true, + ['title' => __('Edit')] + ); + $data[7] .= ''; + } + + if ($manage_pandora) { + $data[7] .= ''; + $data[7] .= html_print_image( + 'images/cross.png', + true, + ['title' => __('Delete')] + ); + $data[7] .= ''; + } + } else { + if ($write_perms || $manage_pandora) { + $data[7] = ''; + $data[7] .= html_print_image( + 'images/config.png', + true, + ['title' => __('Edit')] + ); + $data[7] .= ''; + } + + if ($manage_perms || $manage_pandora) { + $data[7] .= ''; + $data[7] .= html_print_image( + 'images/cross.png', + true, + ['title' => __('Delete')] + ); + $data[7] .= ''; + } + } + + array_push($table->data, $data); + } + + html_print_table($table); + } + + return true; + } + + /** * Return target url sub-string to edit target task. * diff --git a/pandora_console/include/functions_cron.php b/pandora_console/include/functions_cron.php index f67204d5ba..e56a3d4a52 100644 --- a/pandora_console/include/functions_cron.php +++ b/pandora_console/include/functions_cron.php @@ -15,17 +15,23 @@ global $config; require_once $config['homedir'].'/include/functions_db.php'; -// Update the execution interval of the given module +// Update the execution interval of the given module. function cron_update_module_interval($module_id, $cron) { - // Check for a valid cron + // Check for a valid cron. if (!cron_check_syntax($cron)) { return; } if ($cron == '* * * * *') { - $module_interval = db_get_value_filter('module_interval', 'tagente_modulo', ['id_agente_modulo' => $module_id]); - return db_process_sql('UPDATE tagente_estado SET current_interval = '.$module_interval.' WHERE id_agente_modulo = '.(int) $module_id); + $module_interval = db_get_value_filter( + 'module_interval', + 'tagente_modulo', + ['id_agente_modulo' => $module_id] + ); + return db_process_sql( + 'UPDATE tagente_estado SET current_interval = '.$module_interval.' WHERE id_agente_modulo = '.(int) $module_id + ); } else { return db_process_sql( 'UPDATE tagente_estado SET current_interval = '.cron_next_execution($cron, $module_interval, $module_id).' WHERE id_agente_modulo = '.(int) $module_id @@ -38,7 +44,7 @@ function cron_update_module_interval($module_id, $cron) // Get the number of seconds left to the next execution of the given cron entry. function cron_next_execution($cron, $module_interval, $module_id) { - // Get day of the week and month from cron config + // Get day of the week and month from cron config. $cron_array = explode(' ', $cron); $minute = $cron_array[0]; $hour = $cron_array[1]; @@ -46,21 +52,34 @@ function cron_next_execution($cron, $module_interval, $module_id) $month = $cron_array[3]; $wday = $cron_array[4]; - // Get last execution time - $last_execution = db_get_value('utimestamp', 'tagente_estado', 'id_agente_modulo', $module_id); + // Get last execution time. + $last_execution = db_get_value( + 'utimestamp', + 'tagente_estado', + 'id_agente_modulo', + $module_id + ); $cur_time = ($last_execution !== false) ? $last_execution : time(); - // Any day of the way + // Any day of the way. if ($wday == '*') { - $nex_time = cron_next_execution_date($cron, $cur_time, $module_interval); + $nex_time = cron_next_execution_date( + $cron, + $cur_time, + $module_interval + ); return ($nex_time - $cur_time); } - // A specific day of the week + // A specific day of the week. $count = 0; $nex_time = $cur_time; do { - $nex_time = cron_next_execution_date($cron, $nex_time, $module_interval); + $nex_time = cron_next_execution_date( + $cron, + $nex_time, + $module_interval + ); $nex_time_wd = $nex_time; $array_nex = explode(' ', date('m w', $nex_time_wd)); @@ -68,12 +87,12 @@ function cron_next_execution($cron, $module_interval, $module_id) $nex_wday = $array_nex[1]; do { - // Check the day of the week + // Check the day of the week. if ($nex_wday == $wday) { return ($nex_time_wd - $cur_time); } - // Move to the next day of the month + // Move to the next day of the month. $nex_time_wd += SECONDS_1DAY; $array_nex_w = explode(' ', date('m w', $nex_time_wd)); @@ -84,7 +103,7 @@ function cron_next_execution($cron, $module_interval, $module_id) $count++; } while ($count < SECONDS_1MINUTE); - // Something went wrong, default to 5 minutes + // Something went wrong, default to 5 minutes. return SECONDS_5MINUTES; } @@ -92,11 +111,11 @@ function cron_next_execution($cron, $module_interval, $module_id) // Get the next execution date for the given cron entry in seconds since epoch. function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) { - // Get cron configuration + // Get cron configuration. $cron_array = explode(' ', $cron); // REMARKS: Months start from 1 in php (different to server) - // Get current time + // Get current time. if ($cur_time === false) { $cur_time = time(); } @@ -107,7 +126,7 @@ function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) return $nex_time; } - // Update minutes + // Update minutes. $min_s = cron_get_interval($cron_array[0]); $nex_time_array[0] = ($min_s['down'] == '*') ? 0 : $min_s['down']; @@ -118,22 +137,22 @@ function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) } } - // Check if next hour is in cron + // Check if next hour is in cron. $nex_time_array[1]++; $nex_time = cron_valid_date($nex_time_array); if ($nex_time === false) { - // Update the month day if overflow + // Update the month day if overflow. $nex_time_array[1] = 0; $nex_time_array[2]++; $nex_time = cron_valid_date($nex_time_array); if ($nex_time === false) { - // Update the month if overflow + // Update the month if overflow. $nex_time_array[2] = 1; $nex_time_array[3]++; $nex_time = cron_valid_date($nex_time_array); if ($nex_time === false) { - // Update the year if overflow + // Update the year if overflow. $nex_time_array[3] = 1; $nex_time_array[4]++; $nex_time = cron_valid_date($nex_time_array); @@ -141,16 +160,16 @@ function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) } } - // Check the hour + // Check the hour. if (cron_is_in_cron($cron_array, $nex_time_array) && $nex_time) { return $nex_time; } - // Update the hour if fails + // Update the hour if fails. $hour_s = cron_get_interval($cron_array[1]); $nex_time_array[1] = ($hour_s['down'] == '*') ? 0 : $hour_s['down']; - // When an overflow is passed check the hour update again + // When an overflow is passed check the hour update again. $nex_time = cron_valid_date($nex_time_array); if ($nex_time >= $cur_time) { if (cron_is_in_cron($cron_array, $nex_time_array) && $nex_time) { @@ -158,32 +177,32 @@ function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) } } - // Check if next day is in cron + // Check if next day is in cron. $nex_time_array[2]++; $nex_time = cron_valid_date($nex_time_array); if ($nex_time === false) { - // Update the month if overflow + // Update the month if overflow. $nex_time_array[2] = 1; $nex_time_array[3]++; $nex_time = cron_valid_date($nex_time_array); if ($nex_time === false) { - // Update the year if overflow + // Update the year if overflow. $nex_time_array[3] = 1; $nex_time_array[4]++; $nex_time = cron_valid_date($nex_time_array); } } - // Check the day + // Check the day. if (cron_is_in_cron($cron_array, $nex_time_array) && $nex_time) { return $nex_time; } - // Update the day if fails + // Update the day if fails. $mday_s = cron_get_interval($cron_array[2]); $nex_time_array[2] = ($mday_s['down'] == '*') ? 1 : $mday_s['down']; - // When an overflow is passed check the hour update in the next execution + // When an overflow is passed check the hour update in the next execution. $nex_time = cron_valid_date($nex_time_array); if ($nex_time >= $cur_time) { if (cron_is_in_cron($cron_array, $nex_time_array) && $nex_time) { @@ -191,26 +210,26 @@ function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) } } - // Check if next month is in cron + // Check if next month is in cron. $nex_time_array[3]++; $nex_time = cron_valid_date($nex_time_array); if ($nex_time === false) { - // Update the year if overflow + // Update the year if overflow. $nex_time_array[3] = 1; $nex_time_array[4]++; $nex_time = cron_valid_date($nex_time_array); } - // Check the month + // Check the month. if (cron_is_in_cron($cron_array, $nex_time_array) && $nex_time) { return $nex_time; } - // Update the month if fails + // Update the month if fails. $mon_s = cron_get_interval($cron_array[3]); $nex_time_array[3] = ($mon_s['down'] == '*') ? 1 : $mon_s['down']; - // When an overflow is passed check the hour update in the next execution + // When an overflow is passed check the hour update in the next execution. $nex_time = cron_valid_date($nex_time_array); if ($nex_time >= $cur_time) { if (cron_is_in_cron($cron_array, $nex_time_array) && $nex_time) { @@ -218,7 +237,7 @@ function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) } } - // Update the year + // Update the year. $nex_time_array[4]++; $nex_time = cron_valid_date($nex_time_array); @@ -226,10 +245,10 @@ function cron_next_execution_date($cron, $cur_time=false, $module_interval=300) } -// Get an array with the cron interval +// Get an array with the cron interval. function cron_get_interval($element) { - // Not a range + // Not a range. if (!preg_match('/(\d+)\-(\d+)/', $element, $capture)) { return [ 'down' => $element, @@ -250,12 +269,12 @@ function cron_is_in_cron($elems_cron, $elems_curr_time) $elem_cron = array_shift($elems_cron); $elem_curr_time = array_shift($elems_curr_time); - // If there is no elements means that is in cron + // If there is no elements means that is in cron. if ($elem_cron === null || $elem_curr_time === null) { return true; } - // Go to last element if current is a wild card + // Go to last element if current is a wild card. if ($elem_cron != '*') { $elem_s = cron_get_interval($elem_cron); // Check if there is no a range @@ -263,7 +282,7 @@ function cron_is_in_cron($elems_cron, $elems_curr_time) return false; } - // Check if there is on the range + // Check if there is on the range. if ($elem_s['up'] !== false) { if ($elem_s['down'] < $elem_s['up']) { if ($elem_curr_time < $elem_s['down'] || $elem_curr_time > $elem_s['up']) { @@ -283,14 +302,365 @@ function cron_is_in_cron($elems_cron, $elems_curr_time) function cron_valid_date($da) { - $st = sprintf('%04d:%02d:%02d %02d:%02d:00', $da[4], $da[3], $da[2], $da[1], $da[0]); + $st = sprintf( + '%04d:%02d:%02d %02d:%02d:00', + $da[4], + $da[3], + $da[2], + $da[1], + $da[0] + ); $time = strtotime($st); return $time; } -// Check if cron is properly constructed +// Check if cron is properly constructed. function cron_check_syntax($cron) { - return preg_match('/^[\d|\*].* .*[\d|\*].* .*[\d|\*].* .*[\d|\*].* .*[\d|\*]$/', $cron); + return preg_match( + '/^[\d|\*].* .*[\d|\*].* .*[\d|\*].* .*[\d|\*].* .*[\d|\*]$/', + $cron + ); +} + + +function cron_list_table() +{ + global $config; + + $read_perms = check_acl($config['id_user'], 0, 'RR'); + $write_perms = check_acl($config['id_user'], 0, 'RW'); + $manage_perms = check_acl($config['id_user'], 0, 'RM'); + $manage_pandora = check_acl($config['id_user'], 0, 'PM'); + + $url = 'index.php?extension_in_menu=gservers&sec=extensions&sec2=enterprise/extensions/cron&'; + + $user_groups = implode( + ',', + array_keys(users_get_groups()) + ); + + $defined_tasks = db_get_all_rows_filter( + 'tuser_task_scheduled', + 'id_grupo IN ('.$user_groups.')' + ); + + if (!check_acl($config['id_user'], 0, 'PM')) { + $read_tasks = []; + foreach ($defined_tasks as $task) { + $function_name = db_get_value( + 'function_name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + if (($function_name != 'cron_task_execute_custom_script') + && ($function_name != 'cron_task_do_backup') + ) { + $read_tasks[] = $task; + } + } + + $defined_tasks = $read_tasks; + + if (empty($defined_tasks)) { + $defined_tasks = false; + } + } + + if ($defined_tasks !== false) { + echo '

        '.__('Scheduled jobs').'

        '; + + $table = new stdClass(); + $table->class = 'databox data'; + $table->width = '100%'; + $table->data = []; + $table->head = []; + $table->head[0] = ''; + $table->head[1] = __('User'); + $table->head[2] = __('Task'); + $table->head[3] = __('Scheduled'); + $table->head[4] = __('Next execution'); + $table->head[5] = __('Last run'); + $table->head[6] = __('Group'); + $table->head[7] = __('Actions'); + $table->align[7] = 'left'; + + foreach ($defined_tasks as $task) { + $data = []; + + $function_name = db_get_value( + 'function_name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + switch ($function_name) { + case 'cron_task_generate_report': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + $args = unserialize($task['args']); + $report = reports_get_report($args[0]); + + // Check ACL in reports_get_report return false. + if ($report === false) { + continue; + } + + $email = $args[1]; + $data[2] .= '
        - '.__('Report').": "; + $data[2] .= $report['name'].''; + $data[2] .= '
        - '.__('Email').": "; + $data[2] .= ui_print_truncate_text($email, 60, false).''; + break; + + case 'cron_task_generate_report_by_template': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + $args = unserialize($task['args']); + + $filter = []; + $filter['id_report'] = $args[0]; + $template = db_get_row_filter( + 'treport_template', + $filter, + false + ); + + // Check ACL in reports_get_report return false. + if ($template === false) { + continue; + } + + $agents_id = $args[1]; + $id_group = $args[2]; + $report_per_agent = $args[0]; + $report_name = $args[3]; + $email = $args[4]; + $data[2] .= '
        - '.__('Template').": ".$template['name'].''; + $data[2] .= '
        - '.__('Agents').': '.$agents_id.''; + $data[2] .= '
        - '.__('Report per agent').': '.$report_per_agent.''; + $data[2] .= '
        - '.__('Report name').': '.$report_name.''; + $data[2] .= '
        - '.__('Email').": ".$email.''; + break; + + case 'cron_task_execute_custom_script': + if ($manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + $args = unserialize($task['args']); + $data[2] .= '
        - '.__('Custom script').': '.$args[0]; + break; + + case 'cron_task_save_report_to_disk': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + + $args = unserialize($task['args']); + $report = reports_get_report($args[0]); + + // Check ACL in reports_get_report return false. + if ($report === false) { + continue; + } + + $path = $args[1]; + $data[2] .= '
        - '.__('Report').": ".$report['name'].''; + $data[2] .= '
        - '.__('Path').': '.$path.''; + break; + + case 'cron_task_save_xml_report_to_disk': + if ($write_perms || $manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value('name', 'tuser_task', 'id', $task['id_user_task']); + $args = unserialize($task['args']); + $report = reports_get_report($args[0]); + + // Check ACL in reports_get_report return false. + if ($report === false) { + continue; + } + + $path = $args[1]; + $data[2] .= '
        - '.__('Report').": ".$report['name'].''; + $data[2] .= '
        - '.__('Path').': '.$path.''; + break; + + case 'cron_task_do_backup': + if ($manage_pandora) { + $data[0] = ''; + $data[0] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Force run')] + ); + $data[0] .= ''; + } else { + $data[0] = ''; + } + + $data[1] = $task['id_usuario']; + $data[2] = db_get_value( + 'name', + 'tuser_task', + 'id', + $task['id_user_task'] + ); + $args = unserialize($task['args']); + break; + + default: + // Ignore. + break; + } + + $data[3] = cron_get_scheduled_string($task['scheduled']); + $data[4] = date('Y/m/d H:i:s', $args['first_execution']); + $data[5] = empty($task['last_run']) ? __('Never') : date('Y/m/d H:i:s', $task['last_run']); + + $data[6] = ui_print_group_icon($task['id_grupo'], true); + + if ($function_name == 'cron_task_do_backup' || $function_name == 'cron_task_execute_custom_script') { + if ($manage_pandora) { + $data[7] = ''; + $data[7] .= html_print_image( + 'images/config.png', + true, + ['title' => __('Edit')] + ); + $data[7] .= ''; + } + + if ($manage_pandora) { + $data[7] .= ''; + $data[7] .= html_print_image( + 'images/cross.png', + true, + ['title' => __('Delete')] + ); + $data[7] .= ''; + } + } else { + if ($write_perms || $manage_pandora) { + $data[7] = ''; + $data[7] .= html_print_image( + 'images/config.png', + true, + ['title' => __('Edit')] + ); + $data[7] .= ''; + } + + if ($manage_perms || $manage_pandora) { + $data[7] .= ''; + $data[7] .= html_print_image( + 'images/cross.png', + true, + ['title' => __('Delete')] + ); + $data[7] .= ''; + } + } + + array_push($table->data, $data); + } + + html_print_table($table); + } } From eb56fd566c41afa2ec2b517fae4230102892ccfb Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Fri, 22 Feb 2019 13:07:47 +0100 Subject: [PATCH 223/249] implemented services treeview Former-commit-id: d5d71442d0c6122ba91b160647559cdf03f55625 --- pandora_console/images/tree_events.png | Bin 0 -> 329 bytes pandora_console/images/tree_service_map.png | Bin 0 -> 401 bytes pandora_console/include/ajax/tree.ajax.php | 300 ++- pandora_console/include/class/Tree.class.php | 1819 ++++++++-------- .../include/class/TreeGroup.class.php | 786 ++++--- .../include/class/TreeGroupEdition.class.php | 184 +- .../include/class/TreeService.class.php | 342 +++ .../include/javascript/tree/TreeController.js | 1880 +++++++++-------- pandora_console/include/styles/pandora.css | 4 +- pandora_console/operation/events/events.php | 1 + pandora_console/operation/tree.php | 444 ++-- 11 files changed, 2973 insertions(+), 2787 deletions(-) create mode 100644 pandora_console/images/tree_events.png create mode 100644 pandora_console/images/tree_service_map.png create mode 100644 pandora_console/include/class/TreeService.class.php diff --git a/pandora_console/images/tree_events.png b/pandora_console/images/tree_events.png new file mode 100644 index 0000000000000000000000000000000000000000..7628d6a80d852ba73d65176446ae08840da77f7f GIT binary patch literal 329 zcmV-P0k-~$P)q$gGRCwB~mC+4@AP|PpIDjK`1e@?q zSLh}>LF)wC4IBmEd0>M&f_?D4KM85bg(?D_X0SbKep7s{(LZPy@X;JH=p?`oQQeRS_ zH1+jJWe8NzT0-TT3Z?0{sPo&Ni1Sb^yx>uLKAHJX6x43U6@K^Bbqwt&AJ}x5hH7{E zbyU~#WGgNJK2ta9)S-`oYN(uYL%YzxP^g4T8FQaD?)Bx`wr#!rLj*O73mtOa{F3E0 b`4wOQT9iM?aWo@)00000NkvXXu0mjfMuUuS literal 0 HcmV?d00001 diff --git a/pandora_console/images/tree_service_map.png b/pandora_console/images/tree_service_map.png new file mode 100644 index 0000000000000000000000000000000000000000..16005f1c984dead9ac88069241b40d76c7501466 GIT binary patch literal 401 zcmV;C0dD?@P)Ug!OY$R9aJUg32_zw>?E=;}_>=v@ZuGlr7ffX(;SHhU3Jr_^t5e?c`xW z%a!9*MxJFvld!|=hpy|cXq}7Et-Y+}OnMw;scaF47IcYhEtcyl6Q{I9BlgIH^a; vPFvncDbp70;dyjK9}YJAdf@j&-vt-|K80iT031UL00000NkvXXu0mjf?0~A# literal 0 HcmV?d00001 diff --git a/pandora_console/include/ajax/tree.ajax.php b/pandora_console/include/ajax/tree.ajax.php index 6c8365a924..21df029b0a 100644 --- a/pandora_console/include/ajax/tree.ajax.php +++ b/pandora_console/include/ajax/tree.ajax.php @@ -3,173 +3,163 @@ // ================================================== // Copyright (c) 2005-2012 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list + // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 + // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. + // Only accesible by ajax -if (is_ajax()) { - global $config; +if (is_ajax ()) { + global $config; + + enterprise_include_once("include/functions_dashboard.php"); - enterprise_include_once('include/functions_dashboard.php'); + $public_hash = get_parameter('hash', 0); - $public_hash = get_parameter('hash', 0); + // Try to authenticate by hash on public dashboards + if ($public_hash == 0) { + // Login check + check_login(); + } else { + $validate_hash = enterprise_hook( + 'dasboard_validate_public_hash', + array($public_hash, 'tree_view') + ); + if ($validate_hash === false || $validate_hash === ENTERPRISE_NOT_HOOK) { + db_pandora_audit("Invalid public hash", "Trying to access report builder"); + require ("general/noaccess.php"); + exit; + } + } + + require_once($config['homedir'] . "/include/class/Tree.class.php"); + require_once($config['homedir'] . "/include/class/TreeOS.class.php"); + require_once($config['homedir'] . "/include/class/TreeModuleGroup.class.php"); + require_once($config['homedir'] . "/include/class/TreeModule.class.php"); + require_once($config['homedir'] . "/include/class/TreeTag.class.php"); + require_once($config['homedir'] . "/include/class/TreeGroup.class.php"); + require_once($config['homedir'] . "/include/class/TreeService.class.php"); + require_once($config['homedir'] . "/include/class/TreeGroupEdition.class.php"); + enterprise_include_once("include/class/TreePolicies.class.php"); + enterprise_include_once("include/class/TreeGroupMeta.class.php"); + require_once($config['homedir'] . "/include/functions_reporting.php"); + require_once($config['homedir'] . "/include/functions_os.php"); + + $getChildren = (bool) get_parameter('getChildren', 0); + $getGroupStatus = (bool) get_parameter('getGroupStatus', 0); + $getDetail = (bool) get_parameter('getDetail'); + + if ($getChildren) { + $type = get_parameter('type', 'group'); + $rootType = get_parameter('rootType', ''); + $id = get_parameter('id', -1); + $rootID = get_parameter('rootID', -1); + $serverID = get_parameter('serverID', false); + $childrenMethod = get_parameter('childrenMethod', 'on_demand'); + $hash = get_parameter('hash', false); + if ($hash !== false) { + enterprise_hook('dasboard_validate_public_hash', array($hash, 'tree_view')); + } - // Try to authenticate by hash on public dashboards - if ($public_hash == 0) { - // Login check - check_login(); - } else { - $validate_hash = enterprise_hook( - 'dasboard_validate_public_hash', - [ - $public_hash, - 'tree_view', - ] - ); - if ($validate_hash === false || $validate_hash === ENTERPRISE_NOT_HOOK) { - db_pandora_audit('Invalid public hash', 'Trying to access report builder'); - include 'general/noaccess.php'; - exit; - } - } + $default_filters = array( + 'searchAgent' => '', + 'statusAgent' => AGENT_STATUS_ALL, + 'searchModule' => '', + 'statusModule' => -1, + 'groupID' => 0, + 'tagID' => 0, + ); + $filter = get_parameter('filter', $default_filters); - include_once $config['homedir'].'/include/class/Tree.class.php'; - include_once $config['homedir'].'/include/class/TreeOS.class.php'; - include_once $config['homedir'].'/include/class/TreeModuleGroup.class.php'; - include_once $config['homedir'].'/include/class/TreeModule.class.php'; - include_once $config['homedir'].'/include/class/TreeTag.class.php'; - include_once $config['homedir'].'/include/class/TreeGroup.class.php'; - include_once $config['homedir'].'/include/class/TreeGroupEdition.class.php'; - enterprise_include_once('include/class/TreePolicies.class.php'); - enterprise_include_once('include/class/TreeGroupMeta.class.php'); - include_once $config['homedir'].'/include/functions_reporting.php'; - include_once $config['homedir'].'/include/functions_os.php'; + $agent_a = check_acl ($config['id_user'], 0, "AR"); + $agent_w = check_acl ($config['id_user'], 0, "AW"); + $access = ($agent_a == true) ? 'AR' : (($agent_w == true) ? 'AW' : 'AR'); + $switch_type = !empty($rootType) ? $rootType : $type; + switch ($switch_type) { + case 'os': + $tree = new TreeOS($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + break; + case 'module_group': + $tree = new TreeModuleGroup($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + break; + case 'module': + $tree = new TreeModule($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + break; + case 'tag': + $tree = new TreeTag($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + break; + case 'group': + if(is_metaconsole()){ + if (!class_exists('TreeGroupMeta')) break; + $tree = new TreeGroupMeta($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + } + else{ + $tree = new TreeGroup($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + } + break; + case 'policies': + if (!class_exists('TreePolicies')) break; + $tree = new TreePolicies($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + break; + case 'group_edition': + $tree = new TreeGroupEdition($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + break; + case 'services': + $tree = new TreeService($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + break; + default: + // FIXME. No error handler + return; + } - $getChildren = (bool) get_parameter('getChildren', 0); - $getGroupStatus = (bool) get_parameter('getGroupStatus', 0); - $getDetail = (bool) get_parameter('getDetail'); + $tree->setFilter($filter); + ob_clean(); - if ($getChildren) { - $type = get_parameter('type', 'group'); - $rootType = get_parameter('rootType', ''); - $id = get_parameter('id', -1); - $rootID = get_parameter('rootID', -1); - $serverID = get_parameter('serverID', false); - $childrenMethod = get_parameter('childrenMethod', 'on_demand'); - $hash = get_parameter('hash', false); - if ($hash !== false) { - enterprise_hook('dasboard_validate_public_hash', [$hash, 'tree_view']); - } - - $default_filters = [ - 'searchAgent' => '', - 'statusAgent' => AGENT_STATUS_ALL, - 'searchModule' => '', - 'statusModule' => -1, - 'groupID' => 0, - 'tagID' => 0, - ]; - $filter = get_parameter('filter', $default_filters); - - $agent_a = check_acl($config['id_user'], 0, 'AR'); - $agent_w = check_acl($config['id_user'], 0, 'AW'); - $access = ($agent_a == true) ? 'AR' : (($agent_w == true) ? 'AW' : 'AR'); - $switch_type = !empty($rootType) ? $rootType : $type; - switch ($switch_type) { - case 'os': - $tree = new TreeOS($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - break; - - case 'module_group': - $tree = new TreeModuleGroup($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - break; - - case 'module': - $tree = new TreeModule($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - break; - - case 'tag': - $tree = new TreeTag($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - break; - - case 'group': - if (is_metaconsole()) { - if (!class_exists('TreeGroupMeta')) { - break; - } - - $tree = new TreeGroupMeta($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - } else { - $tree = new TreeGroup($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - } - break; - - case 'policies': - if (!class_exists('TreePolicies')) { - break; - } - - $tree = new TreePolicies($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - break; - - case 'group_edition': - $tree = new TreeGroupEdition($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - break; - - default: - // FIXME. No error handler - return; - } - - $tree->setFilter($filter); - ob_clean(); - echo json_encode(['success' => 1, 'tree' => $tree->getArray()]); - return; - } - - if ($getDetail) { - include_once $config['homedir'].'/include/functions_treeview.php'; - - $id = (int) get_parameter('id'); - $type = (string) get_parameter('type'); - - $server = []; - if (is_metaconsole()) { - $server_id = (int) get_parameter('serverID'); - $server = metaconsole_get_servers($server_id); - } - - ob_clean(); - - echo '
        '; - if (!empty($id) && !empty($type)) { - switch ($type) { - case 'agent': - treeview_printTable($id, $server, true); - break; - - case 'module': - treeview_printModuleTable($id, $server, true); - break; - - case 'alert': - treeview_printAlertsTable($id, $server, true); - break; - - default: - // Nothing - break; - } - } - - echo '
        '; - - return; - } - - return; + echo json_encode(array('success' => 1, 'tree' => $tree->getArray())); + return; + } + + if ($getDetail) { + require_once($config['homedir']."/include/functions_treeview.php"); + + $id = (int) get_parameter('id'); + $type = (string) get_parameter('type'); + + $server = array(); + if (is_metaconsole()) { + $server_id = (int) get_parameter('serverID'); + $server = metaconsole_get_servers($server_id); + } + + ob_clean(); + + echo '
        '; + if (!empty($id) && !empty($type)) { + switch ($type) { + case 'agent': + treeview_printTable($id, $server, true); + break; + case 'module': + treeview_printModuleTable($id, $server, true); + break; + case 'alert': + treeview_printAlertsTable($id, $server, true); + break; + default: + // Nothing + break; + } + } + echo '
        '; + + return; + } + + return; } +?> \ No newline at end of file diff --git a/pandora_console/include/class/Tree.class.php b/pandora_console/include/class/Tree.class.php index eda92b48b5..da0380f4ea 100644 --- a/pandora_console/include/class/Tree.class.php +++ b/pandora_console/include/class/Tree.class.php @@ -1,904 +1,762 @@ type = $type; + $this->rootType = !empty($rootType) ? $rootType : $type; + $this->id = $id; + $this->rootID = !empty($rootID) ? $rootID : $id; + $this->serverID = $serverID; + if (is_metaconsole()) { + $this->serverName = metaconsole_get_server_by_id($serverID); + } + $this->childrenMethod = $childrenMethod; + $this->access = $access; - protected $userGroupsACL; + $userGroupsACL = users_get_groups(false, $this->access); - protected $userGroups; + $this->userGroupsACL = empty($userGroupsACL) ? false : $userGroupsACL; + $this->userGroups = $this->userGroupsACL; + $this->userGroupsArray = array_keys($this->userGroups); - protected $userGroupsArray; + global $config; + include_once($config['homedir']."/include/functions_servers.php"); + include_once($config['homedir']."/include/functions_modules.php"); + require_once($config['homedir']."/include/functions_tags.php"); + enterprise_include_once("include/functions_agents.php"); - protected $access = false; + if (is_metaconsole()) enterprise_include_once("meta/include/functions_ui_meta.php"); + } - protected $L1fieldName = ''; + public function setFilter($filter) { + // There is not module filter in metaconsole. + if (is_metaconsole()) { + $filter['searchModule'] = ""; + $filter['statusModule'] = self::TV_DEFAULT_AGENT_STATUS; + } + $this->filter = $filter; + } - protected $L1fieldNameSql = ''; + protected function getEmptyModuleFilterStatus() { + return ( + !isset($this->filter['statusModule']) || + $this->filter['statusModule'] == -1 + ); + } - protected $L1extraFields = []; + protected function getModuleSearchFilter() { + if (empty($this->filter['searchModule'])) { + return ""; + } + return " AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' "; + } - protected $L1inner = ''; - - protected $L1innerInside = ''; - - protected $L1orderByFinal = ''; - - protected $L2condition = ''; - - protected $L2conditionInside = ''; - - protected $L2inner = ''; - - protected $L3forceTagCondition = false; - - const TV_DEFAULT_AGENT_STATUS = -1; + protected function getAgentSearchFilter() { + if (empty($this->filter['searchAgent'])) return ""; + return " AND LOWER(ta.alias) LIKE LOWER('%%".$this->filter['searchAgent']."%%')"; + } - public function __construct($type, $rootType='', $id=-1, $rootID=-1, $serverID=false, $childrenMethod='on_demand', $access='AR') - { - $this->type = $type; - $this->rootType = !empty($rootType) ? $rootType : $type; - $this->id = $id; - $this->rootID = !empty($rootID) ? $rootID : $id; - $this->serverID = $serverID; - if (is_metaconsole()) { - $this->serverName = metaconsole_get_server_by_id($serverID); - } + protected function getAgentStatusFilter ($status = self::TV_DEFAULT_AGENT_STATUS) { + if ($status == self::TV_DEFAULT_AGENT_STATUS) + $status = $this->filter['statusAgent']; - $this->childrenMethod = $childrenMethod; - $this->access = $access; - - $userGroupsACL = users_get_groups(false, $this->access); - $this->userGroupsACL = empty($userGroupsACL) ? false : $userGroupsACL; - $this->userGroups = $this->userGroupsACL; - $this->userGroupsArray = array_keys($this->userGroups); - - global $config; - include_once $config['homedir'].'/include/functions_servers.php'; - include_once $config['homedir'].'/include/functions_modules.php'; - include_once $config['homedir'].'/include/functions_tags.php'; - enterprise_include_once('include/functions_agents.php'); - - if (is_metaconsole()) { - enterprise_include_once('meta/include/functions_ui_meta.php'); - } - } - - - public function setFilter($filter) - { - // There is not module filter in metaconsole. - if (is_metaconsole()) { - $filter['searchModule'] = ''; - $filter['statusModule'] = self::TV_DEFAULT_AGENT_STATUS; - } - - $this->filter = $filter; - } - - - protected function getEmptyModuleFilterStatus() - { - return ( - !isset($this->filter['statusModule']) || - $this->filter['statusModule'] == -1 - ); - } - - - protected function getModuleSearchFilter() - { - if (empty($this->filter['searchModule'])) { - return ''; - } - - return " AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' "; - } - - - protected function getAgentSearchFilter() - { - if (empty($this->filter['searchAgent'])) { - return ''; - } - - return " AND LOWER(ta.alias) LIKE LOWER('%%".$this->filter['searchAgent']."%%')"; - } - - - protected function getAgentStatusFilter($status=self::TV_DEFAULT_AGENT_STATUS) - { - if ($status == self::TV_DEFAULT_AGENT_STATUS) { - $status = $this->filter['statusAgent']; - } - - $agent_status_filter = ''; - switch ($status) { - case AGENT_STATUS_ALL: - break; - - case AGENT_STATUS_NOT_INIT: - $agent_status_filter = ' AND (ta.total_count = 0 - OR ta.total_count = ta.notinit_count) '; - break; - - case AGENT_STATUS_CRITICAL: - $agent_status_filter = ' AND ta.critical_count > 0 '; - break; - - case AGENT_STATUS_WARNING: - $agent_status_filter = ' AND (ta.critical_count = 0 - AND ta.warning_count > 0) '; - break; - - case AGENT_STATUS_UNKNOWN: - $agent_status_filter = ' AND (ta.critical_count = 0 + $agent_status_filter = ""; + switch ($status) { + case AGENT_STATUS_ALL: + break; + case AGENT_STATUS_NOT_INIT: + $agent_status_filter = " AND (ta.total_count = 0 + OR ta.total_count = ta.notinit_count) "; + break; + case AGENT_STATUS_CRITICAL: + $agent_status_filter = " AND ta.critical_count > 0 "; + break; + case AGENT_STATUS_WARNING: + $agent_status_filter = " AND (ta.critical_count = 0 + AND ta.warning_count > 0) "; + break; + case AGENT_STATUS_UNKNOWN: + $agent_status_filter = " AND (ta.critical_count = 0 AND ta.warning_count = 0 - AND ta.unknown_count > 0) '; - break; - - case AGENT_STATUS_NORMAL: - $agent_status_filter = ' AND (ta.critical_count = 0 + AND ta.unknown_count > 0) "; + break; + case AGENT_STATUS_NORMAL: + $agent_status_filter = " AND (ta.critical_count = 0 AND ta.warning_count = 0 AND ta.unknown_count = 0 - AND ta.normal_count > 0) '; - break; - } + AND ta.normal_count > 0) "; + break; + } - return $agent_status_filter; - } + return $agent_status_filter; + } + protected function getFirstLevelFields() { + $fields = array ( + "g AS " . $this->L1fieldName, + "SUM(x_critical) AS total_critical_count", + "SUM(x_warning) AS total_warning_count", + "SUM(x_normal) AS total_normal_count", + "SUM(x_unknown) AS total_unknown_count", + "SUM(x_not_init) AS total_not_init_count", + "SUM(x_alerts) AS total_alerts_count", + "SUM(x_total) AS total_count" + ); + return implode(",", array_merge($fields, $this->L1extraFields)); + } - protected function getFirstLevelFields() - { - $fields = [ - 'g AS '.$this->L1fieldName, - 'SUM(x_critical) AS total_critical_count', - 'SUM(x_warning) AS total_warning_count', - 'SUM(x_normal) AS total_normal_count', - 'SUM(x_unknown) AS total_unknown_count', - 'SUM(x_not_init) AS total_not_init_count', - 'SUM(x_alerts) AS total_alerts_count', - 'SUM(x_total) AS total_count', - ]; - return implode(',', array_merge($fields, $this->L1extraFields)); - } + protected function getFirstLevelFieldsInside() { + return array( + 'warning' => array( + 'header' => "0 AS x_critical, SUM(total) AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", + 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_WARNING, $this->filter['show_not_init_agents']) + ), + 'critical' => array( + 'header' => "SUM(total) AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", + 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_CRITICAL, $this->filter['show_not_init_agents']) + ), + 'normal' => array( + 'header' => "0 AS x_critical, 0 AS x_warning, SUM(total) AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", + 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_NORMAL, $this->filter['show_not_init_agents']) + ), + 'unknown' => array( + 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, SUM(total) AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", + 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_UNKNOWN, $this->filter['show_not_init_agents']) + ), + 'not_init' => array( + 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, SUM(total) AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", + 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_NOT_INIT, $this->filter['show_not_init_agents']) + ), + 'alerts' => array( + 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, SUM(total) AS x_alerts, 0 AS x_total, g", + 'condition' => "AND ta.fired_count > 0" + ), + 'total' => array( + 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, SUM(total) AS x_total, g", + 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_ALL, $this->filter['show_not_init_agents']) + ) + ); + } + protected function getInnerOrLeftJoin () { + return $this->filter['show_not_init_agents'] + ? "LEFT" + : "INNER"; + } - protected function getFirstLevelFieldsInside() - { - return [ - 'warning' => [ - 'header' => '0 AS x_critical, SUM(total) AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', - 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_WARNING, $this->filter['show_not_init_agents']), - ], - 'critical' => [ - 'header' => 'SUM(total) AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', - 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_CRITICAL, $this->filter['show_not_init_agents']), - ], - 'normal' => [ - 'header' => '0 AS x_critical, 0 AS x_warning, SUM(total) AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', - 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_NORMAL, $this->filter['show_not_init_agents']), - ], - 'unknown' => [ - 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, SUM(total) AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', - 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_UNKNOWN, $this->filter['show_not_init_agents']), - ], - 'not_init' => [ - 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, SUM(total) AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', - 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_NOT_INIT, $this->filter['show_not_init_agents']), - ], - 'alerts' => [ - 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, SUM(total) AS x_alerts, 0 AS x_total, g', - 'condition' => 'AND ta.fired_count > 0', - ], - 'total' => [ - 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, SUM(total) AS x_total, g', - 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_ALL, $this->filter['show_not_init_agents']), - ], - ]; - } + protected function getModuleStatusFilter () { + $show_init_condition = ($this->filter['show_not_init_agents']) + ? "" + : " AND ta.notinit_count <> ta.total_count"; + if ($this->getEmptyModuleFilterStatus()) { + return $show_init_condition; + } - protected function getInnerOrLeftJoin() - { - return $this->filter['show_not_init_agents'] ? 'LEFT' : 'INNER'; - } + $field_filter = modules_get_counter_by_states($this->filter['statusModule']); + if ($field_filter === false) return " AND 1=0"; + return "AND ta.$field_filter > 0" . $show_init_condition; + } - protected function getModuleStatusFilter() - { - $show_init_condition = ($this->filter['show_not_init_agents']) ? '' : ' AND ta.notinit_count <> ta.total_count'; - - if ($this->getEmptyModuleFilterStatus()) { - return $show_init_condition; - } - - $field_filter = modules_get_counter_by_states($this->filter['statusModule']); - if ($field_filter === false) { - return ' AND 1=0'; - } - - return "AND ta.$field_filter > 0".$show_init_condition; - } - - - protected function getTagJoin() - { - return 'INNER JOIN ttag_module ttm + protected function getTagJoin () { + return 'INNER JOIN ttag_module ttm ON tam.id_agente_modulo = ttm.id_agente_modulo'; - } + } + protected function getTagCondition () { + $tags = tags_get_user_applied_agent_tags($this->id, "AR"); + // All tags permision, returns no condition + if ($tags === true) return ""; + // No permision, do not show anything + if ($tags === false) return " AND 1=0"; + $tags_sql = implode(',', $tags); + return "AND ttm.id_tag IN ($tags_sql)";; + } - protected function getTagCondition() - { - $tags = tags_get_user_applied_agent_tags($this->id, 'AR'); - // All tags permision, returns no condition - if ($tags === true) { - return ''; - } + protected function getModuleStatusFilterFromTestado ($state = false, $without_ands = false) { + $selected_status = ($state !== false && $state !== self::TV_DEFAULT_AGENT_STATUS) + ? $state + : $this->filter['statusModule']; - // No permision, do not show anything - if ($tags === false) { - return ' AND 1=0'; - } + $filter = array( + modules_get_state_condition($selected_status) + ); + if (!$this->filter['show_not_init_modules'] && $state === false) { + if (!empty($filter)) + $filter[] = "( + tae.estado <> ".AGENT_MODULE_STATUS_NO_DATA." + AND tae.estado <> ".AGENT_MODULE_STATUS_NOT_INIT." + )"; + } + $filter = implode(" AND ", $filter); + return ($without_ands) + ? $filter + : " AND $filter "; + } - $tags_sql = implode(',', $tags); - return "AND ttm.id_tag IN ($tags_sql)"; - ; - } + public function getGroupAclCondition() { + if (users_can_manage_group_all("AR")) return ""; - - protected function getModuleStatusFilterFromTestado($state=false, $without_ands=false) - { - $selected_status = ($state !== false && $state !== self::TV_DEFAULT_AGENT_STATUS) ? $state : $this->filter['statusModule']; - - $filter = [modules_get_state_condition($selected_status)]; - if (!$this->filter['show_not_init_modules'] && $state === false) { - if (!empty($filter)) { - $filter[] = '( - tae.estado <> '.AGENT_MODULE_STATUS_NO_DATA.' - AND tae.estado <> '.AGENT_MODULE_STATUS_NOT_INIT.' - )'; - } - } - - $filter = implode(' AND ', $filter); - return ($without_ands) ? $filter : " AND $filter "; - } - - - public function getGroupAclCondition() - { - if (users_can_manage_group_all('AR')) { - return ''; - } - - $groups_str = implode(',', $this->userGroupsArray); - return " AND ( + $groups_str= implode(",", $this->userGroupsArray); + return " AND ( ta.id_grupo IN ($groups_str) OR tasg.id_group IN ($groups_str) )"; - } + } - - protected function getGroupSearchInner() - { - if (empty($this->filter['searchGroup'])) { - return ''; - } - - return 'INNER JOIN tgrupo tg + protected function getGroupSearchInner() { + if (empty($this->filter['searchGroup'])) return ""; + return "INNER JOIN tgrupo tg ON ta.id_grupo = tg.id_grupo - OR tasg.id_group = tg.id_grupo'; - } - - - protected function getGroupSearchFilter() - { - if (empty($this->filter['searchGroup'])) { - return ''; - } - - return " AND tg.nombre LIKE '%%".$this->filter['searchGroup']."%%'"; - } - - - static function cmpSortNames($a, $b) - { - return strcmp($a['name'], $b['name']); - } - - - protected function getProcessedItem($item, $server=false) - { - if (isset($processed_item['is_processed']) && $processed_item['is_processed']) { - return $item; - } - - $processed_item = []; - $processed_item['id'] = $item['id']; - $processed_item['name'] = $item['name']; - $processed_item['rootID'] = $item['id']; - $processed_item['rootType'] = $this->rootType; - $processed_item['searchChildren'] = 1; - - if (isset($item['type'])) { - $processed_item['type'] = $item['type']; - } else { - $processed_item['type'] = $this->type; - } - - if (isset($item['rootType'])) { - $processed_item['rootType'] = $item['rootType']; - } else { - $processed_item['rootType'] = $this->rootType; - } - - if ($processed_item['type'] == 'group') { - $processed_item['parent'] = $item['parent']; - - $processed_item['icon'] = empty($item['icon']) ? 'without_group.png' : $item['icon'].'.png'; - } - - if (isset($item['iconHTML'])) { - $processed_item['icon'] = $item['iconHTML']; - } - - if (is_metaconsole() && !empty($server)) { - $processed_item['serverID'] = $server['id']; - } - - $counters = []; - if (isset($item['total_unknown_count'])) { - $counters['unknown'] = $item['total_unknown_count']; - } - - if (isset($item['total_critical_count'])) { - $counters['critical'] = $item['total_critical_count']; - } - - if (isset($item['total_warning_count'])) { - $counters['warning'] = $item['total_warning_count']; - } - - if (isset($item['total_not_init_count'])) { - $counters['not_init'] = $item['total_not_init_count']; - } - - if (isset($item['total_normal_count'])) { - $counters['ok'] = $item['total_normal_count']; - } - - if (isset($item['total_count'])) { - $counters['total'] = $item['total_count']; - } - - if (isset($item['total_fired_count'])) { - $counters['alerts'] = $item['total_fired_count']; - } - - if (!empty($counters)) { - $processed_item['counters'] = $counters; - } - - if (!empty($processed_item)) { - $processed_item['is_processed'] = true; - } - - return $processed_item; - } - - - // This function should be used only when retrieving the data of the metaconsole's nodes - protected function getMergedItems($items) - { - // This variable holds the result - $mergedItems = []; - - foreach ($items as $key => $item) { - // Avoid the deleted items - if (!isset($items[$key]) || empty($item)) { - continue; - } - - // Store the item in a temporary element - $resultItem = $item; - - // The 'id' parameter will be stored as 'server_id' => 'id' - $resultItem['id'] = []; - $resultItem['id'][$item['serverID']] = $item['id']; - $resultItem['rootID'] = []; - $resultItem['rootID'][$item['serverID']] = $item['rootID']; - $resultItem['serverID'] = []; - $resultItem['serverID'][$item['serverID']] = $item['rootID']; - - // Initialize counters if any of it don't exist - if (!isset($resultItem['counters'])) { - $resultItem['counters'] = []; - } - - if (!isset($resultItem['counters']['unknown'])) { - $resultItem['counters']['unknown'] = 0; - } - - if (!isset($resultItem['counters']['critical'])) { - $resultItem['counters']['critical'] = 0; - } - - if (!isset($resultItem['counters']['warning'])) { - $resultItem['counters']['warning'] = 0; - } - - if (!isset($resultItem['counters']['not_init'])) { - $resultItem['counters']['not_init'] = 0; - } - - if (!isset($resultItem['counters']['ok'])) { - $resultItem['counters']['ok'] = 0; - } - - if (!isset($resultItem['counters']['total'])) { - $resultItem['counters']['total'] = 0; - } - - if (!isset($resultItem['counters']['alerts'])) { - $resultItem['counters']['alerts'] = 0; - } - - if ($item['type'] == 'group') { - // Add the children - if (!isset($resultItem['children'])) { - $resultItem['children'] = []; - } - } - - // Iterate over the list to search items that match the actual item - foreach ($items as $key2 => $item2) { - // Skip the actual or empty items - if ($key == $key2 || !isset($items[$key2])) { - continue; - } - - // Match with the name and type - if ($item['name'] == $item2['name'] && $item['type'] == $item2['type']) { - // Add the matched ids - $resultItem['id'][$item2['serverID']] = $item2['id']; - $resultItem['rootID'][$item2['serverID']] = $item2['rootID']; - $resultItem['serverID'][$item2['serverID']] = $item2['rootID']; - - // Add the matched counters - if (isset($item2['counters']) && !empty($item2['counters'])) { - foreach ($item2['counters'] as $type => $value) { - if (isset($resultItem['counters'][$type])) { - $resultItem['counters'][$type] += $value; - } - } - } - - if ($item['type'] == 'group') { - // Add the matched children - if (isset($item2['children'])) { - $resultItem['children'] = array_merge($resultItem['children'], $item2['children']); - } - } - - // Remove the item - unset($items[$key2]); - } - } - - if ($item['type'] == 'group') { - // Get the merged children (recursion) - if (!empty($resultItem['children'])) { - $resultItem['children'] = $this->getMergedItems($resultItem['children']); - } - } - - // Add the resulting item - if (!empty($resultItem) && !empty($resultItem['counters']['total'])) { - $mergedItems[] = $resultItem; - } - - // Remove the item - unset($items[$key]); - } - - usort($mergedItems, ['Tree', 'cmpSortNames']); - - return $mergedItems; - } - - - protected function processModule(&$module, $server=false, $all_groups) - { - global $config; - - if (isset($module['children'])) { - foreach ($module['children'] as $i => $children) { - $this->processModule($module['children'][$i], $server, $all_groups); - } - } - - $module['type'] = 'module'; - $module['id'] = (int) $module['id']; - $module['name'] = io_safe_output($module['name']); - $module['id_module_type'] = (int) $module['id_tipo_modulo']; - $module['server_type'] = (int) $module['id_modulo']; - $module['status'] = $module['estado']; - $module['value'] = $module['datos']; - - if (is_metaconsole()) { - $module['serverID'] = $this->serverID; - $module['serverName'] = $this->serverName; - } else { - $module['serverName'] = false; - $module['serverID'] = false; - } - - if (!isset($module['value'])) { - $module['value'] = modules_get_last_value($module['id']); - } - - // Status - switch ($module['status']) { - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - $module['alert'] = 1; - case AGENT_MODULE_STATUS_CRITICAL_BAD: - $statusType = STATUS_MODULE_CRITICAL_BALL; - $statusTitle = __('CRITICAL'); - $module['statusText'] = 'critical'; - break; - - case AGENT_MODULE_STATUS_WARNING_ALERT: - $module['alert'] = 1; - case AGENT_MODULE_STATUS_WARNING: - $statusType = STATUS_MODULE_WARNING_BALL; - $statusTitle = __('WARNING'); - $module['statusText'] = 'warning'; - break; - - case AGENT_MODULE_STATUS_UNKNOWN: - $statusType = STATUS_MODULE_UNKNOWN_BALL; - $statusTitle = __('UNKNOWN'); - $module['statusText'] = 'unknown'; - break; - - case AGENT_MODULE_STATUS_NO_DATA: - case AGENT_MODULE_STATUS_NOT_INIT: - $statusType = STATUS_MODULE_NO_DATA_BALL; - $statusTitle = __('NO DATA'); - $module['statusText'] = 'not_init'; - break; - - case AGENT_MODULE_STATUS_NORMAL_ALERT: - $module['alert'] = 1; - case AGENT_MODULE_STATUS_NORMAL: - default: - $statusType = STATUS_MODULE_OK_BALL; - $statusTitle = __('NORMAL'); - $module['statusText'] = 'ok'; - break; - } - - if ($statusType !== STATUS_MODULE_UNKNOWN_BALL - && $statusType !== STATUS_MODULE_NO_DATA_BALL - ) { - if (is_numeric($module['value'])) { - $statusTitle .= ' : '.format_for_graph($module['value']); - } else { - $statusTitle .= ' : '.substr(io_safe_output($module['value']), 0, 42); - } - } - - $module['statusImageHTML'] = ui_print_status_image($statusType, $statusTitle, true); - - // HTML of the server type image - $module['serverTypeHTML'] = servers_show_type($module['server_type']); - - // Link to the Module graph - // ACL - $acl_graphs = false; - $module['showGraphs'] = 0; - - // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions - if (!empty($group_id) && !is_metaconsole()) { - $acl_graphs = check_acl_one_of_groups($config['id_user'], $all_groups, 'RR'); - } else if (!empty($all_groups)) { - $acl_graphs = true; - } - - if ($acl_graphs) { - $module['showGraphs'] = 1; - } - - if ($module['showGraphs']) { - $graphType = return_graphtype($module['id_module_type']); - $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); - $winHandle = dechex(crc32($module['id'].$module['name'])); - - $graph_params = [ - 'type' => $graphType, - 'period' => SECONDS_1DAY, - 'id' => $module['id'], - 'label' => base64_encode($module['name']), - 'refresh' => SECONDS_10MINUTES, - ]; - - if (is_metaconsole()) { - // Set the server id - $graph_params['server'] = $module['serverID']; - } - - $graph_params_str = http_build_query($graph_params); - $moduleGraphURL = "$url?$graph_params_str"; - - $module['moduleGraph'] = [ - 'url' => $moduleGraphURL, - 'handle' => $winHandle, - ]; - - // Info to be able to open the snapshot image new page - $module['snapshot'] = ui_get_snapshot_link( - [ - 'id_module' => $module['id'], - 'interval' => $module['current_interval'], - 'module_name' => $module['name'], - 'id_node' => $module['serverID'] ? $module['serverID'] : 0, - ], - true - ); - } - - // Alerts fired image - if ((bool) $module['alerts']) { - $module['alertsImageHTML'] = html_print_image('images/bell.png', true, ['title' => __('Module alerts')]); - } - } - - - protected function processModules(&$modules, $server=false) - { - if (!empty($modules)) { - $all_groups = modules_get_agent_groups($modules[0]['id']); - } - - foreach ($modules as $iterator => $module) { - $this->processModule($modules[$iterator], $server, $all_groups); - } - } - - - protected function processAgent(&$agent, $server=false) - { - global $config; - - $agent['type'] = 'agent'; - $agent['id'] = (int) $agent['id']; - $agent['name'] = $agent['name']; - - $agent['rootID'] = $this->rootID; - $agent['rootType'] = $this->rootType; - - if (is_metaconsole()) { - if (isset($agent['server_id'])) { - $agent['serverID'] = $agent['server_id']; - } else if (!empty($server)) { - $agent['serverID'] = $server['id']; - } - } - - // Counters - if (empty($agent['counters'])) { - $agent['counters'] = []; - - $agent['counters']['unknown'] = isset($agent['unknown_count']) ? $agent['unknown_count'] : 0; - $agent['counters']['critical'] = isset($agent['critical_count']) ? $agent['critical_count'] : 0; - $agent['counters']['warning'] = isset($agent['warning_count']) ? $agent['warning_count'] : 0; - $agent['counters']['not_init'] = isset($agent['notinit_count']) ? $agent['notinit_count'] : 0; - $agent['counters']['ok'] = isset($agent['normal_count']) ? $agent['normal_count'] : 0; - $agent['counters']['total'] = isset($agent['total_count']) ? $agent['total_count'] : 0; - $agent['counters']['alerts'] = isset($agent['fired_count']) ? $agent['fired_count'] : 0; - } - - // Status image - $agent['statusImageHTML'] = agents_tree_view_status_img_ball( - $agent['counters']['critical'], - $agent['counters']['warning'], - $agent['counters']['unknown'], - $agent['counters']['total'], - $agent['counters']['not_init'] - ); - - // Alerts fired image - $agent['alertImageHTML'] = agents_tree_view_alert_img_ball($agent['counters']['alerts']); - - // search module recalculate counters - if (array_key_exists('state_normal', $agent)) { - $agent['counters']['unknown'] = $agent['state_unknown']; - $agent['counters']['critical'] = $agent['state_critical']; - $agent['counters']['warning'] = $agent['state_warning']; - $agent['counters']['not_init'] = $agent['state_notinit']; - $agent['counters']['ok'] = $agent['state_normal']; - $agent['counters']['total'] = $agent['state_total']; - - $agent['critical_count'] = $agent['counters']['critical']; - $agent['warning_count'] = $agent['counters']['warning']; - $agent['unknown_count'] = $agent['counters']['unknown']; - $agent['notinit_count'] = $agent['counters']['not_init']; - $agent['normal_count'] = $agent['counters']['ok']; - $agent['total_count'] = $agent['counters']['total']; - } - - if (!$this->getEmptyModuleFilterStatus()) { - $agent['counters']['unknown'] = 0; - $agent['counters']['critical'] = 0; - $agent['counters']['warning'] = 0; - $agent['counters']['not_init'] = 0; - $agent['counters']['ok'] = 0; - $agent['counters']['total'] = 0; - switch ($this->filter['statusModule']) { - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - case AGENT_MODULE_STATUS_CRITICAL_BAD: - $agent['counters']['critical'] = $agent['critical_count']; - $agent['counters']['total'] = $agent['critical_count']; - break; - - case AGENT_MODULE_STATUS_WARNING_ALERT: - case AGENT_MODULE_STATUS_WARNING: - $agent['counters']['warning'] = $agent['warning_count']; - $agent['counters']['total'] = $agent['warning_count']; - break; - - case AGENT_MODULE_STATUS_UNKNOWN: - $agent['counters']['unknown'] = $agent['unknown_count']; - $agent['counters']['total'] = $agent['unknown_count']; - break; - - case AGENT_MODULE_STATUS_NO_DATA: - case AGENT_MODULE_STATUS_NOT_INIT: - $agent['counters']['not_init'] = $agent['notinit_count']; - $agent['counters']['total'] = $agent['notinit_count']; - break; - - case AGENT_MODULE_STATUS_NORMAL_ALERT: - case AGENT_MODULE_STATUS_NORMAL: - $agent['counters']['ok'] = $agent['normal_count']; - $agent['counters']['total'] = $agent['normal_count']; - break; - } - } - - if (!$this->filter['show_not_init_modules']) { - $agent['counters']['total'] -= $agent['counters']['not_init']; - $agent['counters']['not_init'] = 0; - } - - // Quiet image - if (isset($agent['quiet']) && $agent['quiet']) { - $agent['quietImageHTML'] = html_print_image('/images/dot_blue.png', true, ['title' => __('Quiet')]); - } - - // Children - if (empty($agent['children'])) { - $agent['children'] = []; - if ($agent['counters']['total'] > 0) { - switch ($this->childrenMethod) { - case 'on_demand': - $agent['searchChildren'] = 1; - break; - - case 'live': - $agent['searchChildren'] = 0; - break; - } - } else { - switch ($this->childrenMethod) { - case 'on_demand': - $agent['searchChildren'] = 0; - break; - - case 'live': - $agent['searchChildren'] = 0; - break; - } - } - } - } - - - protected function processAgents(&$agents, $server=false) - { - if (!empty($agents)) { - foreach ($agents as $iterator => $agent) { - $this->processAgent($agents[$iterator], $server); - } - } - } - - - protected function getData() - { - - } - - - protected function getFirstLevel() - { - $sql = $this->getFirstLevelSql(); - $items = db_get_all_rows_sql($sql); - if ($items === false) { - $items = []; - } - - $this->tree = $this->getProcessedItemsFirstLevel($items); - } - - - protected function getProcessedItemsFirstLevel($items) - { - $processed_items = []; - foreach ($items as $key => $item) { - $processed_item = $this->getProcessedItem($item); - $processed_items[] = $processed_item; - } - - return $processed_items; - } - - - protected function getFirstLevelSql() - { - $fields = $this->getFirstLevelFields(); - $field_name_sql = $this->L1fieldNameSql; - $inside_fields = $this->getFirstLevelFieldsInside(); - $inner = $this->L1inner; - $inner_inside = $this->L1innerInside; - $order_by_final = $this->L1orderByFinal; - - $group_inner = $this->getGroupSearchInner(); - $group_acl = $this->getGroupAclCondition(); - $group_search_filter = $this->getGroupSearchFilter(); - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_search_filter = $this->getModuleSearchFilter(); - $module_status_inner = ''; - $module_status_filter = $this->getModuleStatusFilterFromTestado(); - if (!empty($module_status_filter)) { - $module_status_inner = ' + OR tasg.id_group = tg.id_grupo" + ; + } + + protected function getGroupSearchFilter() { + if (empty($this->filter['searchGroup'])) return ""; + return " AND tg.nombre LIKE '%%" . $this->filter['searchGroup'] . "%%'"; + } + + static function cmpSortNames($a, $b) { + return strcmp($a["name"], $b["name"]); + } + + protected function getProcessedItem ($item, $server = false) { + + if (isset($processed_item['is_processed']) && $processed_item['is_processed']) + return $item; + + $processed_item = array(); + $processed_item['id'] = $item['id']; + $processed_item['name'] = $item['name']; + $processed_item['rootID'] = $item['id']; + $processed_item['rootType'] = $this->rootType; + $processed_item['searchChildren'] = 1; + + if (isset($item['type'])) + $processed_item['type'] = $item['type']; + else + $processed_item['type'] = $this->type; + + if (isset($item['rootType'])) + $processed_item['rootType'] = $item['rootType']; + else + $processed_item['rootType'] = $this->rootType; + + if ($processed_item['type'] == 'group') { + $processed_item['parent'] = $item['parent']; + + $processed_item['icon'] = empty($item['icon']) + ? "without_group.png" + : $item['icon'].".png"; + } + if (isset($item['iconHTML'])) { + $processed_item['icon'] = $item['iconHTML']; + } + + if (is_metaconsole() && !empty($server)) { + $processed_item['serverID'] = $server['id']; + } + + $counters = array(); + if (isset($item['total_unknown_count'])) + $counters['unknown'] = $item['total_unknown_count']; + if (isset($item['total_critical_count'])) + $counters['critical'] = $item['total_critical_count']; + if (isset($item['total_warning_count'])) + $counters['warning'] = $item['total_warning_count']; + if (isset($item['total_not_init_count'])) + $counters['not_init'] = $item['total_not_init_count']; + if (isset($item['total_normal_count'])) + $counters['ok'] = $item['total_normal_count']; + if (isset($item['total_count'])) + $counters['total'] = $item['total_count']; + if (isset($item['total_fired_count'])) + $counters['alerts'] = $item['total_fired_count']; + + if (!empty($counters)) + $processed_item['counters'] = $counters; + + if (!empty($processed_item)) + $processed_item['is_processed'] = true; + + return $processed_item; + } + + // This function should be used only when retrieving the data of the metaconsole's nodes + protected function getMergedItems ($items) { + // This variable holds the result + $mergedItems = array(); + + foreach ($items as $key => $item) { + // Avoid the deleted items + if (!isset($items[$key]) || empty($item)) + continue; + + // Store the item in a temporary element + $resultItem = $item; + + // The 'id' parameter will be stored as 'server_id' => 'id' + $resultItem['id'] = array(); + $resultItem['id'][$item['serverID']] = $item['id']; + $resultItem['rootID'] = array(); + $resultItem['rootID'][$item['serverID']] = $item['rootID']; + $resultItem['serverID'] = array(); + $resultItem['serverID'][$item['serverID']] = $item['rootID']; + + // Initialize counters if any of it don't exist + if (!isset($resultItem['counters'])) + $resultItem['counters'] = array(); + if (!isset($resultItem['counters']['unknown'])) + $resultItem['counters']['unknown'] = 0; + if (!isset($resultItem['counters']['critical'])) + $resultItem['counters']['critical'] = 0; + if (!isset($resultItem['counters']['warning'])) + $resultItem['counters']['warning'] = 0; + if (!isset($resultItem['counters']['not_init'])) + $resultItem['counters']['not_init'] = 0; + if (!isset($resultItem['counters']['ok'])) + $resultItem['counters']['ok'] = 0; + if (!isset($resultItem['counters']['total'])) + $resultItem['counters']['total'] = 0; + if (!isset($resultItem['counters']['alerts'])) + $resultItem['counters']['alerts'] = 0; + + if ($item['type'] == 'group') { + // Add the children + if (!isset($resultItem['children'])) + $resultItem['children'] = array(); + } + + // Iterate over the list to search items that match the actual item + foreach ($items as $key2 => $item2) { + // Skip the actual or empty items + if ($key == $key2 || !isset($items[$key2])) + continue; + + // Match with the name and type + if ($item['name'] == $item2['name'] && $item['type'] == $item2['type']) { + // Add the matched ids + $resultItem['id'][$item2['serverID']] = $item2['id']; + $resultItem['rootID'][$item2['serverID']] = $item2['rootID']; + $resultItem['serverID'][$item2['serverID']] = $item2['rootID']; + + // Add the matched counters + if (isset($item2['counters']) && !empty($item2['counters'])) { + foreach ($item2['counters'] as $type => $value) { + if (isset($resultItem['counters'][$type])) + $resultItem['counters'][$type] += $value; + } + } + + if ($item['type'] == 'group') { + // Add the matched children + if (isset($item2['children'])) + $resultItem['children'] = array_merge($resultItem['children'], $item2['children']); + } + + // Remove the item + unset($items[$key2]); + } + } + + if ($item['type'] == 'group') { + // Get the merged children (recursion) + if (!empty($resultItem['children'])) + $resultItem['children'] = $this->getMergedItems($resultItem['children']); + + } + + // Add the resulting item + if (!empty($resultItem) && !empty($resultItem['counters']['total'])) + $mergedItems[] = $resultItem; + + // Remove the item + unset($items[$key]); + } + + usort($mergedItems, array("Tree", "cmpSortNames")); + + return $mergedItems; + } + + protected function processModule (&$module, $server = false, $all_groups) { + global $config; + + if (isset($module['children'])) { + foreach ($module['children'] as $i => $children) { + $this->processModule($module['children'][$i], $server, $all_groups); + } + } + + $module['type'] = 'module'; + $module['id'] = (int) $module['id']; + $module['name'] = io_safe_output($module['name']); + $module['id_module_type'] = (int) $module['id_tipo_modulo']; + $module['server_type'] = (int) $module['id_modulo']; + $module['status'] = $module['estado']; + $module['value'] = $module['datos']; + + if (is_metaconsole()) { + $module['serverID'] = $this->serverID; + $module['serverName'] = $this->serverName; + } + else { + $module['serverName'] = false; + $module['serverID'] = false; + } + + if (!isset($module['value'])) + $module['value'] = modules_get_last_value($module['id']); + + // Status + switch ($module['status']) { + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + $module['alert'] = 1; + case AGENT_MODULE_STATUS_CRITICAL_BAD: + $statusType = STATUS_MODULE_CRITICAL_BALL; + $statusTitle = __('CRITICAL'); + $module['statusText'] = "critical"; + break; + case AGENT_MODULE_STATUS_WARNING_ALERT: + $module['alert'] = 1; + case AGENT_MODULE_STATUS_WARNING: + $statusType = STATUS_MODULE_WARNING_BALL; + $statusTitle = __('WARNING'); + $module['statusText'] = "warning"; + break; + case AGENT_MODULE_STATUS_UNKNOWN: + $statusType = STATUS_MODULE_UNKNOWN_BALL; + $statusTitle = __('UNKNOWN'); + $module['statusText'] = "unknown"; + break; + case AGENT_MODULE_STATUS_NO_DATA: + case AGENT_MODULE_STATUS_NOT_INIT: + $statusType = STATUS_MODULE_NO_DATA_BALL; + $statusTitle = __('NO DATA'); + $module['statusText'] = "not_init"; + break; + case AGENT_MODULE_STATUS_NORMAL_ALERT: + $module['alert'] = 1; + case AGENT_MODULE_STATUS_NORMAL: + default: + $statusType = STATUS_MODULE_OK_BALL; + $statusTitle = __('NORMAL'); + $module['statusText'] = "ok"; + break; + } + + if ($statusType !== STATUS_MODULE_UNKNOWN_BALL + && $statusType !== STATUS_MODULE_NO_DATA_BALL) { + if (is_numeric($module["value"])) { + $statusTitle .= " : " . format_for_graph($module["value"]); + } + else { + $statusTitle .= " : " . substr(io_safe_output($module["value"]),0,42); + } + } + + $module['statusImageHTML'] = ui_print_status_image($statusType, $statusTitle, true); + + // HTML of the server type image + $module['serverTypeHTML'] = servers_show_type($module['server_type']); + + // Link to the Module graph + + // ACL + $acl_graphs = false; + $module["showGraphs"] = 0; + + // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions + if (!empty($group_id) && !is_metaconsole()) { + $acl_graphs = check_acl_one_of_groups($config['id_user'], $all_groups, "RR"); + } + else if (!empty($all_groups)) { + $acl_graphs = true; + } + + if ($acl_graphs) { + $module["showGraphs"] = 1; + } + + if ($module["showGraphs"]) { + $graphType = return_graphtype($module['id_module_type']); + $url = ui_get_full_url("operation/agentes/stat_win.php", false, false, false); + $winHandle = dechex(crc32($module['id'].$module['name'])); + + $graph_params = array( + "type" => $graphType, + "period" => SECONDS_1DAY, + "id" => $module['id'], + "label" => base64_encode($module['name']), + "refresh" => SECONDS_10MINUTES + ); + + if (is_metaconsole()) { + // Set the server id + $graph_params["server"] = $module['serverID']; + } + + $graph_params_str = http_build_query($graph_params); + $moduleGraphURL = "$url?$graph_params_str"; + + $module['moduleGraph'] = array( + 'url' => $moduleGraphURL, + 'handle' => $winHandle + ); + + // Info to be able to open the snapshot image new page + $module['snapshot'] = ui_get_snapshot_link(array( + 'id_module' => $module['id'], + 'interval' => $module['current_interval'], + 'module_name' => $module['name'], + 'id_node' => $module['serverID'] ? $module['serverID'] : 0, + ), true); + } + + // Alerts fired image + if ((bool)$module['alerts']) { + $module['alertsImageHTML'] = html_print_image("images/bell.png", true, array("title" => __('Module alerts'))); + } + } + + protected function processModules (&$modules, $server = false) { + if (!empty($modules)) { + $all_groups = modules_get_agent_groups($modules[0]['id']); + } + foreach ($modules as $iterator => $module) { + $this->processModule($modules[$iterator], $server, $all_groups); + } + } + + protected function processAgent (&$agent, $server = false) { + global $config; + + $agent['type'] = 'agent'; + $agent['id'] = (int) $agent['id']; + $agent['name'] = $agent['name']; + + $agent['rootID'] = $this->rootID; + $agent['rootType'] = $this->rootType; + + if (is_metaconsole()) { + if (isset($agent['server_id'])) + $agent['serverID'] = $agent['server_id']; + else if (!empty($server)) + $agent['serverID'] = $server['id']; + } + // Counters + if (empty($agent['counters'])) { + $agent['counters'] = array(); + + $agent['counters']['unknown'] = isset($agent['unknown_count']) ? $agent['unknown_count'] : 0; + $agent['counters']['critical'] = isset($agent['critical_count']) ? $agent['critical_count'] : 0; + $agent['counters']['warning'] = isset($agent['warning_count']) ? $agent['warning_count'] : 0; + $agent['counters']['not_init'] = isset($agent['notinit_count']) ? $agent['notinit_count'] : 0; + $agent['counters']['ok'] = isset($agent['normal_count']) ? $agent['normal_count'] : 0; + $agent['counters']['total'] = isset($agent['total_count']) ? $agent['total_count'] : 0; + $agent['counters']['alerts'] = isset($agent['fired_count']) ? $agent['fired_count'] : 0; + } + + // Status image + $agent['statusImageHTML'] = agents_tree_view_status_img_ball( + $agent['counters']['critical'], + $agent['counters']['warning'], + $agent['counters']['unknown'], + $agent['counters']['total'], + $agent['counters']['not_init']); + + // Alerts fired image + $agent["alertImageHTML"] = agents_tree_view_alert_img_ball($agent['counters']['alerts']); + + // search module recalculate counters + if(array_key_exists('state_normal', $agent)){ + $agent['counters']['unknown'] = $agent['state_unknown']; + $agent['counters']['critical'] = $agent['state_critical']; + $agent['counters']['warning'] = $agent['state_warning']; + $agent['counters']['not_init'] = $agent['state_notinit']; + $agent['counters']['ok'] = $agent['state_normal']; + $agent['counters']['total'] = $agent['state_total']; + + $agent['critical_count'] = $agent['counters']['critical']; + $agent['warning_count'] = $agent['counters']['warning']; + $agent['unknown_count'] = $agent['counters']['unknown']; + $agent['notinit_count'] = $agent['counters']['not_init']; + $agent['normal_count'] = $agent['counters']['ok']; + $agent['total_count'] = $agent['counters']['total']; + } + + if (!$this->getEmptyModuleFilterStatus()) { + $agent['counters']['unknown'] = 0; + $agent['counters']['critical'] = 0; + $agent['counters']['warning'] = 0; + $agent['counters']['not_init'] = 0; + $agent['counters']['ok'] = 0; + $agent['counters']['total'] = 0; + switch($this->filter['statusModule']) { + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + case AGENT_MODULE_STATUS_CRITICAL_BAD: + $agent['counters']['critical'] = $agent['critical_count']; + $agent['counters']['total'] = $agent['critical_count']; + break; + case AGENT_MODULE_STATUS_WARNING_ALERT: + case AGENT_MODULE_STATUS_WARNING: + $agent['counters']['warning'] = $agent['warning_count']; + $agent['counters']['total'] = $agent['warning_count']; + break; + case AGENT_MODULE_STATUS_UNKNOWN: + $agent['counters']['unknown'] = $agent['unknown_count']; + $agent['counters']['total'] = $agent['unknown_count']; + break; + case AGENT_MODULE_STATUS_NO_DATA: + case AGENT_MODULE_STATUS_NOT_INIT: + $agent['counters']['not_init'] = $agent['notinit_count']; + $agent['counters']['total'] = $agent['notinit_count']; + break; + case AGENT_MODULE_STATUS_NORMAL_ALERT: + case AGENT_MODULE_STATUS_NORMAL: + $agent['counters']['ok'] = $agent['normal_count']; + $agent['counters']['total'] = $agent['normal_count']; + break; + } + } + + if (!$this->filter['show_not_init_modules']) { + $agent['counters']['total'] -= $agent['counters']['not_init']; + $agent['counters']['not_init'] = 0; + } + + // Quiet image + if (isset($agent['quiet']) && $agent['quiet']) + $agent['quietImageHTML'] = html_print_image("/images/dot_blue.png", true, array("title" => __('Quiet'))); + + // Children + if (empty($agent['children'])) { + $agent['children'] = array(); + if ($agent['counters']['total'] > 0) { + switch ($this->childrenMethod) { + case 'on_demand': + $agent['searchChildren'] = 1; + break; + case 'live': + $agent['searchChildren'] = 0; + break; + } + } + else { + switch ($this->childrenMethod) { + case 'on_demand': + $agent['searchChildren'] = 0; + break; + case 'live': + $agent['searchChildren'] = 0; + break; + } + } + } + } + + protected function processAgents (&$agents, $server = false) { + if (!empty($agents)) { + foreach ($agents as $iterator => $agent) { + $this->processAgent($agents[$iterator], $server); + } + } + } + + protected function getData() { + + } + + protected function getFirstLevel() { + $sql = $this->getFirstLevelSql(); + $items = db_get_all_rows_sql($sql); + if ($items === false) $items = array(); + + $this->tree = $this->getProcessedItemsFirstLevel($items); + } + + protected function getProcessedItemsFirstLevel($items){ + $processed_items = array(); + foreach ($items as $key => $item) { + $processed_item = $this->getProcessedItem($item); + $processed_items[] = $processed_item; + } + return $processed_items; + } + + protected function getFirstLevelSql() { + + $fields = $this->getFirstLevelFields(); + $field_name_sql = $this->L1fieldNameSql; + $inside_fields = $this->getFirstLevelFieldsInside(); + $inner = $this->L1inner; + $inner_inside = $this->L1innerInside; + $order_by_final = $this->L1orderByFinal; + + $group_inner = $this->getGroupSearchInner(); + $group_acl = $this->getGroupAclCondition(); + $group_search_filter = $this->getGroupSearchFilter(); + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_search_filter = $this->getModuleSearchFilter(); + $module_status_inner = ""; + $module_status_filter = $this->getModuleStatusFilterFromTestado(); + if (!empty($module_status_filter)) { + $module_status_inner = " INNER JOIN tagente_estado tae - ON tae.id_agente_modulo = tam.id_agente_modulo'; - } + ON tae.id_agente_modulo = tam.id_agente_modulo"; + } - $sql_model = "SELECT %s FROM + $sql_model = "SELECT %s FROM ( SELECT COUNT(DISTINCT(ta.id_agente)) AS total, $field_name_sql AS g FROM tagente ta @@ -920,42 +778,34 @@ class Tree $group_acl GROUP BY $field_name_sql ) x GROUP BY g"; - $sql_array = []; - foreach ($inside_fields as $inside_field) { - $sql_array[] = sprintf( - $sql_model, - $inside_field['header'], - $inside_field['condition'] - ); - } - - $sql = "SELECT $fields FROM (".implode(' UNION ALL ', $sql_array).") x2 + $sql_array = array(); + foreach ($inside_fields as $inside_field) { + $sql_array[] = sprintf( + $sql_model, + $inside_field['header'], + $inside_field['condition'] + ); + } + $sql = "SELECT $fields FROM (" . implode(" UNION ALL ", $sql_array) . ") x2 $inner GROUP BY g ORDER BY $order_by_final"; - return $sql; - } + return $sql; + } + protected function getSecondLevel() { + $sql = $this->getSecondLevelSql(); + $data = db_process_sql($sql); + if (empty($data)) { + $this->tree = array(); + return; + } + $this->processAgents($data); + $this->tree = $data; + } - protected function getSecondLevel() - { - $sql = $this->getSecondLevelSql(); - $data = db_process_sql($sql); - if (empty($data)) { - $this->tree = []; - return; - } - - $this->processAgents($data); - - $this->tree = $data; - } - - - protected function getSecondLevelSql() - { - $columns = sprintf( - 'ta.id_agente AS id, ta.nombre AS name, ta.alias, + protected function getSecondLevelSql() { + $columns = sprintf("ta.id_agente AS id, ta.nombre AS name, ta.alias, ta.fired_count, ta.normal_count, ta.warning_count, ta.critical_count, ta.unknown_count, ta.notinit_count, ta.total_count, ta.quiet, @@ -965,29 +815,29 @@ class Tree SUM(if(%s, 1, 0)) as state_notinit, SUM(if(%s, 1, 0)) as state_normal, SUM(if(%s AND tae.estado IS NOT NULL, 1, 0)) as state_total - ', - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_CRITICAL_ALERT, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_WARNING_ALERT, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_UNKNOWN, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NO_DATA, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NORMAL, true), - $this->getModuleStatusFilterFromTestado(self::TV_DEFAULT_AGENT_STATUS, true) - ); + ", + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_CRITICAL_ALERT, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_WARNING_ALERT, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_UNKNOWN, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NO_DATA, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NORMAL, true), + $this->getModuleStatusFilterFromTestado(self::TV_DEFAULT_AGENT_STATUS, true) + ); - $inner_or_left = $this->getInnerOrLeftJoin(); - $group_inner = $this->getGroupSearchInner(); - $group_acl = $this->getGroupAclCondition(); - $group_search_filter = $this->getGroupSearchFilter(); - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_search_filter = $this->getModuleSearchFilter(); - $module_status_filter = $this->getModuleStatusFilter(); + $inner_or_left = $this->getInnerOrLeftJoin(); + $group_inner = $this->getGroupSearchInner(); + $group_acl = $this->getGroupAclCondition(); + $group_search_filter = $this->getGroupSearchFilter(); + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_search_filter = $this->getModuleSearchFilter(); + $module_status_filter = $this->getModuleStatusFilter(); - $condition = $this->L2condition; - $condition_inside = $this->L2conditionInside; - $inner = $this->L2inner; + $condition = $this->L2condition; + $condition_inside = $this->L2conditionInside; + $inner = $this->L2inner; - $sql = "SELECT $columns + $sql = "SELECT $columns FROM tagente ta $inner_or_left JOIN tagente_modulo tam ON ta.id_agente = tam.id_agente @@ -1017,48 +867,51 @@ class Tree ORDER BY ta.alias ASC, ta.id_agente ASC "; - return $sql; - } + return $sql; + } + protected function getThirdLevel() { + $sql = $this->getThirdLevelSql(); + $data = db_process_sql($sql); + if (empty($data)) { + $this->tree = array(); + return; + } + $data = $this->getProcessedModules($data); + $this->processModules($data); +hd("MODULES: ", true); +hd($data, true); + $this->tree = $data; + } - protected function getThirdLevel() - { - $sql = $this->getThirdLevelSql(); - $data = db_process_sql($sql); - if (empty($data)) { - $this->tree = []; - return; - } + protected function getThirdLevelSql() { + // Get the server id + $serverID = $this->serverID; - $data = $this->getProcessedModules($data); - $this->processModules($data); + $group_acl = $this->getGroupAclCondition(); + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_search_filter = $this->getModuleSearchFilter(); + $module_status_filter = $this->getModuleStatusFilterFromTestado(); + $agent_filter = "AND ta.id_agente = " . $this->id; + $tag_condition = $this->getTagCondition(); + $tag_join = empty($tag_condition) && (!$this->L3forceTagCondition) + ? '' + : $this->getTagJoin(); - $this->tree = $data; - } + if ($this->avoid_condition === true) { + $condition = ''; + $inner = ''; + } else { + $condition = $this->L2condition; + $inner = $this->L2inner; + } - - protected function getThirdLevelSql() - { - // Get the server id - $serverID = $this->serverID; - - $group_acl = $this->getGroupAclCondition(); - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_search_filter = $this->getModuleSearchFilter(); - $module_status_filter = $this->getModuleStatusFilterFromTestado(); - $agent_filter = 'AND ta.id_agente = '.$this->id; - $tag_condition = $this->getTagCondition(); - $tag_join = empty($tag_condition) && (!$this->L3forceTagCondition) ? '' : $this->getTagJoin(); - - $condition = $this->L2condition; - $inner = $this->L2inner; - - $columns = 'DISTINCT(tam.id_agente_modulo) AS id, tam.nombre AS name, + $columns = 'DISTINCT(tam.id_agente_modulo) AS id, tam.nombre AS name, tam.id_tipo_modulo, tam.id_modulo, tae.estado, tae.datos, tam.parent_module_id AS parent, tatm.id AS alerts'; - $sql = "SELECT $columns + $sql = "SELECT $columns FROM tagente_modulo tam $tag_join INNER JOIN tagente_estado tae @@ -1076,81 +929,57 @@ class Tree $group_acl $agent_search_filter $agent_status_filter - $module_status_filter $module_search_filter $tag_condition ORDER BY tam.nombre ASC, tam.id_agente_modulo ASC"; - return $sql; - } + return $sql; + } - public function getJSON() - { - $this->getData(); + public function getJSON() { + $this->getData(); - return json_encode($this->tree); - } + return json_encode($this->tree); + } + public function getArray() { + $this->getData(); - public function getArray() - { - $this->getData(); + return $this->tree; + } - return $this->tree; - } + static function name2symbol($name) { + return str_replace( + array(' ','#','/','.','(',')','¿','?','¡','!'), + array( + '_articapandora_'.ord(' ').'_pandoraartica_', + '_articapandora_'.ord('#').'_pandoraartica_', + '_articapandora_'.ord('/').'_pandoraartica_', + '_articapandora_'.ord('.').'_pandoraartica_', + '_articapandora_'.ord('(').'_pandoraartica_', + '_articapandora_'.ord(')').'_pandoraartica_', + '_articapandora_'.ord('¿').'_pandoraartica_', + '_articapandora_'.ord('?').'_pandoraartica_', + '_articapandora_'.ord('¡').'_pandoraartica_', + '_articapandora_'.ord('!').'_pandoraartica_' + ), + io_safe_output($name) + ); + } + static function symbol2name($name) { + $symbols = ' !"#$%&\'()*+,./:;<=>?@[\\]^{|}~'; + for ($i = 0; $i < strlen($symbols); $i++) { + $name = str_replace('_articapandora_' . + ord(substr($symbols, $i, 1)) .'_pandoraartica_', + substr($symbols, $i, 1), $name); + } + return io_safe_input($name); + } - static function name2symbol($name) - { - return str_replace( - [ - ' ', - '#', - '/', - '.', - '(', - ')', - '¿', - '?', - '¡', - '!', - ], - [ - '_articapandora_'.ord(' ').'_pandoraartica_', - '_articapandora_'.ord('#').'_pandoraartica_', - '_articapandora_'.ord('/').'_pandoraartica_', - '_articapandora_'.ord('.').'_pandoraartica_', - '_articapandora_'.ord('(').'_pandoraartica_', - '_articapandora_'.ord(')').'_pandoraartica_', - '_articapandora_'.ord('¿').'_pandoraartica_', - '_articapandora_'.ord('?').'_pandoraartica_', - '_articapandora_'.ord('¡').'_pandoraartica_', - '_articapandora_'.ord('!').'_pandoraartica_', - ], - io_safe_output($name) - ); - } - - - static function symbol2name($name) - { - $symbols = ' !"#$%&\'()*+,./:;<=>?@[\\]^{|}~'; - for ($i = 0; $i < strlen($symbols); $i++) { - $name = str_replace( - '_articapandora_'.ord(substr($symbols, $i, 1)).'_pandoraartica_', - substr($symbols, $i, 1), - $name - ); - } - - return io_safe_input($name); - } - - - protected function getProcessedModules($modules_tree) - { - return $modules_tree; - } - + protected function getProcessedModules($modules_tree) { + return $modules_tree; + } } +?> diff --git a/pandora_console/include/class/TreeGroup.class.php b/pandora_console/include/class/TreeGroup.class.php index bef4287c7d..fd38794d1c 100644 --- a/pandora_console/include/class/TreeGroup.class.php +++ b/pandora_console/include/class/TreeGroup.class.php @@ -1,215 +1,193 @@ L1fieldName = "id_group"; + $this->L1extraFields = array( + "tg.nombre AS `name`", + "tg.icon", + "tg.id_grupo AS gid" + ); - $this->L1fieldName = 'id_group'; - $this->L1extraFields = [ - 'tg.nombre AS `name`', - 'tg.icon', - 'tg.id_grupo AS gid', - ]; + $this->L2conditionInside = "AND ( + ta.id_grupo = " . $this->id . " + OR tasg.id_group = " . $this->id . " + )"; + } - $this->L2conditionInside = 'AND ( - ta.id_grupo = '.$this->id.' - OR tasg.id_group = '.$this->id.' - )'; - } + public function setPropagateCounters($value) { + $this->propagateCounters = (bool)$value; + } + public function setDisplayAllGroups($value) { + $this->displayAllGroups = (bool)$value; + } - public function setPropagateCounters($value) - { - $this->propagateCounters = (bool) $value; - } + protected function getData() { + if ($this->id == -1) { + $this->getFirstLevel(); - public function setDisplayAllGroups($value) - { - $this->displayAllGroups = (bool) $value; - } + } elseif ($this->type == 'group') { + $this->getSecondLevel(); + } elseif ($this->type == 'agent') { + $this->getThirdLevel(); + } + } + protected function getGroupSearchFilter() { + return ""; + } - protected function getData() - { - if ($this->id == -1) { - $this->getFirstLevel(); - } else if ($this->type == 'group') { - $this->getSecondLevel(); - } else if ($this->type == 'agent') { - $this->getThirdLevel(); - } - } + protected function getFirstLevel() { + $processed_items = $this->getProcessedGroups(); + if (!empty($processed_items)) { + // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants + if (!empty($this->filter['searchGroup'])) { + // Save the groups which intersect with the user groups + $groups = db_get_all_rows_filter('tgrupo', array('nombre' => '%' . $this->filter['searchGroup'] . '%')); + if ($groups == false) $groups = array(); + $userGroupsACL = $this->userGroupsACL; + $ids_hash = array_reduce($groups, function ($userGroups, $group) use ($userGroupsACL) { + $group_id = $group['id_grupo']; + if (isset($userGroupsACL[$group_id])) { + $userGroups[$group_id] = $userGroupsACL[$group_id]; + } - protected function getGroupSearchFilter() - { - return ''; - } + return $userGroups; + }, array()); + $result = self::extractGroupsWithIDs($processed_items, $ids_hash); - protected function getFirstLevel() - { - $processed_items = $this->getProcessedGroups(); + $processed_items = ($result === false) ? array() : $result; + } - if (!empty($processed_items)) { - // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants - if (!empty($this->filter['searchGroup'])) { - // Save the groups which intersect with the user groups - $groups = db_get_all_rows_filter('tgrupo', ['nombre' => '%'.$this->filter['searchGroup'].'%']); - if ($groups == false) { - $groups = []; - } + // groupID filter. To access the view from tactical views f.e. + if (!empty($this->filter['groupID'])) { + $result = self::extractItemWithID($processed_items, $this->filter['groupID'], "group", $this->strictACL); - $userGroupsACL = $this->userGroupsACL; - $ids_hash = array_reduce( - $groups, - function ($userGroups, $group) use ($userGroupsACL) { - $group_id = $group['id_grupo']; - if (isset($userGroupsACL[$group_id])) { - $userGroups[$group_id] = $userGroupsACL[$group_id]; - } + $processed_items = ($result === false) ? array() : array($result); + } + } + hd("G-GETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVEL", true); +hd($processed_items, true); + $this->tree = $processed_items; + } - return $userGroups; - }, - [] - ); + protected function getProcessedGroups () { + $processed_groups = array(); + // Index and process the groups + $groups = $this->getGroupCounters(); - $result = self::extractGroupsWithIDs($processed_items, $ids_hash); + // If user have not permissions in parent, set parent node to 0 (all) + // Avoid to do foreach for admins + if (!users_can_manage_group_all("AR")) { + foreach ($groups as $id => $group) { + if (!isset($this->userGroups[$groups[$id]['parent']])) { + $groups[$id]['parent'] = 0; + } + } + } + // Build the group hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = array(); + } + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], array("Tree", "cmpSortNames")); + } + } + //Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter($groups, function ($group) { + return !$group['have_parent']; + }); + // Propagate child counters to her parents - $processed_items = ($result === false) ? [] : $result; - } + if ($this->propagateCounters) { + TreeGroup::processCounters($groups); + // Filter groups and eliminates the reference to empty groups + $groups = $this->deleteEmptyGroups($groups); + } else { + $groups = $this->deleteEmptyGroupsNotPropagate($groups); + } - // groupID filter. To access the view from tactical views f.e. - if (!empty($this->filter['groupID'])) { - $result = self::extractItemWithID($processed_items, $this->filter['groupID'], 'group', $this->strictACL); + usort($groups, array("Tree", "cmpSortNames")); - $processed_items = ($result === false) ? [] : [$result]; - } - } + return $groups; + } - $this->tree = $processed_items; - } + protected function getGroupCounters() { + $fields = $this->getFirstLevelFields(); + $inside_fields = $this->getFirstLevelFieldsInside(); + $group_acl = ""; + $secondary_group_acl = ""; + if (!users_can_manage_group_all("AR")) { + $user_groups_str = implode(",", $this->userGroupsArray); + $group_acl = " AND ta.id_grupo IN ($user_groups_str)"; + $secondary_group_acl = " AND tasg.id_group IN ($user_groups_str)"; + } + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_search_filter = preg_replace("/%/", "%%", $agent_search_filter); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_status_filter = $this->getModuleStatusFilter(); - protected function getProcessedGroups() - { - $processed_groups = []; - // Index and process the groups - $groups = $this->getGroupCounters(); - - // If user have not permissions in parent, set parent node to 0 (all) - // Avoid to do foreach for admins - if (!users_can_manage_group_all('AR')) { - foreach ($groups as $id => $group) { - if (!isset($this->userGroups[$groups[$id]['parent']])) { - $groups[$id]['parent'] = 0; - } - } - } - - // Build the group hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = []; - } - - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } - - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); - } - } - - // Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter( - $groups, - function ($group) { - return !$group['have_parent']; - } - ); - // Propagate child counters to her parents - if ($this->propagateCounters) { - self::processCounters($groups); - // Filter groups and eliminates the reference to empty groups - $groups = $this->deleteEmptyGroups($groups); - } else { - $groups = $this->deleteEmptyGroupsNotPropagate($groups); - } - - usort($groups, ['Tree', 'cmpSortNames']); - return $groups; - } - - - protected function getGroupCounters() - { - $fields = $this->getFirstLevelFields(); - $inside_fields = $this->getFirstLevelFieldsInside(); - - $group_acl = ''; - $secondary_group_acl = ''; - if (!users_can_manage_group_all('AR')) { - $user_groups_str = implode(',', $this->userGroupsArray); - $group_acl = " AND ta.id_grupo IN ($user_groups_str)"; - $secondary_group_acl = " AND tasg.id_group IN ($user_groups_str)"; - } - - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_search_filter = preg_replace('/%/', '%%', $agent_search_filter); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_status_filter = $this->getModuleStatusFilter(); - - $module_search_inner = ''; - $module_search_filter = ''; - if (!empty($this->filter['searchModule'])) { - $module_search_inner = ' + $module_search_inner = ""; + $module_search_filter = ""; + if (!empty($this->filter['searchModule'])) { + $module_search_inner = " INNER JOIN tagente_modulo tam ON ta.id_agente = tam.id_agente INNER JOIN tagente_estado tae - ON tae.id_agente_modulo = tam.id_agente_modulo'; - $module_search_filter = "AND tam.disabled = 0 - AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' ".$this->getModuleStatusFilterFromTestado(); - } + ON tae.id_agente_modulo = tam.id_agente_modulo"; + $module_search_filter = "AND tam.disabled = 0 + AND tam.nombre LIKE '%%" . $this->filter['searchModule'] . "%%' " . + $this->getModuleStatusFilterFromTestado() + ; + } - $table = is_metaconsole() ? 'tmetaconsole_agent' : 'tagente'; - $table_sec = is_metaconsole() ? 'tmetaconsole_agent_secondary_group' : 'tagent_secondary_group'; + $table = is_metaconsole() ? "tmetaconsole_agent" : "tagente"; + $table_sec = is_metaconsole() ? "tmetaconsole_agent_secondary_group" : "tagent_secondary_group"; - $sql_model = "SELECT %s FROM + $sql_model = "SELECT %s FROM ( SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_grupo AS g FROM $table ta @@ -236,294 +214,254 @@ class TreeGroup extends Tree $secondary_group_acl GROUP BY id_group ) x GROUP BY g"; - $sql_array = []; - foreach ($inside_fields as $inside_field) { - $sql_array[] = sprintf( - $sql_model, - $inside_field['header'], - $inside_field['condition'], - $inside_field['condition'] - ); - } - - $sql = "SELECT $fields FROM (".implode(' UNION ALL ', $sql_array).') x2 + $sql_array = array(); + foreach ($inside_fields as $inside_field) { + $sql_array[] = sprintf( + $sql_model, + $inside_field['header'], + $inside_field['condition'], + $inside_field['condition'] + ); + } + $sql = "SELECT $fields FROM (" . implode(" UNION ALL ", $sql_array) . ") x2 RIGHT JOIN tgrupo tg ON x2.g = tg.id_grupo - GROUP BY tg.id_grupo'; - $stats = db_get_all_rows_sql($sql); + GROUP BY tg.id_grupo"; + $stats = db_get_all_rows_sql($sql); - $group_stats = []; - foreach ($stats as $group) { - $group_stats[$group['gid']]['total_count'] = (int) $group['total_count']; - $group_stats[$group['gid']]['total_critical_count'] = (int) $group['total_critical_count']; - $group_stats[$group['gid']]['total_unknown_count'] = (int) $group['total_unknown_count']; - $group_stats[$group['gid']]['total_warning_count'] = (int) $group['total_warning_count']; - $group_stats[$group['gid']]['total_not_init_count'] = (int) $group['total_not_init_count']; - $group_stats[$group['gid']]['total_normal_count'] = (int) $group['total_normal_count']; - $group_stats[$group['gid']]['total_fired_count'] = (int) $group['total_alerts_count']; - $group_stats[$group['gid']]['name'] = $group['name']; - $group_stats[$group['gid']]['parent'] = $group['parent']; - $group_stats[$group['gid']]['icon'] = $group['icon']; - $group_stats[$group['gid']]['id'] = $group['gid']; - $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); - } + $group_stats = array(); - return $group_stats; - } + hd("STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS ", true); + hd($stats, true); + foreach ($stats as $group) { + $group_stats[$group['gid']]['total_count'] = (int)$group['total_count']; + $group_stats[$group['gid']]['total_critical_count'] = (int)$group['total_critical_count']; + $group_stats[$group['gid']]['total_unknown_count'] = (int)$group['total_unknown_count']; + $group_stats[$group['gid']]['total_warning_count'] = (int)$group['total_warning_count']; + $group_stats[$group['gid']]['total_not_init_count'] = (int)$group['total_not_init_count']; + $group_stats[$group['gid']]['total_normal_count'] = (int)$group['total_normal_count']; + $group_stats[$group['gid']]['total_fired_count'] = (int)$group['total_alerts_count']; + $group_stats[$group['gid']]['name'] = $group['name']; + $group_stats[$group['gid']]['parent'] = $group['parent']; + $group_stats[$group['gid']]['icon'] = $group['icon']; + $group_stats[$group['gid']]['id'] = $group['gid']; + $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); + + } - protected function getFirstLevelFields() - { - $fields = parent::getFirstLevelFields(); - $parent = $this->getDisplayHierarchy() ? 'tg.parent' : '0 as parent'; - return "$fields, $parent"; - } + return $group_stats; + } - protected function getProcessedModules($modules_tree) - { - $groups = []; - foreach ($modules_tree as $group) { - $groups[$group['id']] = $group; - } + protected function getFirstLevelFields() { + $fields = parent::getFirstLevelFields(); + $parent = $this->getDisplayHierarchy() ? 'tg.parent' : '0 as parent'; + return "$fields, $parent"; + } - // Build the module hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = []; - } + protected function getProcessedModules($modules_tree) { - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } + $groups = array(); + foreach ($modules_tree as $group) { + $groups[$group["id"]] = $group; + } - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); - } - } + // Build the module hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = array(); + } + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } - // Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter( - $groups, - function ($group) { - return !$group['have_parent']; - } - ); + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], array("Tree", "cmpSortNames")); + } + } + //Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter($groups, function ($group) { + return !$group['have_parent']; + }); - return array_values($groups); - } + return array_values($groups); + } + // FIXME: Hierarchy lops is broken + protected function getProcessedModules_old($modules_tree) { - // FIXME: Hierarchy lops is broken - protected function getProcessedModules_old($modules_tree) - { - $tree_modules = []; - $new_modules_root = array_filter( - $modules_tree, - function ($module) { - return (isset($module['parent']) && ($module['parent'] == 0)); - } - ); + $tree_modules = array(); + $new_modules_root = array_filter($modules_tree, function ($module) { + return (isset($module['parent']) && ($module['parent'] == 0)); + }); - $new_modules_child = array_filter( - $modules_tree, - function ($module) { - return (isset($module['parent']) && ($module['parent'] != 0)); - } - ); + $new_modules_child = array_filter($modules_tree, function ($module) { + return (isset($module['parent']) && ($module['parent'] != 0)); + }); - $i = 0; - while (!empty($new_modules_child)) { - foreach ($new_modules_child as $i => $child) { - self::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child); - } - } + $i = 0; + while (!empty($new_modules_child)) { + foreach ($new_modules_child as $i => $child) { + TreeGroup::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child); + } + } - foreach ($new_modules_root as $m) { - $tree_modules[] = $m; - } + foreach ($new_modules_root as $m) { + $tree_modules[] = $m; + } + return $tree_modules; + } - return $tree_modules; - } + // FIXME with getProcessedModules_old + static function recursive_modules_tree_view (&$new_modules, &$new_modules_child, $i, $child) { + foreach ($new_modules as $index => $module) { + if ($module['id'] == $child['parent']) { + $new_modules[$index]['children'][] = $child; + unset($new_modules_child[$i]); + break; + } + else if (isset($new_modules[$index]['children'])) { + TreeGroup::recursive_modules_tree_view ($new_modules[$index]['children'], $new_modules_child, $i, $child); + } + } + } + static function processCounters(&$groups) { + $all_counters = array(); + foreach ($groups as $id => $group) { + $child_counters = array(); + if (!empty($groups[$id]['children'])) { + $child_counters = TreeGroup::processCounters($groups[$id]['children']); + } + if (!empty($child_counters)) { + foreach($child_counters as $type => $value) { + $groups[$id]['counters'][$type] += $value; + } + } + foreach($groups[$id]['counters'] as $type => $value) { + $all_counters[$type] += $value; + } + } + return $all_counters; + } - // FIXME with getProcessedModules_old - static function recursive_modules_tree_view(&$new_modules, &$new_modules_child, $i, $child) - { - foreach ($new_modules as $index => $module) { - if ($module['id'] == $child['parent']) { - $new_modules[$index]['children'][] = $child; - unset($new_modules_child[$i]); - break; - } else if (isset($new_modules[$index]['children'])) { - self::recursive_modules_tree_view($new_modules[$index]['children'], $new_modules_child, $i, $child); - } - } - } + /** + * @brief Recursive function to remove the empty groups + * + * @param groups All groups structure + * + * @return new_groups A new groups structure without empty groups + */ + protected function deleteEmptyGroups ($groups) { + if($this->displayAllGroups) return $groups; + $new_groups = array(); + foreach ($groups as $group) { + // If a group is empty, do not add to new_groups. + if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) { + continue; + } + // Tray to remove the children groups + if (!empty($group['children'])) { + $children = $this->deleteEmptyGroups ($group['children']); + if (empty($children)) unset($group['children']); + else $group['children'] = $children; + } + $new_groups[] = $group; + } + return $new_groups; + } + protected function deleteEmptyGroupsNotPropagate ($groups) { + if($this->displayAllGroups) return $groups; + $new_groups = array(); + foreach ($groups as $group) { + // Tray to remove the children groups + if (!empty($group['children'])) { + $children = $this->deleteEmptyGroupsNotPropagate ($group['children']); + if (empty($children)) { + unset($group['children']); + // If a group is empty, do not add to new_groups. + if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { + $new_groups[] = $group; + } + } else { + $group['children'] = $children; + $new_groups[] = $group; + } + } else { + // If a group is empty, do not add to new_groups. + if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { + $new_groups[] = $group; + } + } + } + return $new_groups; + } - static function processCounters(&$groups) - { - $all_counters = []; - foreach ($groups as $id => $group) { - $child_counters = []; - if (!empty($groups[$id]['children'])) { - $child_counters = self::processCounters($groups[$id]['children']); - } + private static function extractGroupsWithIDs ($groups, $ids_hash) { + $result_groups = array(); + foreach ($groups as $group) { + if (isset($ids_hash[$group['id']])) { + $result_groups[] = $group; + } + else if (!empty($group['children'])) { + $result = self::extractGroupsWithIDs($group['children'], $ids_hash); - if (!empty($child_counters)) { - foreach ($child_counters as $type => $value) { - $groups[$id]['counters'][$type] += $value; - } - } + // Item found on children + if (!empty($result)) { + $result_groups = array_merge($result_groups, $result); + } + } + } - foreach ($groups[$id]['counters'] as $type => $value) { - $all_counters[$type] += $value; - } - } + return $result_groups; + } - return $all_counters; - } + private static function extractItemWithID ($items, $item_id, $item_type = "group", $strictACL = false) { + foreach ($items as $item) { + if ($item["type"] != $item_type) + continue; + // Item found + if ($strictACL && is_metaconsole()) { + foreach ($item["id"] as $server_id => $id) { + if ($id == $item_id) + return $item; + } + } + else { + if ($item["id"] == $item_id) + return $item; + } - /** - * @brief Recursive function to remove the empty groups - * - * @param groups All groups structure - * - * @return new_groups A new groups structure without empty groups - */ - protected function deleteEmptyGroups($groups) - { - if ($this->displayAllGroups) { - return $groups; - } + if ($item["type"] == "group" && !empty($item["children"])) { + $result = self::extractItemWithID($item["children"], $item_id, $item_type, $strictACL); - $new_groups = []; - foreach ($groups as $group) { - // If a group is empty, do not add to new_groups. - if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) { - continue; - } + // Item found on children + if ($result !== false) + return $result; + } + } - // Tray to remove the children groups - if (!empty($group['children'])) { - $children = $this->deleteEmptyGroups($group['children']); - if (empty($children)) { - unset($group['children']); - } else { - $group['children'] = $children; - } - } - - $new_groups[] = $group; - } - - return $new_groups; - } - - - protected function deleteEmptyGroupsNotPropagate($groups) - { - if ($this->displayAllGroups) { - return $groups; - } - - $new_groups = []; - foreach ($groups as $group) { - // Tray to remove the children groups - if (!empty($group['children'])) { - $children = $this->deleteEmptyGroupsNotPropagate($group['children']); - if (empty($children)) { - unset($group['children']); - // If a group is empty, do not add to new_groups. - if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { - $new_groups[] = $group; - } - } else { - $group['children'] = $children; - $new_groups[] = $group; - } - } else { - // If a group is empty, do not add to new_groups. - if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { - $new_groups[] = $group; - } - } - } - - return $new_groups; - } - - - private static function extractGroupsWithIDs($groups, $ids_hash) - { - $result_groups = []; - foreach ($groups as $group) { - if (isset($ids_hash[$group['id']])) { - $result_groups[] = $group; - } else if (!empty($group['children'])) { - $result = self::extractGroupsWithIDs($group['children'], $ids_hash); - - // Item found on children - if (!empty($result)) { - $result_groups = array_merge($result_groups, $result); - } - } - } - - return $result_groups; - } - - - private static function extractItemWithID($items, $item_id, $item_type='group', $strictACL=false) - { - foreach ($items as $item) { - if ($item['type'] != $item_type) { - continue; - } - - // Item found - if ($strictACL && is_metaconsole()) { - foreach ($item['id'] as $server_id => $id) { - if ($id == $item_id) { - return $item; - } - } - } else { - if ($item['id'] == $item_id) { - return $item; - } - } - - if ($item['type'] == 'group' && !empty($item['children'])) { - $result = self::extractItemWithID($item['children'], $item_id, $item_type, $strictACL); - - // Item found on children - if ($result !== false) { - return $result; - } - } - } - - // Item not found - return false; - } - - - protected function getDisplayHierarchy() - { - return $this->filter['searchHirearchy'] || - (empty($this->filter['searchAgent']) && empty($this->filter['searchModule'])); - } + // Item not found + return false; + } + protected function getDisplayHierarchy() { + return $this->filter['searchHirearchy'] || + (empty($this->filter['searchAgent']) && empty($this->filter['searchModule'])); + } } + +?> + diff --git a/pandora_console/include/class/TreeGroupEdition.class.php b/pandora_console/include/class/TreeGroupEdition.class.php index 55efebe976..dea62da238 100644 --- a/pandora_console/include/class/TreeGroupEdition.class.php +++ b/pandora_console/include/class/TreeGroupEdition.class.php @@ -1,120 +1,108 @@ id == -1) { + $this->getFirstLevel(); + } + } + + protected function getProcessedGroups () { + $processed_groups = array(); + // Index and process the groups + $groups = $this->getGroupCounters(); + + // If user have not permissions in parent, set parent node to 0 (all) + // Avoid to do foreach for admins + if (!users_can_manage_group_all("AR")) { + foreach ($groups as $id => $group) { + if (!isset($this->userGroups[$groups[$id]['parent']])) { + $groups[$id]['parent'] = 0; + } + } + } + // Build the group hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = array(); + } + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } + + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], array("Tree", "cmpSortNames")); + } + } + //Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter($groups, function ($group) { + return !$group['have_parent']; + }); + + usort($groups, array("Tree", "cmpSortNames")); + return $groups; + } - public function __construct($type, $rootType='', $id=-1, $rootID=-1, $serverID=false, $childrenMethod='on_demand', $access='AR') - { - global $config; - - parent::__construct($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - } - - - protected function getData() - { - if ($this->id == -1) { - $this->getFirstLevel(); - } - } - - - protected function getProcessedGroups() - { - $processed_groups = []; - // Index and process the groups - $groups = $this->getGroupCounters(); - - // If user have not permissions in parent, set parent node to 0 (all) - // Avoid to do foreach for admins - if (!users_can_manage_group_all('AR')) { - foreach ($groups as $id => $group) { - if (!isset($this->userGroups[$groups[$id]['parent']])) { - $groups[$id]['parent'] = 0; - } - } - } - - // Build the group hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = []; - } - - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } - - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); - } - } - - // Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter( - $groups, - function ($group) { - return !$group['have_parent']; - } - ); - - usort($groups, ['Tree', 'cmpSortNames']); - return $groups; - } - - - protected function getGroupCounters() - { - $messages = [ - 'confirm' => __('Confirm'), - 'cancel' => __('Cancel'), - 'messg' => __('Are you sure?'), - ]; - $sql = 'SELECT id_grupo AS gid, + protected function getGroupCounters() { + $messages = array( + 'confirm' => __('Confirm'), + 'cancel' => __('Cancel'), + 'messg' => __('Are you sure?') + ); + $sql = "SELECT id_grupo AS gid, nombre as name, parent, icon FROM tgrupo - '; + "; - $stats = db_get_all_rows_sql($sql); - $group_stats = []; - foreach ($stats as $group) { - $group_stats[$group['gid']]['name'] = $group['name']; - $group_stats[$group['gid']]['parent'] = $group['parent']; - $group_stats[$group['gid']]['icon'] = $group['icon']; - $group_stats[$group['gid']]['id'] = $group['gid']; - $group_stats[$group['gid']]['type'] = 'group'; - - $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); - $group_stats[$group['gid']]['delete']['messages'] = $messages; - $group_stats[$group['gid']]['edit'] = 1; - $group_stats[$group['gid']]['alerts'] = ''; - } - - return $group_stats; - } + $stats = db_get_all_rows_sql($sql); + $group_stats = array(); + foreach ($stats as $group) { + $group_stats[$group['gid']]['name'] = $group['name']; + $group_stats[$group['gid']]['parent'] = $group['parent']; + $group_stats[$group['gid']]['icon'] = $group['icon']; + $group_stats[$group['gid']]['id'] = $group['gid']; + $group_stats[$group['gid']]['type'] = 'group'; + $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); + $group_stats[$group['gid']]['delete']['messages'] = $messages; + $group_stats[$group['gid']]['edit'] = 1; + $group_stats[$group['gid']]['alerts'] = ''; + } + return $group_stats; + } } + +?> + diff --git a/pandora_console/include/class/TreeService.class.php b/pandora_console/include/class/TreeService.class.php new file mode 100644 index 0000000000..46f9139427 --- /dev/null +++ b/pandora_console/include/class/TreeService.class.php @@ -0,0 +1,342 @@ +L1fieldName = "id_group"; + $this->L1extraFields = array( + "ts.name AS `name`", + "ts.id AS `sid`" + ); + + $this->filter['statusAgent'] = AGENT_STATUS_ALL; + + $this->avoid_condition = true; + + $this->L2inner = 'LEFT JOIN tservice_element tse + ON tse.id_agent = ta.id_agente'; + + $this->L2condition = 'AND tse.id_service='.$this->id; + + } + + public function setPropagateCounters($value) { + $this->propagateCounters = (bool)$value; + } + + public function setDisplayAllGroups($value) { + $this->displayAllGroups = (bool)$value; + } + + protected function getData() { + if ($this->id == -1) { + $this->getFirstLevel(); + } elseif ($this->type == 'services') { + $this->getSecondLevel(); + } elseif ($this->type == 'agent') { + $this->getThirdLevel(); + } + } + + protected function getFirstLevel() { + $processed_items = $this->getProcessedServices(); + $ids = array_keys($processed_items); + + + + $filter=array('id'=>$ids); + + $own_info = get_user_info($config['id_user']); + + if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $display_all_services = true; + } else { + $display_all_services = false; + } + + $this->tree = []; + + $services = services_get_services($filter, false, $display_all_services); + + foreach ($services as $row) { + + + + $status = services_get_status($row, true); + + switch ($status) { + + case SERVICE_STATUS_NORMAL: + $processed_items[$row['id']]['statusImageHTML']='NORMAL status.'; + break; + + case SERVICE_STATUS_CRITICAL: + $processed_items[$row['id']]['statusImageHTML']='CRITICAL status.'; + break; + + case SERVICE_STATUS_WARNING: + $processed_items[$row['id']][$key]['statusImageHTML']='WARNING status.'; + break; + + case SERVICE_STATUS_UNKNOWN: + default: + $processed_items[$row['id']]['statusImageHTML']='UNKNOWN status.'; + break; + } + } + + $this->tree = $processed_items; + } + + protected function getProcessedServices () { + $fields = $this->getFirstLevelFields(); + + //hd($this->userGroupsArray, true); + + if (users_can_manage_group_all("AR")){ + $groups_acl = ""; + } + else{ + $groups_acl = "AND ts.id_group IN (".implode(',', $this->userGroupsArray).")"; + } + + $sql = sprintf("SELECT t1.* + FROM tservice_element tss + RIGHT JOIN + (SELECT ts.id, ts.id_agent_module, ts.name, ts.name AS `alias`, ts.id AS `rootID`, + 'services' AS rootType, 'services' AS type, + 0 AS quiet, + SUM(if((tse.id_agent<>0), 1, 0)) AS `total_agents`, + SUM(if((tse.id_agente_modulo<>0), 1, 0)) AS `total_modules`, + SUM(if((tse.id_service_child<>0), 1, 0)) AS `total_services` + FROM tservice ts + LEFT JOIN tservice_element tse + ON ts.id=tse.id_service + GROUP BY id + ) as t1 + ON tss.id_service_child = t1.id + WHERE tss.id_service_child IS NULL + %s + ", + $groups_acl + ); + + + $stats = db_get_all_rows_sql($sql); + + + + + $services = array(); + + foreach ($stats as $service) { + $services[$service['id']] = $this->getProcessedItem($services[$service['id']]); + if ($service['total_services']+$service['total_agents']+$service['total_modules'] > 0) + $services[$service['id']]['searchChildren'] = 1; + else + $services[$service['id']]['searchChildren'] = 0; + + $services[$service['id']]['counters'] = array('total_services'=>$service['total_services'], 'total_agents'=>$service['total_agents'], 'total_modules'=>$service['total_modules']); + $services[$service['id']]['name'] = $service['name']; + $services[$service['id']]['id'] = $service['id']; + $services[$service['id']]['serviceDetail']='http://localhost/pandora_console/index.php?sec=network&sec2=enterprise/operation/services/services&tab=service_map&id_service='.(int)$service['id']; + } + + hd("STATS:::::::::::::::::::::::::::::: ", true); +hd($services, true); + + return $services; + } + + protected function getFirstLevelFields() { + $fields = array(); + + return implode(",", array_merge($fields, $this->L1extraFields)); + } + + protected function getSecondLevel() { + $data = array(); + $data_agents = array(); + $data_modules = array(); + $data_services = array(); + + $sql = $this->getSecondLevelSql(); + $data_agents = db_process_sql($sql); + + if (empty($data_agents)) + $data_agents = array(); + + $this->processAgents($data_agents); + + foreach ($data_agents as $key => $agent) { + $data_agents[$key]['showEventsBtn'] = 1; + $data_agents[$key]['eventAgent'] = $agent['id']; + } + + $sql = $this->getSecondLevelModulesSql(); + $data_modules = db_process_sql($sql); + + if (empty($data_modules)) + $data_modules = array(); + else { + foreach ($data_modules as $key => $module) { + switch ($module['estado']) { + case '0': + $data_modules[$key]['statusImageHTML'] = 'NORMAL status.'; + break; + case '1': + $data_modules[$key]['statusImageHTML'] = 'CRITICAL status.'; + break; + case '2': + $data_modules[$key]['statusImageHTML'] = 'WARNING status.'; + break; + case '4': + $data_modules[$key]['statusImageHTML'] = 'UNKNOWN status.'; + break; + default: + # code... + break; + } + + $data_modules[$key]['showEventsBtn'] = 1; + $data_modules[$key]['eventModule'] = $module['id_agente_modulo']; + } + } + + hd("MODULESSSS::", true); +hd($data_modules, true); + + $sql = $this->getSecondLevelServicesSql(); + $data_services = db_process_sql($sql); + + + $service_stats = array(); + + foreach ($data_services as $service) { + $service_stats[$service['id']]['id'] = (int)$service['id']; + $service_stats[$service['id']]['name'] = $service['name']; + $service_stats[$service['id']]['alias'] = $service['name']; + if ($service['total_services']+$service['total_agents']+$service['total_modules'] > 0) + $service_stats[$service['id']]['searchChildren'] = 1; + else + $services[$service['id']]['searchChildren'] = 0; + + $service_stats[$service['id']]['rootID'] = $service['rootID']; + $service_stats[$service['id']]['rootType'] = $service['rootType']; + $service_stats[$service['id']]['type'] = 'services'; + $service_stats[$service['id']]['children']=array(); + $service_stats[$service['id']]['serviceDetail']='http://localhost/pandora_console/index.php?sec=network&sec2=enterprise/operation/services/services&tab=service_map&id_service='.(int)$service['id']; + $service_stats[$service['id']]['counters']=array('total_services'=>$service['total_services'], 'total_agents'=>$service['total_agents'], 'total_modules'=>$service['total_modules']); + + } + + $own_info = get_user_info($config['id_user']); + + if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $display_all_services = true; + } else { + $display_all_services = false; + } + + $services = services_get_services($filter, false, $display_all_services); + + foreach ($services as $row) { + + if (!array_key_exists($row['id'], $service_stats)) + continue; + + $status = services_get_status($row, true); + + + switch ($status) { + + case SERVICE_STATUS_NORMAL: + $service_stats[$row['id']]['statusImageHTML']='NORMAL status.'; + break; + + case SERVICE_STATUS_CRITICAL: + $service_stats[$row['id']]['statusImageHTML']='CRITICAL status.'; + break; + + case SERVICE_STATUS_WARNING: + $service_stats[$row['id']][$key]['statusImageHTML']='WARNING status.'; + break; + + case SERVICE_STATUS_UNKNOWN: + default: + $service_stats[$row['id']]['statusImageHTML']='UNKNOWN status.'; + break; + } + } + + $data_services = array_values($service_stats); + + $data = array_merge($data_services, $data_agents, $data_modules); + + if (empty($data)) { + $this->tree = array(); + return; + } + + $this->tree = $data; + } + + protected function getSecondLevelServicesSql() { + $group_acl = $this->getGroupAclCondition(); + + $sql = "SELECT ts.id, ts.name, tse1.id_service AS `rootID`, 'services' AS rootType, 'services' AS type, 0 AS quiet, SUM(if((tse2.id_agent<>0), 1, 0)) AS `total_agents`, SUM(if((tse2.id_agente_modulo<>0), 1, 0)) AS `total_modules`, SUM(if((tse2.id_service_child<>0), 1, 0)) AS `total_services`, 0 AS fired_count, 0 AS normal_count, 0 AS warning_count, 0 AS critical_count, 0 AS unknown_count, 0 AS notinit_count, 0 AS state_critical, 0 AS state_warning, 0 AS state_unknown, 0 AS state_notinit, 0 AS state_normal, 0 AS state_total, '' AS statusImageHTML, '' AS alertImageHTML + FROM tservice_element tse1 + LEFT JOIN tservice_element tse2 ON tse1.id_service_child=tse2.id_service + LEFT JOIN tservice ts ON tse1.id_service_child=ts.id + WHERE tse1.id_service=$this->id AND tse1.id_service_child<>0 + GROUP BY tse1.id_service_child + "; + + return $sql; + } + + + protected function getSecondLevelModulesSql() { + + $sql = "SELECT tse.id_agente_modulo, nombre AS `name`, nombre AS `alias`, tse.id_service AS `rootID`, 'services' AS `rootType`, 'modules' AS `type`, estado + FROM tservice_element tse + INNER JOIN tagente_modulo tam ON tse.id_agente_modulo=tam.id_agente_modulo + INNER JOIN tagente_estado tae ON tam.id_agente_modulo=tae.id_agente_estado + WHERE tse.id_service=$this->id AND tse.id_agente_modulo<>0 + "; + + return $sql; + } + + protected function getAgentStatusFilter ($status = self::TV_DEFAULT_AGENT_STATUS) { + return ''; + } + +} + +?> + diff --git a/pandora_console/include/javascript/tree/TreeController.js b/pandora_console/include/javascript/tree/TreeController.js index e3f7260de4..e22a17ced9 100644 --- a/pandora_console/include/javascript/tree/TreeController.js +++ b/pandora_console/include/javascript/tree/TreeController.js @@ -13,895 +13,991 @@ // GNU General Public License for more details. var TreeController = { - controllers: [], - getController: function() { - var controller = { - index: -1, - recipient: "", - tree: [], - emptyMessage: "No data found.", - foundMessage: "Found groups", - errorMessage: "Error", - baseURL: "", - ajaxURL: "ajax.php", - ajaxPage: "include/ajax/tree.ajax", - detailRecipient: "", - filter: {}, - counterTitles: {}, - shouldHaveCounters: true, - reload: function() { - // Bad recipient - if ( - typeof this.recipient == "undefined" || - this.recipient.length == 0 - ) { - return; - } - - // Load branch - function _processGroup(container, elements, rootGroup) { - var $group = $("
          "); - - // First group - if (typeof rootGroup != "undefinded" && rootGroup == true) { - $group - .addClass("tree-root") - .hide() - .prepend( - '' - ); - } - // Normal group - else { - $group.addClass("tree-group").hide(); - } - - container.append($group); - - _.each(elements, function(element) { - element.jqObject = _processNode($group, element); - }); - - return $group; - } - - // Load leaf counters - function _processNodeCounters(container, counters, type) { - var hasCounters = false; - - if (typeof counters != "undefined") { - function _processNodeCounterTitle( - container, - elementType, - counterType - ) { - var defaultCounterTitles = { - total: { - agents: "Total agents", - modules: "Total modules", - none: "Total" - }, - alerts: { - agents: "Alerts fired", - modules: "Alerts fired", - none: "Alerts fired" - }, - critical: { - agents: "Critical agents", - modules: "Critical modules", - none: "Critical" - }, - warning: { - agents: "Warning agents", - modules: "Warning modules", - none: "Warning" - }, - unknown: { - agents: "Unknown agents", - modules: "Unknown modules", - none: "Unknown" - }, - not_init: { - agents: "Not init agents", - modules: "Not init modules", - none: "Not init" - }, - ok: { - agents: "Normal agents", - modules: "Normal modules", - none: "Normal" - } - }; - - try { - var title = ""; - switch (elementType) { - case "group": - if ( - typeof controller.counterTitles != "undefined" && - typeof controller.counterTitles[counterType] != - "undefined" && - typeof controller.counterTitles[counterType].agents != - "undefined" - ) { - title = controller.counterTitles[counterType].agents; - } else { - title = defaultCounterTitles[counterType].agents; - } - break; - case "agent": - if ( - typeof controller.counterTitles != "undefined" && - typeof controller.counterTitles[counterType] != - "undefined" && - typeof controller.counterTitles[counterType].modules != - "undefined" - ) { - title = controller.counterTitles[counterType].modules; - } else { - title = defaultCounterTitles[counterType].modules; - } - break; - default: - if ( - typeof controller.counterTitles != "undefined" && - typeof controller.counterTitles[counterType] != - "undefined" && - typeof controller.counterTitles[counterType].none != - "undefined" - ) { - title = controller.counterTitles[counterType].none; - } else { - title = defaultCounterTitles[counterType].none; - } - break; - } - if (title.length > 0) { - container - .data("title", title) - .addClass("forced_title") - .data("use_title_for_force_title", 1); // Trick to make easier the 'force title' output - } - } catch (error) { - // console.log(error); - } - } - - var $counters = $("
          "); - $counters.addClass("tree-node-counters"); - - if (typeof counters.total != "undefined" && counters.total >= 0) { - var $totalCounter = $("
          "); - $totalCounter - .addClass("tree-node-counter") - .addClass("total") - .html(counters.total); - - _processNodeCounterTitle($totalCounter, type, "total"); - - // Open the parentheses - $counters.append(" ("); - - $counters.append($totalCounter); - - if ( - typeof counters.alerts != "undefined" && - counters.alerts > 0 - ) { - var $firedCounter = $("
          "); - $firedCounter - .addClass("tree-node-counter") - .addClass("alerts") - .addClass("orange") - .html(counters.alerts); - - _processNodeCounterTitle($firedCounter, type, "alerts"); - - $counters.append(" : ").append($firedCounter); - } - if ( - typeof counters.critical != "undefined" && - counters.critical > 0 - ) { - var $criticalCounter = $("
          "); - $criticalCounter - .addClass("tree-node-counter") - .addClass("critical") - .addClass("red") - .html(counters.critical); - - _processNodeCounterTitle($criticalCounter, type, "critical"); - - $counters.append(" : ").append($criticalCounter); - } - if ( - typeof counters.warning != "undefined" && - counters.warning > 0 - ) { - var $warningCounter = $("
          "); - $warningCounter - .addClass("tree-node-counter") - .addClass("warning") - .addClass("yellow") - .html(counters.warning); - - _processNodeCounterTitle($warningCounter, type, "warning"); - - $counters.append(" : ").append($warningCounter); - } - if ( - typeof counters.unknown != "undefined" && - counters.unknown > 0 - ) { - var $unknownCounter = $("
          "); - $unknownCounter - .addClass("tree-node-counter") - .addClass("unknown") - .addClass("grey") - .html(counters.unknown); - - _processNodeCounterTitle($unknownCounter, type, "unknown"); - - $counters.append(" : ").append($unknownCounter); - } - if ( - typeof counters.not_init != "undefined" && - counters.not_init > 0 - ) { - var $notInitCounter = $("
          "); - $notInitCounter - .addClass("tree-node-counter") - .addClass("not_init") - .addClass("blue") - .html(counters.not_init); - - _processNodeCounterTitle($notInitCounter, type, "not_init"); - - $counters.append(" : ").append($notInitCounter); - } - if (typeof counters.ok != "undefined" && counters.ok > 0) { - var $okCounter = $("
          "); - $okCounter - .addClass("tree-node-counter") - .addClass("ok") - .addClass("green") - .html(counters.ok); - - _processNodeCounterTitle($okCounter, type, "ok"); - - $counters.append(" : ").append($okCounter); - } - - // Close the parentheses - $counters.append(")"); - - hasCounters = true; - } - - // Add the counters html to the container - container.append($counters); - } - - return hasCounters; - } - - // Load leaf - function _processNode(container, element) { - // type, [id], [serverID], callback - function _getTreeDetailData(type, id, serverID, callback) { - var lastParam = arguments[arguments.length - 1]; - var callback; - if (typeof lastParam === "function") callback = lastParam; - - var serverID; - if (arguments.length >= 4) serverID = arguments[2]; - var id; - if (arguments.length >= 3) id = arguments[1]; - var type; - if (arguments.length >= 2) type = arguments[0]; - - if (typeof type === "undefined") - throw new TypeError("Type required"); - if (typeof callback === "undefined") - throw new TypeError("Callback required"); - - var postData = { - page: controller.ajaxPage, - getDetail: 1, - type: type - }; - - if (typeof id !== "undefined") postData.id = id; - if (typeof serverID !== "undefined") postData.serverID = serverID; - - $.ajax({ - url: controller.ajaxURL, - type: "POST", - dataType: "html", - data: postData, - success: function(data, textStatus, xhr) { - callback(null, data); - }, - error: function(xhr, textStatus, errorThrown) { - callback(errorThrown); - } - }); - } - - var $node = $("
        • "); - var $leafIcon = $("
          "); - var $content = $("
          "); - - // Leaf icon - $leafIcon.addClass("leaf-icon"); - - // Content - $content.addClass("node-content"); - switch (element.type) { - case "group": - if ( - typeof element.icon != "undefined" && - element.icon.length > 0 - ) { - $content.append( - ' ' - ); - } else if ( - typeof element.iconHTML != "undefined" && - element.iconHTML.length > 0 - ) { - $content.append(element.iconHTML + " "); - } - $content.append(element.name); - - if (typeof element.edit != "undefined") { - var url_edit = - controller.baseURL + - "index.php?sec=gagente&sec2=godmode/groups/configure_group&tab=tree&id_group=" + - element.id; - var $updateicon = $( - '' - ); - var $updatebtn = $('').append( - $updateicon - ); - $content.append($updatebtn); - } - - if (typeof element.delete != "undefined") { - var url_delete = - controller.baseURL + - "index.php?sec=gagente&sec2=godmode/groups/group_list&tab=tree&delete_group=1&id_group=" + - element.id; - var $deleteBtn = $( - '' - ); - $deleteBtn.click(function(event) { - var ok_function = function() { - window.location.replace(url_delete); - }; - display_confirm_dialog( - element.delete.messages.messg, - element.delete.messages.confirm, - element.delete.messages.cancel, - ok_function - ); - }); - $content.append($deleteBtn); - } - - if (typeof element.alerts != "undefined") { - $content.append(element.alerts); - } - - break; - case "agent": - // Is quiet - if ( - typeof element.quietImageHTML != "undefined" && - element.quietImageHTML.length > 0 - ) { - var $quietImage = $(element.quietImageHTML); - $quietImage.addClass("agent-quiet"); - - $content.append($quietImage); - } - // Status image - if ( - typeof element.statusImageHTML != "undefined" && - element.statusImageHTML.length > 0 - ) { - var $statusImage = $(element.statusImageHTML); - $statusImage.addClass("agent-status"); - - $content.append($statusImage); - } - // Alerts fired image - if ( - typeof element.alertImageHTML != "undefined" && - element.alertImageHTML.length > 0 - ) { - var $alertImage = $(element.alertImageHTML); - $alertImage.addClass("agent-alerts-fired"); - - $content.append($alertImage); - } - $content.append(element.alias); - break; - case "module": - // Status image - if ( - typeof element.statusImageHTML != "undefined" && - element.statusImageHTML.length > 0 - ) { - var $statusImage = $(element.statusImageHTML); - $statusImage.addClass("module-status"); - - $content.append($statusImage); - } - // Server type - if ( - typeof element.serverTypeHTML != "undefined" && - element.serverTypeHTML.length > 0 && - element.serverTypeHTML != "--" - ) { - var $serverTypeImage = $(element.serverTypeHTML); - $serverTypeImage.addClass("module-server-type"); - - $content.append($serverTypeImage); - } - - if ( - typeof element.showGraphs != "undefined" && - element.showGraphs != 0 - ) { - // Graph pop-up - if (typeof element.moduleGraph != "undefined") { - if (element.statusImageHTML.indexOf("data:image") != -1) { - var $graphImage = $( - ' ' - ); - } else { - var $graphImage = $( - ' ' - ); - } - - $graphImage.addClass("module-graph").click(function(e) { - e.preventDefault(); - if (element.statusImageHTML.indexOf("data:image") != -1) { - try { - winopeng_var( - decodeURI(element.snapshot[0]), - element.snapshot[1], - element.snapshot[2], - element.snapshot[3] - ); - } catch (error) { - // console.log(error); - } - } else { - try { - winopeng( - element.moduleGraph.url, - element.moduleGraph.handle - ); - } catch (error) { - // console.log(error); - } - } - }); - - $content.append($graphImage); - } - - // Data pop-up - if (typeof element.id != "undefined" && !isNaN(element.id)) { - var $dataImage = $( - ' ' - ); - $dataImage.addClass("module-data").click(function(e) { - e.preventDefault(); - - try { - var serverName = - element.serverName.length > 0 ? element.serverName : ""; - if ($("#module_details_window").length > 0) - show_module_detail_dialog( - element.id, - "", - serverName, - 0, - 86400, - element.name.replace(/ /g, " ") - ); - } catch (error) { - // console.log(error); - } - }); - - $content.append($dataImage); - } - } - - // Alerts - if ( - typeof element.alertsImageHTML != "undefined" && - element.alertsImageHTML.length > 0 - ) { - var $alertsImage = $(element.alertsImageHTML); - - $alertsImage - .addClass("module-alerts") - .click(function(e) { - _getTreeDetailData( - "alert", - element.id, - element.serverID, - function(error, data) { - if (error) { - // console.error(error); - } else { - controller.detailRecipient - .render(element.name, data) - .open(); - } - } - ); - - // Avoid the execution of the module detail event - e.stopPropagation(); - }) - .css("cursor", "pointer"); - - $content.append($alertsImage); - } - - $content.append(element.name); - break; - case "os": - if ( - typeof element.icon != "undefined" && - element.icon.length > 0 - ) { - $content.append( - ' ' - ); - } - $content.append(element.name); - break; - case "tag": - if ( - typeof element.icon != "undefined" && - element.icon.length > 0 - ) { - $content.append( - ' ' - ); - } else { - $content.append( - ' ' - ); - } - $content.append(element.name); - break; - default: - $content.append(element.name); - break; - } - - // Load the status counters - var hasCounters = _processNodeCounters( - $content, - element.counters, - element.type - ); - //Don't show empty groups - if (element.type == "agent") { - if (!hasCounters) { - return; - } - } - // If exist the detail container, show the data - if (typeof controller.detailRecipient !== "undefined") { - if (element.type == "agent" || element.type == "module") { - $content - .click(function(e) { - _getTreeDetailData( - element.type, - element.id, - element.serverID, - function(error, data) { - if (error) { - // console.error(error); - } else { - controller.detailRecipient - .render(element.name, data) - .open(); - } - } - ); - }) - .css("cursor", "pointer"); - } - } - - $node - .addClass("tree-node") - .append($leafIcon) - .append($content); - - container.append($node); - - $node.addClass("leaf-empty"); - - if ( - typeof element.children != "undefined" && - element.children.length > 0 - ) { - $node.removeClass("leaf-empty").addClass("leaf-closed"); - - // Add children - var $children = _processGroup($node, element.children); - $node.data("children", $children); - - if ( - typeof element.searchChildren == "undefined" || - !element.searchChildren - ) { - $leafIcon.click(function(e) { - e.preventDefault(); - - if ($node.hasClass("leaf-open")) { - $node - .removeClass("leaf-open") - .addClass("leaf-closed") - .data("children") - .slideUp(); - } else { - $node - .removeClass("leaf-closed") - .addClass("leaf-open") - .data("children") - .slideDown(); - } - }); - } - } - // Get hash and user. - var public_hash = $("#hidden-publi_dash_tree_view_hash").val(); - if (typeof public_hash === "undefined") public_hash = 0; - var public_user = $("#hidden-publi_dash_tree_view_id_user").val(); - if (typeof public_user === "undefined") public_user = 0; - - if ( - typeof element.searchChildren != "undefined" && - element.searchChildren - ) { - if ( - element.rootType == "group_edition" && - typeof element.children == "undefined" - ) { - $node.addClass("leaf-empty"); - } else { - $node.removeClass("leaf-empty").addClass("leaf-closed"); - $leafIcon.click(function(e) { - e.preventDefault(); - - if ( - !$node.hasClass("leaf-loading") && - !$node.hasClass("children-loaded") && - !$node.hasClass("leaf-empty") - ) { - $node - .removeClass("leaf-closed") - .removeClass("leaf-error") - .addClass("leaf-loading"); - - $.ajax({ - url: controller.ajaxURL, - type: "POST", - dataType: "json", - data: { - page: controller.ajaxPage, - getChildren: 1, - id: element.id, - type: element.type, - rootID: element.rootID, - serverID: element.serverID, - rootType: element.rootType, - filter: controller.filter, - hash: public_hash, - id_user: public_user - }, - complete: function(xhr, textStatus) { - $node.removeClass("leaf-loading"); - $node.addClass("children-loaded"); - }, - success: function(data, textStatus, xhr) { - if (data.success) { - var $group = $node.children("ul.tree-group"); - if ( - (typeof data.tree != "undefined" && - data.tree.length > 0) || - $group.length > 0 - ) { - $node.addClass("leaf-open"); - - if ($group.length <= 0) { - $group = $("
            "); - $group.addClass("tree-group").hide(); - $node.append($group); - } - - _.each(data.tree, function(element) { - element.jqObject = _processNode($group, element); - }); - - $group.slideDown(); - - $node.data("children", $group); - - // Add again the hover event to the 'force_callback' elements - forced_title_callback(); - } else { - $node.addClass("leaf-empty"); - } - } else { - $node.addClass("leaf-error"); - } - }, - error: function(xhr, textStatus, errorThrown) { - $node.addClass("leaf-error"); - } - }); - } else if (!$node.hasClass("leaf-empty")) { - if ($node.hasClass("leaf-open")) { - $node - .removeClass("leaf-open") - .addClass("leaf-closed") - .data("children") - .slideUp(); - } else { - $node - .removeClass("leaf-closed") - .addClass("leaf-open") - .data("children") - .slideDown(); - } - } - }); - } - } - - return $node; - } - - if (controller.recipient.length == 0) { - return; - } else if (controller.tree.length == 0) { - controller.recipient.empty(); - controller.recipient.html( - "
            " + controller.emptyMessage + "
            " - ); - return; - } - - controller.recipient.empty(); - controller.recipient.html( - "
            " + - controller.foundMessage + - ": " + - controller.tree.length + - "
            " + - "
            " - ); - - var $children = _processGroup(this.recipient, this.tree, true); - $children.show(); - - controller.recipient.data("children", $children); - - // Add again the hover event to the 'force_callback' elements - forced_title_callback(); - }, - load: function() { - this.reload(); - }, - changeTree: function(tree) { - this.tree = tree; - this.reload(); - }, - init: function(data) { - if ( - typeof data.recipient !== "undefined" && - data.recipient.length > 0 - ) { - this.recipient = data.recipient; - } - if (typeof data.detailRecipient !== "undefined") { - this.detailRecipient = data.detailRecipient; - } - if (typeof data.tree !== "undefined") { - this.tree = data.tree; - } - if ( - typeof data.emptyMessage !== "undefined" && - data.emptyMessage.length > 0 - ) { - this.emptyMessage = data.emptyMessage; - } - if ( - typeof data.foundMessage !== "undefined" && - data.foundMessage.length > 0 - ) { - this.foundMessage = data.foundMessage; - } - if ( - typeof data.errorMessage !== "undefined" && - data.errorMessage.length > 0 - ) { - this.errorMessage = data.errorMessage; - } - if (typeof data.baseURL !== "undefined" && data.baseURL.length > 0) { - this.baseURL = data.baseURL; - } - if (typeof data.ajaxURL !== "undefined" && data.ajaxURL.length > 0) { - this.ajaxURL = data.ajaxURL; - } - if (typeof data.ajaxPage !== "undefined" && data.ajaxPage.length > 0) { - this.ajaxPage = data.ajaxPage; - } - if (typeof data.filter !== "undefined") { - this.filter = data.filter; - } - - this.load(); - }, - remove: function() { - if (typeof this.recipient != "undefined" && this.recipient.length > 0) { - this.recipient.empty(); - } - - if (this.index > -1) { - TreeController.controllers.splice(this.index, 1); - } - } - }; - controller.index = TreeController.controllers.push(controller) - 1; - - return controller; - } -}; + controllers: [], + getController: function () { + var controller = { + index: -1, + recipient: '', + tree: [], + emptyMessage: "No data found.", + foundMessage: "Found groups", + errorMessage: "Error", + baseURL: "", + ajaxURL: "ajax.php", + ajaxPage: "include/ajax/tree.ajax", + detailRecipient: '', + filter: {}, + counterTitles: {}, + shouldHaveCounters: true, + reload: function () { + // Bad recipient + if (typeof this.recipient == 'undefined' || this.recipient.length == 0) { + return; + } + + // Load branch + function _processGroup (container, elements, rootGroup) { + + var $group = $("
              "); + + // First group + if (typeof rootGroup != 'undefinded' && rootGroup == true) { + $group + .addClass("tree-root") + .hide() + .prepend(''); + } + // Normal group + else { + $group + .addClass("tree-group") + .hide(); + } + + container.append($group); + + _.each(elements, function(element) { + element.jqObject = _processNode($group, element); + }); + + return $group; + } + + // Load leaf counters + function _processNodeCounters (container, counters, type) { + var hasCounters = false; + + if (typeof counters != 'undefined') { + + function _processNodeCounterTitle (container, elementType, counterType) { + + var defaultCounterTitles = { + total: { + agents: "Total agents", + modules: "Total modules", + none: "Total" + }, + alerts: { + agents: "Alerts fired", + modules: "Alerts fired", + none: "Alerts fired" + }, + critical: { + agents: "Critical agents", + modules: "Critical modules", + none: "Critical" + }, + warning: { + agents: "Warning agents", + modules: "Warning modules", + none: "Warning" + }, + unknown: { + agents: "Unknown agents", + modules: "Unknown modules", + none: "Unknown" + }, + not_init: { + agents: "Not init agents", + modules: "Not init modules", + none: "Not init" + }, + ok: { + agents: "Normal agents", + modules: "Normal modules", + none: "Normal" + } + } + + var serviceCounterTitles = { + total_services: { + totals: "Services" + }, + total_agents: { + totals: "Agents" + }, + total_modules: { + totals: "Modules" + } + } + + try { + + var title = ''; + + switch (elementType) { + case "group": + if (typeof controller.counterTitles != 'undefined' + && typeof controller.counterTitles[counterType] != 'undefined' + && typeof controller.counterTitles[counterType].agents != 'undefined') { + title = controller.counterTitles[counterType].agents; + } + else { + title = defaultCounterTitles[counterType].agents; + } + break; + case "agent": + if (typeof controller.counterTitles != 'undefined' + && typeof controller.counterTitles[counterType] != 'undefined' + && typeof controller.counterTitles[counterType].modules != 'undefined') { + title = controller.counterTitles[counterType].modules; + } + else { + title = defaultCounterTitles[counterType].modules; + } + break; + case "services": + title = serviceCounterTitles[counterType].totals; + break; + default: + if (typeof controller.counterTitles != 'undefined' + && typeof controller.counterTitles[counterType] != 'undefined' + && typeof controller.counterTitles[counterType].none != 'undefined') { + title = controller.counterTitles[counterType].none; + } + else { + title = defaultCounterTitles[counterType].none; + } + break; + } + if (title.length > 0) { + container + .data("title", title) + .addClass("forced_title") + .data("use_title_for_force_title", 1); // Trick to make easier the 'force title' output + } + } + catch (error) { + // console.log(error); + } + } + + + if (type=="services") { + + var $counters = $("
              "); + $counters.addClass('tree-node-counters'); + + if (counters.total_services+counters.total_agents+counters.total_modules > 0) { + + // Open the parentheses + $counters.append(" ("); + + if (typeof counters.total_services != 'undefined' + && counters.total_services >= 0) { + + var $servicesCounter = $("
              "); + $servicesCounter + .addClass('tree-node-counter') + .addClass('total') + .html(counters.total_services); + + _processNodeCounterTitle($servicesCounter, type, "total_services"); + + $counters + .append($servicesCounter); + } else { + var $servicesCounter = $("
              "); + $servicesCounter + .addClass('tree-node-counter') + .addClass('total') + .html('0'); + + _processNodeCounterTitle($servicesCounter, type, "total_services"); + + $counters + .append($servicesCounter); + } + + if (typeof counters.total_agents != 'undefined' + && counters.total_agents > 0) { + var $agentsCounter = $("
              "); + $agentsCounter + .addClass('tree-node-counter') + .html(counters.total_agents); + + _processNodeCounterTitle($agentsCounter, type, "total_agents"); + + $counters + .append(" : ") + .append($agentsCounter); + } else { + var $agentsCounter = $("
              "); + $agentsCounter + .addClass('tree-node-counter') + .addClass('total') + .html('0'); + + _processNodeCounterTitle($agentsCounter, type, "total_agents"); + + $counters + .append(" : ") + .append($agentsCounter); + } + + if (typeof counters.total_modules != 'undefined' + && counters.total_modules > 0) { + var $modulesCounter = $("
              "); + $modulesCounter + .addClass('tree-node-counter') + .addClass('total') + .html(counters.total_modules); + + _processNodeCounterTitle($modulesCounter, type, "total_modules"); + + $counters + .append(" : ") + .append($modulesCounter); + } else { + var $modulesCounter = $("
              "); + $modulesCounter + .addClass('tree-node-counter') + .addClass('total') + .html('0'); + + _processNodeCounterTitle($modulesCounter, type, "total_modules"); + + $counters + .append(" : ") + .append($modulesCounter); + } + + // Close the parentheses + $counters.append(")"); + + hasCounters = true; + } + } else { + + var $counters = $("
              "); + $counters.addClass('tree-node-counters'); + + if (typeof counters.total != 'undefined' + && counters.total >= 0) { + + var $totalCounter = $("
              "); + $totalCounter + .addClass('tree-node-counter') + .addClass('total') + .html(counters.total); + + _processNodeCounterTitle($totalCounter, type, "total"); + + // Open the parentheses + $counters.append(" ("); + + $counters.append($totalCounter); + + if (typeof counters.alerts != 'undefined' + && counters.alerts > 0) { + var $firedCounter = $("
              "); + $firedCounter + .addClass('tree-node-counter') + .addClass('alerts') + .addClass('orange') + .html(counters.alerts); + + _processNodeCounterTitle($firedCounter, type, "alerts"); + + $counters + .append(" : ") + .append($firedCounter); + } + if (typeof counters.critical != 'undefined' + && counters.critical > 0) { + var $criticalCounter = $("
              "); + $criticalCounter + .addClass('tree-node-counter') + .addClass('critical') + .addClass('red') + .html(counters.critical); + + _processNodeCounterTitle($criticalCounter, type, "critical"); + + $counters + .append(" : ") + .append($criticalCounter); + } + if (typeof counters.warning != 'undefined' + && counters.warning > 0) { + var $warningCounter = $("
              "); + $warningCounter + .addClass('tree-node-counter') + .addClass('warning') + .addClass('yellow') + .html(counters.warning); + + _processNodeCounterTitle($warningCounter, type, "warning"); + + $counters + .append(" : ") + .append($warningCounter); + } + if (typeof counters.unknown != 'undefined' + && counters.unknown > 0) { + var $unknownCounter = $("
              "); + $unknownCounter + .addClass('tree-node-counter') + .addClass('unknown') + .addClass('grey') + .html(counters.unknown); + + _processNodeCounterTitle($unknownCounter, type, "unknown"); + + $counters + .append(" : ") + .append($unknownCounter); + } + if (typeof counters.not_init != 'undefined' + && counters.not_init > 0) { + var $notInitCounter = $("
              "); + $notInitCounter + .addClass('tree-node-counter') + .addClass('not_init') + .addClass('blue') + .html(counters.not_init); + + _processNodeCounterTitle($notInitCounter, type, "not_init"); + + $counters + .append(" : ") + .append($notInitCounter); + } + if (typeof counters.ok != 'undefined' + && counters.ok > 0) { + var $okCounter = $("
              "); + $okCounter + .addClass('tree-node-counter') + .addClass('ok') + .addClass('green') + .html(counters.ok); + + _processNodeCounterTitle($okCounter, type, "ok"); + + $counters + .append(" : ") + .append($okCounter); + } + } + + // Close the parentheses + $counters.append(")"); + + hasCounters = true; + } + + // Add the counters html to the container + container.append($counters); + } + + return hasCounters; + } + + // Load leaf + function _processNode (container, element) { + // type, [id], [serverID], callback + function _getTreeDetailData (type, id, serverID, callback) { + var lastParam = arguments[arguments.length - 1]; + var callback; + if (typeof lastParam === 'function') + callback = lastParam; + + var serverID; + if (arguments.length >= 4) + serverID = arguments[2]; + var id; + if (arguments.length >= 3) + id = arguments[1]; + var type; + if (arguments.length >= 2) + type = arguments[0]; + + if (typeof type === 'undefined') + throw new TypeError('Type required'); + if (typeof callback === 'undefined') + throw new TypeError('Callback required'); + + var postData = { + page: controller.ajaxPage, + getDetail: 1, + type: type + } + + if (typeof id !== 'undefined') + postData.id = id; + if (typeof serverID !== 'undefined') + postData.serverID = serverID; + + $.ajax({ + url: controller.ajaxURL, + type: 'POST', + dataType: 'html', + data: postData, + success: function(data, textStatus, xhr) { + callback(null, data); + }, + error: function(xhr, textStatus, errorThrown) { + callback(errorThrown); + } + }); + } + + var $node = $("
            • "); + var $leafIcon = $("
              "); + var $content = $("
              "); + + // Leaf icon + $leafIcon.addClass("leaf-icon"); + + // Content + $content.addClass("node-content"); + switch (element.type) { + case 'group': + if (typeof element.icon != 'undefined' && element.icon.length > 0) { + $content.append(' '); + } + else if (typeof element.iconHTML != 'undefined' && element.iconHTML.length > 0) { + $content.append(element.iconHTML + " "); + } + $content.append(element.name); + + if(typeof element.edit != 'undefined'){ + var url_edit = controller.baseURL + "index.php?sec=gagente&sec2=godmode/groups/configure_group&tab=tree&id_group=" + element.id; + var $updateicon = $('') + var $updatebtn = $('') + .append($updateicon); + $content.append($updatebtn); + } + + if(typeof element.delete != 'undefined'){ + var url_delete = controller.baseURL + "index.php?sec=gagente&sec2=godmode/groups/group_list&tab=tree&delete_group=1&id_group=" + element.id; + var $deleteBtn = $(''); + $deleteBtn.click(function (event){ + var ok_function = function(){ + window.location.replace(url_delete); + }; + display_confirm_dialog( + element.delete.messages.messg, + element.delete.messages.confirm, + element.delete.messages.cancel, + ok_function + ) + }); + $content.append($deleteBtn); + } + + if(typeof element.alerts != 'undefined'){ + $content.append(element.alerts); + } + + break; + case 'agent': + // Is quiet + if (typeof element.quietImageHTML != 'undefined' + && element.quietImageHTML.length > 0) { + var $quietImage = $(element.quietImageHTML); + $quietImage.addClass("agent-quiet"); + + $content.append($quietImage); + } + // Status image + if (typeof element.statusImageHTML != 'undefined' + && element.statusImageHTML.length > 0) { + var $statusImage = $(element.statusImageHTML); + $statusImage.addClass("agent-status"); + + $content.append($statusImage); + } + // Alerts fired image + if (typeof element.alertImageHTML != 'undefined' + && element.alertImageHTML.length > 0) { + var $alertImage = $(element.alertImageHTML); + $alertImage.addClass("agent-alerts-fired"); + + $content.append($alertImage); + } + + // Events by agent + if (element.showEventsBtn == 1) { + if (typeof element.eventAgent != 'undefined') { + + $content.append(''); + var $eventImage = $(''); + $eventImage.addClass("agent-alerts-fired"); + $eventImage + .click(function (e) { + e.preventDefault(); + + document.getElementById('hiddenAgentsEventsForm-'+element.eventAgent).submit(); + }) + .css('cursor', 'pointer'); + + $content.append($eventImage); + } + } + + $content.append(' '+element.alias); + break; + case 'services': + + if (typeof element.statusImageHTML != 'undefined' + && element.statusImageHTML.length > 0) { + var $statusImage = $(element.statusImageHTML); + $statusImage.addClass("agent-status"); + + $content.append($statusImage); + } + + + var $serviceDetailImage = $(''); + + if (typeof element.serviceDetail != 'undefined') { + + $serviceDetailImage + .click(function (e) { + e.preventDefault(); + + window.location.href = element.serviceDetail; + }) + .css('cursor', 'pointer'); + + $content.append($serviceDetailImage); + } + + $content.append(' '+element.name); + + + + + break; + case 'modules': + if (typeof element.statusImageHTML != 'undefined' + && element.statusImageHTML.length > 0) { + var $statusImage = $(element.statusImageHTML); + $statusImage.addClass("agent-status"); + + $content.append($statusImage); + } + + // Events by module + if (element.showEventsBtn == 1) { + if (typeof element.eventModule != 'undefined') { + + $content.append(''); + var $moduleImage = $(''); + $moduleImage + .click(function (e) { + e.preventDefault(); + + document.getElementById('hiddenModulesEventsForm-'+element.eventModule).submit(); + }) + .css('cursor', 'pointer'); + + $content.append($moduleImage); + } + } + + $content.append(' '+element.name); + break; + case 'module': + // Status image + if (typeof element.statusImageHTML != 'undefined' + && element.statusImageHTML.length > 0) { + var $statusImage = $(element.statusImageHTML); + $statusImage.addClass("module-status"); + + $content.append($statusImage); + } + // Server type + if (typeof element.serverTypeHTML != 'undefined' + && element.serverTypeHTML.length > 0 + && element.serverTypeHTML != '--') { + var $serverTypeImage = $(element.serverTypeHTML); + $serverTypeImage.addClass("module-server-type"); + + $content.append($serverTypeImage); + } + + if (typeof element.showGraphs != 'undefined' && element.showGraphs != 0) { + // Graph pop-up + if (typeof element.moduleGraph != 'undefined') { + + if(element.statusImageHTML.indexOf('data:image')!=-1){ + var $graphImage = $(' '); + } + else{ + + var $graphImage = $(' '); + } + + $graphImage + .addClass('module-graph') + .click(function (e) { + e.preventDefault(); + if(element.statusImageHTML.indexOf('data:image')!=-1){ + try { + winopeng_var( + decodeURI(element.snapshot[0]), + element.snapshot[1], + element.snapshot[2], + element.snapshot[3] + ); + } + catch (error) { + // console.log(error); + } + } + else{ + try { + winopeng(element.moduleGraph.url, element.moduleGraph.handle); + } + catch (error) { + // console.log(error); + } + } + }); + + $content.append($graphImage); + } + + // Data pop-up + if (typeof element.id != 'undefined' && !isNaN(element.id)) { + + var $dataImage = $(' '); + $dataImage + .addClass('module-data') + .click(function (e) { + e.preventDefault(); + + try { + var serverName = element.serverName.length > 0 ? element.serverName : ''; + if ($("#module_details_window").length > 0) + show_module_detail_dialog(element.id, '', serverName, 0, 86400, element.name.replace(/ /g , " ") ); + } + catch (error) { + // console.log(error); + } + }); + + $content.append($dataImage); + } + } + + // Alerts + if (typeof element.alertsImageHTML != 'undefined' + && element.alertsImageHTML.length > 0) { + + var $alertsImage = $(element.alertsImageHTML); + + $alertsImage + .addClass("module-alerts") + .click(function (e) { + _getTreeDetailData('alert', element.id, element.serverID, function (error, data) { + if (error) { + // console.error(error); + } + else { + controller.detailRecipient.render(element.name, data).open(); + } + }); + + // Avoid the execution of the module detail event + e.stopPropagation(); + }) + .css('cursor', 'pointer'); + + $content.append($alertsImage); + } + + $content.append(element.name); + break; + case 'os': + if (typeof element.icon != 'undefined' && element.icon.length > 0) { + $content.append(' '); + } + $content.append(element.name); + break; + case 'tag': + if (typeof element.icon != 'undefined' && element.icon.length > 0) { + $content.append(' '); + } + else { + $content.append(' '); + } + $content.append(element.name); + break; + case 'services': + // Status image + if (typeof element.statusImageHTML != 'undefined' + && element.statusImageHTML.length > 0) { + var $statusImage = $(element.statusImageHTML); + $statusImage.addClass("agent-status"); + + $content.append($statusImage); + } + $content.append(element.name); + break; + default: + $content.append(element.name); + break; + } + + // Load the status counters + console.log(element.counters); + var hasCounters = _processNodeCounters($content, element.counters, element.type); + //Don't show empty groups + if (element.type == 'agent') { + if (!hasCounters) { + return; + } + } + // If exist the detail container, show the data + if (typeof controller.detailRecipient !== 'undefined') { + if (element.type == 'agent' || element.type == 'module') { + $content.click(function (e) { + _getTreeDetailData(element.type, element.id, element.serverID, function (error, data) { + if (error) { + // console.error(error); + } + else { + controller.detailRecipient.render(element.name, data).open(); + } + }); + }) + .css('cursor', 'pointer'); + } + } + + $node + .addClass("tree-node") + .append($leafIcon) + .append($content); + + container.append($node); + + $node.addClass("leaf-empty"); + + if (typeof element.children != 'undefined' && element.children.length > 0) { + $node + .removeClass("leaf-empty") + .addClass("leaf-closed"); + + // Add children + var $children = _processGroup($node, element.children); + $node.data('children', $children); + + if (typeof element.searchChildren == 'undefined' || !element.searchChildren) { + $leafIcon.click(function (e) { + e.preventDefault(); + + if ($node.hasClass("leaf-open")) { + $node + .removeClass("leaf-open") + .addClass("leaf-closed") + .data('children') + .slideUp(); + } + else { + $node + .removeClass("leaf-closed") + .addClass("leaf-open") + .data('children') + .slideDown(); + } + }); + } + } + // Get hash and user. + var public_hash = $("#hidden-publi_dash_tree_view_hash" ).val(); + if (typeof(public_hash) === 'undefined') public_hash = 0; + var public_user = $("#hidden-publi_dash_tree_view_id_user" ).val(); + if (typeof(public_user) === 'undefined') public_user = 0; + + if (typeof element.searchChildren != 'undefined' && element.searchChildren) { + if(element.rootType == "group_edition" + && typeof element.children == 'undefined'){ + $node.addClass("leaf-empty"); + } + else{ + $node + .removeClass("leaf-empty") + .addClass("leaf-closed"); + $leafIcon.click(function (e) { + e.preventDefault(); + + if (!$node.hasClass("leaf-loading") && !$node.hasClass("children-loaded") && !$node.hasClass("leaf-empty")) { + $node + .removeClass("leaf-closed") + .removeClass("leaf-error") + .addClass("leaf-loading"); + + $.ajax({ + url: controller.ajaxURL, + type: 'POST', + dataType: 'json', + data: { + page: controller.ajaxPage, + getChildren: 1, + id: element.id, + type: element.type, + rootID: element.rootID, + serverID: element.serverID, + rootType: element.rootType, + filter: controller.filter, + hash: public_hash, + id_user: public_user + }, + complete: function(xhr, textStatus) { + $node.removeClass("leaf-loading"); + $node.addClass("children-loaded"); + }, + success: function(data, textStatus, xhr) { + if (data.success) { + var $group = $node.children("ul.tree-group"); + if ((typeof data.tree != 'undefined' && data.tree.length > 0) || $group.length > 0) { + $node.addClass("leaf-open"); + + if ($group.length <= 0) { + $group = $("
                "); + $group + .addClass("tree-group") + .hide(); + $node.append($group); + } + //console.log(data.tree); + + _.each(data.tree, function(element) { + element.jqObject = _processNode($group, element); + }); + + $group.slideDown(); + + $node.data('children', $group); + + // Add again the hover event to the 'force_callback' elements + forced_title_callback(); + } + else { + $node.addClass("leaf-empty"); + } + } + else { + $node.addClass("leaf-error"); + } + }, + error: function(xhr, textStatus, errorThrown) { + $node.addClass("leaf-error"); + } + }); + } + else if (! $node.hasClass("leaf-empty")) { + if ($node.hasClass("leaf-open")) { + $node + .removeClass("leaf-open") + .addClass("leaf-closed") + .data('children') + .slideUp(); + } + else { + $node + .removeClass("leaf-closed") + .addClass("leaf-open") + .data('children') + .slideDown(); + } + } + }); + } + } + + return $node; + } + + if (controller.recipient.length == 0) { + return; + } + else if (controller.tree.length == 0) { + controller.recipient.empty(); + controller.recipient.html("
                " + controller.emptyMessage + "
                "); + return; + } + + controller.recipient.empty(); + controller.recipient.html( + "
                " + + controller.foundMessage + ": " + controller.tree.length + + "
                " + + "
                " + ); + + var $children = _processGroup(this.recipient, this.tree, true); + $children.show(); + + controller.recipient.data('children', $children); + + // Add again the hover event to the 'force_callback' elements + forced_title_callback(); + }, + load: function () { + this.reload(); + }, + changeTree: function (tree) { + this.tree = tree; + this.reload(); + }, + init: function (data) { + if (typeof data.recipient !== 'undefined' && data.recipient.length > 0) { + this.recipient = data.recipient; + } + if (typeof data.detailRecipient !== 'undefined') { + this.detailRecipient = data.detailRecipient; + } + if (typeof data.tree !== 'undefined') { + this.tree = data.tree; + } + if (typeof data.emptyMessage !== 'undefined' && data.emptyMessage.length > 0) { + this.emptyMessage = data.emptyMessage; + } + if (typeof data.foundMessage !== 'undefined' && data.foundMessage.length > 0) { + this.foundMessage = data.foundMessage; + } + if (typeof data.errorMessage !== 'undefined' && data.errorMessage.length > 0) { + this.errorMessage = data.errorMessage; + } + if (typeof data.baseURL !== 'undefined' && data.baseURL.length > 0) { + this.baseURL = data.baseURL; + } + if (typeof data.ajaxURL !== 'undefined' && data.ajaxURL.length > 0) { + this.ajaxURL = data.ajaxURL; + } + if (typeof data.ajaxPage !== 'undefined' && data.ajaxPage.length > 0) { + this.ajaxPage = data.ajaxPage; + } + if (typeof data.filter !== 'undefined') { + this.filter = data.filter; + } + + this.load(); + }, + remove: function () { + if (typeof this.recipient != 'undefined' && this.recipient.length > 0) { + this.recipient.empty(); + } + + if (this.index > -1) { + TreeController.controllers.splice(this.index, 1); + } + } + } + controller.index = TreeController.controllers.push(controller) - 1; + + return controller; + } +} diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 70a9c4920e..180c187db0 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -21,8 +21,8 @@ Description: The default Pandora FMS theme layout */ /* Tree view styles */ -/*@import url(tree.css); -@import url(fixed-bottom-box.css);*/ +@import url(tree.css); +@import url(fixed-bottom-box.css); /* * --------------------------------------------------------------------- diff --git a/pandora_console/operation/events/events.php b/pandora_console/operation/events/events.php index 18e1e77ffc..5dc7caea1b 100644 --- a/pandora_console/operation/events/events.php +++ b/pandora_console/operation/events/events.php @@ -314,6 +314,7 @@ if ($id_agent != 0) { $text_module = (string) get_parameter('module_search', ''); $id_agent_module = get_parameter('module_search_hidden', get_parameter('id_agent_module', 0)); +hd("------------------------------------>>>>>>> ".$id_agent_module." y id_agent: ".$id_agent, true); if ($id_agent_module != 0) { $text_module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $id_agent_module); if ($text_module == false) { diff --git a/pandora_console/operation/tree.php b/pandora_console/operation/tree.php index fde9586325..3491f71458 100755 --- a/pandora_console/operation/tree.php +++ b/pandora_console/operation/tree.php @@ -278,226 +278,228 @@ enterprise_hook('close_meta_frame'); From 1feebae56497953b994017ab4684ce7ec610e8a7 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 22 Feb 2019 13:33:46 +0100 Subject: [PATCH 224/249] removed fullurl supervisor Former-commit-id: 74cc731977477c444150d49aff9ab062ddac065a --- .../include/class/ConsoleSupervisor.php | 118 +++++------------- 1 file changed, 33 insertions(+), 85 deletions(-) diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index 4873186d62..c0a91480cc 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -637,9 +637,7 @@ class ConsoleSupervisor 'Your license is going to expire in %d days. Please contact sales.', $days_to_expiry ), - 'url' => ui_get_full_url( - 'index.php?sec=gsetup&sec2=godmode/setup/license' - ), + 'url' => 'index.php?sec=gsetup&sec2=godmode/setup/license', ] ); } else if ($days_to_expiry < 0) { @@ -649,9 +647,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.LICENSE.EXPIRATION', 'title' => __('License is expired.'), 'message' => __('Your license has expired. Please contact sales.'), - 'url' => ui_get_full_url( - 'index.php?sec=gsetup&sec2=godmode/setup/license' - ), + 'url' => 'index.php?sec=gsetup&sec2=godmode/setup/license', ] ); return false; @@ -728,9 +724,7 @@ class ConsoleSupervisor 'Directory %s is not writable. Please configure proper permissions.', $config['attachment_store'] ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=general', ] ); return; @@ -752,9 +746,7 @@ class ConsoleSupervisor 'There are more than %d files in attachment, you should consider cleaning up your attachment directory manually.', $config['num_files_attachment'] ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf', ] ); } else { @@ -786,9 +778,7 @@ class ConsoleSupervisor 'Remote configuration directory %s is not readable. Please configure it.', $config['remote_config'] ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=general', ] ); return; @@ -807,9 +797,7 @@ class ConsoleSupervisor 'Remote configuration directory %s is not writable. Please configure it.', $config['remote_config'].'/conf' ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=general', ] ); } else { @@ -827,9 +815,7 @@ class ConsoleSupervisor 'Collections directory %s is not writable. Please configure it.', $config['remote_config'].'/collections' ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=general', ] ); } else { @@ -847,9 +833,7 @@ class ConsoleSupervisor 'MD5 directory %s is not writable. Please configure it.', $config['remote_config'].'/md5' ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=general' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=general', ] ); } else { @@ -880,9 +864,7 @@ class ConsoleSupervisor $MAX_FILES_DATA_IN, $config['remote_config'] ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf', ] ); } else { @@ -905,9 +887,7 @@ class ConsoleSupervisor $MAX_BADXML_FILES_DATA_IN, $config['remote_config'] ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf', ] ); } else { @@ -984,9 +964,7 @@ class ConsoleSupervisor $modules_queued, $queue['queued_modules'] ), - 'url' => ui_get_full_url( - 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60' - ), + 'url' => 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60', ] ); } else { @@ -1088,9 +1066,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.SERVER.STATUS.'.$server['id_server'], 'title' => $msg, 'message' => $description, - 'url' => ui_get_full_url( - 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60' - ), + 'url' => 'index.php?sec=gservers&sec2=godmode/servers/modificar_server&refr=60', ] ); } @@ -1176,7 +1152,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.PHP.SAFE_MODE', 'title' => __('PHP safe mode is enabled. Some features may not properly work.'), 'message' => __('To disable, change it on your PHP configuration file (php.ini) and put safe_mode = Off (Dont forget restart apache process after changes)'), - 'url' => ui_get_full_url('index.php'), + 'url' => 'index.php', ] ); } else { @@ -1195,7 +1171,7 @@ class ConsoleSupervisor __('Recommended value is %s'), '-1 ('.__('Unlimited').')' ).'

                '.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), - 'url' => ui_get_full_url('index.php'), + 'url' => 'index.php', ] ); } else { @@ -1214,7 +1190,7 @@ class ConsoleSupervisor __('Recommended value is: %s'), '0 ('.__('Unlimited').')' ).'

                '.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), - 'url' => ui_get_full_url('index.php'), + 'url' => 'index.php', ] ); } else { @@ -1233,7 +1209,7 @@ class ConsoleSupervisor __('Recommended value is: %s'), sprintf(__('%s or greater'), '800M') ).'

                '.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), - 'url' => ui_get_full_url('index.php'), + 'url' => 'index.php', ] ); } else { @@ -1252,7 +1228,7 @@ class ConsoleSupervisor __('Recommended value is: %s'), sprintf(__('%s or greater'), '500M') ).'

                '.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator'), - 'url' => ui_get_full_url('index.php'), + 'url' => 'index.php', ] ); } else { @@ -1265,7 +1241,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.PHP.DISABLE_FUNCTIONS', 'title' => __('Problems with disable functions in PHP.INI'), 'message' => __('Variable disable_functions containts functions system() or exec(), in PHP configuration file (php.ini)').'

                '.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator (Dont forget restart apache process after changes)'), - 'url' => ui_get_full_url('index.php'), + 'url' => 'index.php', ] ); } else { @@ -1343,9 +1319,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.HISTORYDB', 'title' => __('Historical database not available'), 'message' => __('Historical database is enabled. But not available using given configuration. Please check it.'), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=hist_db' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=hist_db', ] ); } else { @@ -1392,9 +1366,7 @@ class ConsoleSupervisor 'Your database is not maintained correctly. It seems that more than 48hrs have passed without proper maintenance. Please review documents of %s on how to perform this maintenance process (DB Tool) and enable it as soon as possible.', io_safe_output(get_product_name()) ), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf', ] ); } else { @@ -1454,9 +1426,7 @@ class ConsoleSupervisor 'Historical database maintance problem.' ), 'message' => __('Your historical database is not being maintained correctly. It seems that more than 48hrs have passed without proper maintenance. Please review documents of %s on how to perform this maintenance process (DB Tool) and enable it as soon as possible.', get_product_name()), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=perf', ] ); } else { @@ -1495,9 +1465,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.HISTORYDB.MR', 'title' => __('Historical database MR missmatch'), 'message' => __('Your historical database is not using the same schema of main DB. This could produce anomalyes while storing historical data.'), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=hist_db' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=hist_db', ] ); } else { @@ -1539,9 +1507,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.EXT.ELASTICSEARCH', 'title' => __('Log collector cannot connect to ElasticSearch'), 'message' => __('ElasticSearch is not available using current configuration. Please check it.'), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=log' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=log', ] ); } else { @@ -1611,9 +1577,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.METACONSOLE.DB_CONNECTION', 'title' => __('Metaconsole DB is not available.'), 'message' => __('Cannot connect with Metaconsole DB using stored configuration. Please check it.'), - 'url' => ui_get_full_url( - 'index.php?sec=general&sec2=godmode/setup/setup§ion=enterprise' - ), + 'url' => 'index.php?sec=general&sec2=godmode/setup/setup§ion=enterprise', ] ); } @@ -1642,9 +1606,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.DOWNTIME', 'title' => __('Scheduled downtime running.'), 'message' => __('A scheduled downtime is running. Some monitorization data won\'t be available while downtime is taking place.'), - 'url' => ui_get_full_url( - 'index.php?sec=gagente&sec2=godmode/agentes/planned_downtime.list' - ), + 'url' => 'index.php?sec=gagente&sec2=godmode/agentes/planned_downtime.list', ] ); return; @@ -1805,9 +1767,7 @@ class ConsoleSupervisor date('M j, G:i:s ', $next_downtime_begin), date('M j, G:i:s ', $next_downtime_end) ), - 'url' => ui_get_full_url( - 'index.php?sec=gagente&sec2=godmode/agentes/planned_downtime.list' - ), + 'url' => 'index.php?sec=gagente&sec2=godmode/agentes/planned_downtime.list', ] ); return; @@ -1912,9 +1872,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.SECURITY.DEFAULT_PASSWORD', 'title' => __('Default password for "Admin" user has not been changed.'), 'message' => __('Please change the default password because is a common vulnerability reported.'), - 'url' => ui_get_full_url( - 'index.php?sec=gusuarios&sec2=godmode/users/user_list' - ), + 'url' => 'index.php?sec=gusuarios&sec2=godmode/users/user_list', ] ); } else { @@ -1940,9 +1898,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.MISC.FONTPATH', 'title' => __('Default font doesnt exist'), 'message' => __('Your defined font doesnt exist or is not defined. Please check font parameters in your config'), - 'url' => ui_get_full_url( - 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=vis' - ), + 'url' => 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=vis', ] ); } else { @@ -1969,7 +1925,7 @@ class ConsoleSupervisor 'Your %s has the "develop_bypass" mode enabled. This is a developer mode and should be disabled in a production system. This value is written in the main index.php file', get_product_name() ), - 'url' => ui_get_full_url('index.php'), + 'url' => 'index.php', ] ); } else { @@ -1992,9 +1948,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.MISC.EVENTSTORMPROTECTION', 'title' => __('Event storm protection is activated.'), 'message' => __('You need to restart server after altering this configuration setting. No events will be generated during this mode.'), - 'url' => ui_get_full_url( - 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=general' - ), + 'url' => 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=general', ] ); } else { @@ -2021,9 +1975,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.UPDATEMANAGER.OPENSETUP', 'title' => __('Error, first setup "Open update".'), 'message' => $message, - 'url' => ui_get_full_url( - 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=general' - ), + 'url' => 'index.php?sec=gsetup&sec2=godmode/setup/setup§ion=general', ] ); } @@ -2043,9 +1995,7 @@ class ConsoleSupervisor get_product_name() ), 'message' => __('There is a new update available. Please go to Administration:Setup:Update Manager for more details.'), - 'url' => ui_get_full_url( - 'index.php?sec=gsetup&sec2=godmode/update_manager/update_manager&tab=online' - ), + 'url' => 'index.php?sec=gsetup&sec2=godmode/update_manager/update_manager&tab=online', ] ); } else { @@ -2132,9 +2082,7 @@ class ConsoleSupervisor 'type' => 'NOTIF.CRON.CONFIGURED', 'title' => __('DiscoveryConsoleTasks is not configured.'), 'message' => __($message_conf_cron), - 'url' => ui_get_full_url( - 'index.php?extension_in_menu=gservers&sec=extensions&sec2=enterprise/extensions/cron' - ), + 'url' => 'index.php?extension_in_menu=gservers&sec=extensions&sec2=enterprise/extensions/cron', ] ); } else { From f0c9d1631835b630f25465ec654493d10ed8e2b1 Mon Sep 17 00:00:00 2001 From: daniel Date: Fri, 22 Feb 2019 13:45:59 +0100 Subject: [PATCH 225/249] fixed errors view discovery task list Former-commit-id: 7e3160cde5c0fa46ee3d918789ffec4091f42c31 --- .../wizards/DiscoveryTaskList.class.php | 40 ++++++++++++++----- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index af6c371b67..c9ecaa8ec9 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -76,6 +76,7 @@ class DiscoveryTaskList extends Wizard */ public function run() { + global $config; // Load styles. parent::run(); @@ -94,7 +95,14 @@ class DiscoveryTaskList extends Wizard return $this->deleteTask(); } - return $this->showListConsoleTask().''.$this->showList(); + $ret = $this->showListConsoleTask(); + $ret2 = $this->showList(); + + if ($ret === false && $ret2 === false) { + include_once $config['homedir'].'/general/firts_task/recon_view.php'; + } + + return $ret; } @@ -255,7 +263,6 @@ class DiscoveryTaskList extends Wizard } else { $recon_task = db_get_all_rows_sql('SELECT * FROM trecon_task'); if ($recon_task === false) { - include_once $config['homedir'].'/general/firts_task/recon_view.php'; return false; } else { include_once $config['homedir'].'/include/functions_graph.php'; @@ -819,14 +826,18 @@ class DiscoveryTaskList extends Wizard if ($function_name == 'cron_task_do_backup' || $function_name == 'cron_task_execute_custom_script') { if ($manage_pandora) { - $data[7] = ''; + $data[7] = ''; $data[7] .= html_print_image( 'images/config.png', true, ['title' => __('Edit')] - ); - $data[7] .= ''; + ).''; } if ($manage_pandora) { @@ -841,14 +852,18 @@ class DiscoveryTaskList extends Wizard } } else { if ($write_perms || $manage_pandora) { - $data[7] = ''; + $data[7] = ''; $data[7] .= html_print_image( 'images/config.png', true, ['title' => __('Edit')] - ); - $data[7] .= ''; + ).''; } if ($manage_perms || $manage_pandora) { @@ -867,6 +882,8 @@ class DiscoveryTaskList extends Wizard } html_print_table($table); + } else { + return false; } return true; @@ -890,6 +907,9 @@ class DiscoveryTaskList extends Wizard case CLOUDWIZARD_AWS_DESCRIPTION: return 'wiz=cloud&mode=amazonws&page=1'; + case 'console_task': + return 'wiz=ctask'; + default: return 'wiz=hd&mode=netscan'; } From faae9c58b34fbababffd4f5c746156c6a3f9a5ba Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Fri, 22 Feb 2019 14:09:27 +0100 Subject: [PATCH 226/249] implement services tree view Former-commit-id: a081515f62ab210f96687577bfde60d5f6d23f23 --- pandora_console/include/class/Tree.class.php | 2 - .../include/class/TreeGroup.class.php | 906 ++++++++++-------- .../include/class/TreeGroupEdition.class.php | 184 ++-- .../include/class/TreeService.class.php | 8 - .../include/javascript/tree/TreeController.js | 2 - pandora_console/operation/events/events.php | 1 - 6 files changed, 582 insertions(+), 521 deletions(-) diff --git a/pandora_console/include/class/Tree.class.php b/pandora_console/include/class/Tree.class.php index da0380f4ea..4ad71f9ce1 100644 --- a/pandora_console/include/class/Tree.class.php +++ b/pandora_console/include/class/Tree.class.php @@ -879,8 +879,6 @@ class Tree { } $data = $this->getProcessedModules($data); $this->processModules($data); -hd("MODULES: ", true); -hd($data, true); $this->tree = $data; } diff --git a/pandora_console/include/class/TreeGroup.class.php b/pandora_console/include/class/TreeGroup.class.php index fd38794d1c..05ba271e24 100644 --- a/pandora_console/include/class/TreeGroup.class.php +++ b/pandora_console/include/class/TreeGroup.class.php @@ -1,467 +1,529 @@ L1fieldName = "id_group"; - $this->L1extraFields = array( - "tg.nombre AS `name`", - "tg.icon", - "tg.id_grupo AS gid" - ); - - $this->L2conditionInside = "AND ( - ta.id_grupo = " . $this->id . " - OR tasg.id_group = " . $this->id . " - )"; - } - - public function setPropagateCounters($value) { - $this->propagateCounters = (bool)$value; - } - - public function setDisplayAllGroups($value) { - $this->displayAllGroups = (bool)$value; - } - - protected function getData() { - if ($this->id == -1) { - - $this->getFirstLevel(); - - } elseif ($this->type == 'group') { - $this->getSecondLevel(); - } elseif ($this->type == 'agent') { - $this->getThirdLevel(); - } - } - - protected function getGroupSearchFilter() { - return ""; - } - - protected function getFirstLevel() { - $processed_items = $this->getProcessedGroups(); - - if (!empty($processed_items)) { - // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants - if (!empty($this->filter['searchGroup'])) { - // Save the groups which intersect with the user groups - $groups = db_get_all_rows_filter('tgrupo', array('nombre' => '%' . $this->filter['searchGroup'] . '%')); - if ($groups == false) $groups = array(); - $userGroupsACL = $this->userGroupsACL; - $ids_hash = array_reduce($groups, function ($userGroups, $group) use ($userGroupsACL) { - $group_id = $group['id_grupo']; - if (isset($userGroupsACL[$group_id])) { - $userGroups[$group_id] = $userGroupsACL[$group_id]; - } - - return $userGroups; - }, array()); - - $result = self::extractGroupsWithIDs($processed_items, $ids_hash); - - $processed_items = ($result === false) ? array() : $result; - } - - // groupID filter. To access the view from tactical views f.e. - if (!empty($this->filter['groupID'])) { - $result = self::extractItemWithID($processed_items, $this->filter['groupID'], "group", $this->strictACL); - - $processed_items = ($result === false) ? array() : array($result); - } - } - hd("G-GETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVELGETFIRSTLEVEL", true); -hd($processed_items, true); - $this->tree = $processed_items; - } - - protected function getProcessedGroups () { - $processed_groups = array(); - // Index and process the groups - $groups = $this->getGroupCounters(); - - // If user have not permissions in parent, set parent node to 0 (all) - // Avoid to do foreach for admins - if (!users_can_manage_group_all("AR")) { - foreach ($groups as $id => $group) { - if (!isset($this->userGroups[$groups[$id]['parent']])) { - $groups[$id]['parent'] = 0; - } - } - } - // Build the group hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = array(); - } - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], array("Tree", "cmpSortNames")); - } - } - //Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter($groups, function ($group) { - return !$group['have_parent']; - }); - // Propagate child counters to her parents - - if ($this->propagateCounters) { - TreeGroup::processCounters($groups); - // Filter groups and eliminates the reference to empty groups - $groups = $this->deleteEmptyGroups($groups); - } else { - $groups = $this->deleteEmptyGroupsNotPropagate($groups); - } - - usort($groups, array("Tree", "cmpSortNames")); - - return $groups; - } - - protected function getGroupCounters() { - $fields = $this->getFirstLevelFields(); - $inside_fields = $this->getFirstLevelFieldsInside(); - - $group_acl = ""; - $secondary_group_acl = ""; - if (!users_can_manage_group_all("AR")) { - $user_groups_str = implode(",", $this->userGroupsArray); - $group_acl = " AND ta.id_grupo IN ($user_groups_str)"; - $secondary_group_acl = " AND tasg.id_group IN ($user_groups_str)"; - } - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_search_filter = preg_replace("/%/", "%%", $agent_search_filter); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_status_filter = $this->getModuleStatusFilter(); - - $module_search_inner = ""; - $module_search_filter = ""; - if (!empty($this->filter['searchModule'])) { - $module_search_inner = " - INNER JOIN tagente_modulo tam - ON ta.id_agente = tam.id_agente - INNER JOIN tagente_estado tae - ON tae.id_agente_modulo = tam.id_agente_modulo"; - $module_search_filter = "AND tam.disabled = 0 - AND tam.nombre LIKE '%%" . $this->filter['searchModule'] . "%%' " . - $this->getModuleStatusFilterFromTestado() - ; - } - - $table = is_metaconsole() ? "tmetaconsole_agent" : "tagente"; - $table_sec = is_metaconsole() ? "tmetaconsole_agent_secondary_group" : "tagent_secondary_group"; - - $sql_model = "SELECT %s FROM - ( - SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_grupo AS g - FROM $table ta - $module_search_inner - WHERE ta.disabled = 0 - %s - $agent_search_filter - $agent_status_filter - $module_status_filter - $module_search_filter - $group_acl - GROUP BY id_grupo - UNION ALL - SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_group AS g - FROM $table ta INNER JOIN $table_sec tasg - ON ta.id_agente = tasg.id_agent - $module_search_inner - WHERE ta.disabled = 0 - %s - $agent_search_filter - $agent_status_filter - $module_status_filter - $module_search_filter - $secondary_group_acl - GROUP BY id_group - ) x GROUP BY g"; - $sql_array = array(); - foreach ($inside_fields as $inside_field) { - $sql_array[] = sprintf( - $sql_model, - $inside_field['header'], - $inside_field['condition'], - $inside_field['condition'] - ); - } - $sql = "SELECT $fields FROM (" . implode(" UNION ALL ", $sql_array) . ") x2 - RIGHT JOIN tgrupo tg - ON x2.g = tg.id_grupo - GROUP BY tg.id_grupo"; - $stats = db_get_all_rows_sql($sql); - - $group_stats = array(); - - hd("STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS STATS ", true); - hd($stats, true); - foreach ($stats as $group) { - $group_stats[$group['gid']]['total_count'] = (int)$group['total_count']; - $group_stats[$group['gid']]['total_critical_count'] = (int)$group['total_critical_count']; - $group_stats[$group['gid']]['total_unknown_count'] = (int)$group['total_unknown_count']; - $group_stats[$group['gid']]['total_warning_count'] = (int)$group['total_warning_count']; - $group_stats[$group['gid']]['total_not_init_count'] = (int)$group['total_not_init_count']; - $group_stats[$group['gid']]['total_normal_count'] = (int)$group['total_normal_count']; - $group_stats[$group['gid']]['total_fired_count'] = (int)$group['total_alerts_count']; - $group_stats[$group['gid']]['name'] = $group['name']; - $group_stats[$group['gid']]['parent'] = $group['parent']; - $group_stats[$group['gid']]['icon'] = $group['icon']; - $group_stats[$group['gid']]['id'] = $group['gid']; - $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); - - } + protected $displayAllGroups = false; + public function __construct($type, $rootType='', $id=-1, $rootID=-1, $serverID=false, $childrenMethod='on_demand', $access='AR') + { + global $config; - return $group_stats; - } + parent::__construct($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - protected function getFirstLevelFields() { - $fields = parent::getFirstLevelFields(); - $parent = $this->getDisplayHierarchy() ? 'tg.parent' : '0 as parent'; - return "$fields, $parent"; - } + $this->L1fieldName = 'id_group'; + $this->L1extraFields = [ + 'tg.nombre AS `name`', + 'tg.icon', + 'tg.id_grupo AS gid', + ]; - protected function getProcessedModules($modules_tree) { + $this->L2conditionInside = 'AND ( + ta.id_grupo = '.$this->id.' + OR tasg.id_group = '.$this->id.' + )'; + } - $groups = array(); - foreach ($modules_tree as $group) { - $groups[$group["id"]] = $group; - } - // Build the module hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = array(); - } - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } + public function setPropagateCounters($value) + { + $this->propagateCounters = (bool) $value; + } - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], array("Tree", "cmpSortNames")); - } - } - //Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter($groups, function ($group) { - return !$group['have_parent']; - }); - return array_values($groups); - } + public function setDisplayAllGroups($value) + { + $this->displayAllGroups = (bool) $value; + } - // FIXME: Hierarchy lops is broken - protected function getProcessedModules_old($modules_tree) { - $tree_modules = array(); - $new_modules_root = array_filter($modules_tree, function ($module) { - return (isset($module['parent']) && ($module['parent'] == 0)); - }); + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } else if ($this->type == 'group') { + $this->getSecondLevel(); + } else if ($this->type == 'agent') { + $this->getThirdLevel(); + } + } - $new_modules_child = array_filter($modules_tree, function ($module) { - return (isset($module['parent']) && ($module['parent'] != 0)); - }); - $i = 0; - while (!empty($new_modules_child)) { - foreach ($new_modules_child as $i => $child) { - TreeGroup::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child); - } - } + protected function getGroupSearchFilter() + { + return ''; + } - foreach ($new_modules_root as $m) { - $tree_modules[] = $m; - } - return $tree_modules; - } - // FIXME with getProcessedModules_old - static function recursive_modules_tree_view (&$new_modules, &$new_modules_child, $i, $child) { - foreach ($new_modules as $index => $module) { - if ($module['id'] == $child['parent']) { - $new_modules[$index]['children'][] = $child; - unset($new_modules_child[$i]); - break; - } - else if (isset($new_modules[$index]['children'])) { - TreeGroup::recursive_modules_tree_view ($new_modules[$index]['children'], $new_modules_child, $i, $child); - } - } - } + protected function getFirstLevel() + { + $processed_items = $this->getProcessedGroups(); - static function processCounters(&$groups) { - $all_counters = array(); - foreach ($groups as $id => $group) { - $child_counters = array(); - if (!empty($groups[$id]['children'])) { - $child_counters = TreeGroup::processCounters($groups[$id]['children']); - } - if (!empty($child_counters)) { - foreach($child_counters as $type => $value) { - $groups[$id]['counters'][$type] += $value; - } - } - foreach($groups[$id]['counters'] as $type => $value) { - $all_counters[$type] += $value; - } - } - return $all_counters; - } + if (!empty($processed_items)) { + // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants + if (!empty($this->filter['searchGroup'])) { + // Save the groups which intersect with the user groups + $groups = db_get_all_rows_filter('tgrupo', ['nombre' => '%'.$this->filter['searchGroup'].'%']); + if ($groups == false) { + $groups = []; + } - /** - * @brief Recursive function to remove the empty groups - * - * @param groups All groups structure - * - * @return new_groups A new groups structure without empty groups - */ - protected function deleteEmptyGroups ($groups) { - if($this->displayAllGroups) return $groups; - $new_groups = array(); - foreach ($groups as $group) { - // If a group is empty, do not add to new_groups. - if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) { - continue; - } - // Tray to remove the children groups - if (!empty($group['children'])) { - $children = $this->deleteEmptyGroups ($group['children']); - if (empty($children)) unset($group['children']); - else $group['children'] = $children; - } - $new_groups[] = $group; - } - return $new_groups; - } + $userGroupsACL = $this->userGroupsACL; + $ids_hash = array_reduce( + $groups, + function ($userGroups, $group) use ($userGroupsACL) { + $group_id = $group['id_grupo']; + if (isset($userGroupsACL[$group_id])) { + $userGroups[$group_id] = $userGroupsACL[$group_id]; + } - protected function deleteEmptyGroupsNotPropagate ($groups) { - if($this->displayAllGroups) return $groups; - $new_groups = array(); - foreach ($groups as $group) { - // Tray to remove the children groups - if (!empty($group['children'])) { - $children = $this->deleteEmptyGroupsNotPropagate ($group['children']); - if (empty($children)) { - unset($group['children']); - // If a group is empty, do not add to new_groups. - if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { - $new_groups[] = $group; - } - } else { - $group['children'] = $children; - $new_groups[] = $group; - } - } else { - // If a group is empty, do not add to new_groups. - if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { - $new_groups[] = $group; - } - } - } - return $new_groups; - } + return $userGroups; + }, + [] + ); - private static function extractGroupsWithIDs ($groups, $ids_hash) { - $result_groups = array(); - foreach ($groups as $group) { - if (isset($ids_hash[$group['id']])) { - $result_groups[] = $group; - } - else if (!empty($group['children'])) { - $result = self::extractGroupsWithIDs($group['children'], $ids_hash); + $result = self::extractGroupsWithIDs($processed_items, $ids_hash); - // Item found on children - if (!empty($result)) { - $result_groups = array_merge($result_groups, $result); - } - } - } + $processed_items = ($result === false) ? [] : $result; + } - return $result_groups; - } + // groupID filter. To access the view from tactical views f.e. + if (!empty($this->filter['groupID'])) { + $result = self::extractItemWithID($processed_items, $this->filter['groupID'], 'group', $this->strictACL); - private static function extractItemWithID ($items, $item_id, $item_type = "group", $strictACL = false) { - foreach ($items as $item) { - if ($item["type"] != $item_type) - continue; + $processed_items = ($result === false) ? [] : [$result]; + } + } - // Item found - if ($strictACL && is_metaconsole()) { - foreach ($item["id"] as $server_id => $id) { - if ($id == $item_id) - return $item; - } - } - else { - if ($item["id"] == $item_id) - return $item; - } + $this->tree = $processed_items; + } - if ($item["type"] == "group" && !empty($item["children"])) { - $result = self::extractItemWithID($item["children"], $item_id, $item_type, $strictACL); - // Item found on children - if ($result !== false) - return $result; - } - } + protected function getProcessedGroups() + { + $processed_groups = []; + // Index and process the groups + $groups = $this->getGroupCounters(); - // Item not found - return false; - } + // If user have not permissions in parent, set parent node to 0 (all) + // Avoid to do foreach for admins + if (!users_can_manage_group_all('AR')) { + foreach ($groups as $id => $group) { + if (!isset($this->userGroups[$groups[$id]['parent']])) { + $groups[$id]['parent'] = 0; + } + } + } + + // Build the group hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = []; + } + + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } + + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); + } + } + + // Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter( + $groups, + function ($group) { + return !$group['have_parent']; + } + ); + // Propagate child counters to her parents + if ($this->propagateCounters) { + self::processCounters($groups); + // Filter groups and eliminates the reference to empty groups + $groups = $this->deleteEmptyGroups($groups); + } else { + $groups = $this->deleteEmptyGroupsNotPropagate($groups); + } + + usort($groups, ['Tree', 'cmpSortNames']); + return $groups; + } + + + protected function getGroupCounters() + { + $fields = $this->getFirstLevelFields(); + $inside_fields = $this->getFirstLevelFieldsInside(); + + $group_acl = ''; + $secondary_group_acl = ''; + if (!users_can_manage_group_all('AR')) { + $user_groups_str = implode(',', $this->userGroupsArray); + $group_acl = " AND ta.id_grupo IN ($user_groups_str)"; + $secondary_group_acl = " AND tasg.id_group IN ($user_groups_str)"; + } + + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_search_filter = preg_replace('/%/', '%%', $agent_search_filter); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_status_filter = $this->getModuleStatusFilter(); + + $module_search_inner = ''; + $module_search_filter = ''; + if (!empty($this->filter['searchModule'])) { + $module_search_inner = ' + INNER JOIN tagente_modulo tam + ON ta.id_agente = tam.id_agente + INNER JOIN tagente_estado tae + ON tae.id_agente_modulo = tam.id_agente_modulo'; + $module_search_filter = "AND tam.disabled = 0 + AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' ".$this->getModuleStatusFilterFromTestado(); + } + + $table = is_metaconsole() ? 'tmetaconsole_agent' : 'tagente'; + $table_sec = is_metaconsole() ? 'tmetaconsole_agent_secondary_group' : 'tagent_secondary_group'; + + $sql_model = "SELECT %s FROM + ( + SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_grupo AS g + FROM $table ta + $module_search_inner + WHERE ta.disabled = 0 + %s + $agent_search_filter + $agent_status_filter + $module_status_filter + $module_search_filter + $group_acl + GROUP BY id_grupo + UNION ALL + SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_group AS g + FROM $table ta INNER JOIN $table_sec tasg + ON ta.id_agente = tasg.id_agent + $module_search_inner + WHERE ta.disabled = 0 + %s + $agent_search_filter + $agent_status_filter + $module_status_filter + $module_search_filter + $secondary_group_acl + GROUP BY id_group + ) x GROUP BY g"; + $sql_array = []; + foreach ($inside_fields as $inside_field) { + $sql_array[] = sprintf( + $sql_model, + $inside_field['header'], + $inside_field['condition'], + $inside_field['condition'] + ); + } + + $sql = "SELECT $fields FROM (".implode(' UNION ALL ', $sql_array).') x2 + RIGHT JOIN tgrupo tg + ON x2.g = tg.id_grupo + GROUP BY tg.id_grupo'; + $stats = db_get_all_rows_sql($sql); + + $group_stats = []; + foreach ($stats as $group) { + $group_stats[$group['gid']]['total_count'] = (int) $group['total_count']; + $group_stats[$group['gid']]['total_critical_count'] = (int) $group['total_critical_count']; + $group_stats[$group['gid']]['total_unknown_count'] = (int) $group['total_unknown_count']; + $group_stats[$group['gid']]['total_warning_count'] = (int) $group['total_warning_count']; + $group_stats[$group['gid']]['total_not_init_count'] = (int) $group['total_not_init_count']; + $group_stats[$group['gid']]['total_normal_count'] = (int) $group['total_normal_count']; + $group_stats[$group['gid']]['total_fired_count'] = (int) $group['total_alerts_count']; + $group_stats[$group['gid']]['name'] = $group['name']; + $group_stats[$group['gid']]['parent'] = $group['parent']; + $group_stats[$group['gid']]['icon'] = $group['icon']; + $group_stats[$group['gid']]['id'] = $group['gid']; + $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); + } + + return $group_stats; + } + + + protected function getFirstLevelFields() + { + $fields = parent::getFirstLevelFields(); + $parent = $this->getDisplayHierarchy() ? 'tg.parent' : '0 as parent'; + return "$fields, $parent"; + } + + + protected function getProcessedModules($modules_tree) + { + $groups = []; + foreach ($modules_tree as $group) { + $groups[$group['id']] = $group; + } + + // Build the module hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = []; + } + + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } + + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); + } + } + + // Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter( + $groups, + function ($group) { + return !$group['have_parent']; + } + ); + + return array_values($groups); + } + + + // FIXME: Hierarchy lops is broken + protected function getProcessedModules_old($modules_tree) + { + $tree_modules = []; + $new_modules_root = array_filter( + $modules_tree, + function ($module) { + return (isset($module['parent']) && ($module['parent'] == 0)); + } + ); + + $new_modules_child = array_filter( + $modules_tree, + function ($module) { + return (isset($module['parent']) && ($module['parent'] != 0)); + } + ); + + $i = 0; + while (!empty($new_modules_child)) { + foreach ($new_modules_child as $i => $child) { + self::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child); + } + } + + foreach ($new_modules_root as $m) { + $tree_modules[] = $m; + } + + return $tree_modules; + } + + + // FIXME with getProcessedModules_old + static function recursive_modules_tree_view(&$new_modules, &$new_modules_child, $i, $child) + { + foreach ($new_modules as $index => $module) { + if ($module['id'] == $child['parent']) { + $new_modules[$index]['children'][] = $child; + unset($new_modules_child[$i]); + break; + } else if (isset($new_modules[$index]['children'])) { + self::recursive_modules_tree_view($new_modules[$index]['children'], $new_modules_child, $i, $child); + } + } + } + + + static function processCounters(&$groups) + { + $all_counters = []; + foreach ($groups as $id => $group) { + $child_counters = []; + if (!empty($groups[$id]['children'])) { + $child_counters = self::processCounters($groups[$id]['children']); + } + + if (!empty($child_counters)) { + foreach ($child_counters as $type => $value) { + $groups[$id]['counters'][$type] += $value; + } + } + + foreach ($groups[$id]['counters'] as $type => $value) { + $all_counters[$type] += $value; + } + } + + return $all_counters; + } + + + /** + * @brief Recursive function to remove the empty groups + * + * @param groups All groups structure + * + * @return new_groups A new groups structure without empty groups + */ + protected function deleteEmptyGroups($groups) + { + if ($this->displayAllGroups) { + return $groups; + } + + $new_groups = []; + foreach ($groups as $group) { + // If a group is empty, do not add to new_groups. + if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) { + continue; + } + + // Tray to remove the children groups + if (!empty($group['children'])) { + $children = $this->deleteEmptyGroups($group['children']); + if (empty($children)) { + unset($group['children']); + } else { + $group['children'] = $children; + } + } + + $new_groups[] = $group; + } + + return $new_groups; + } + + + protected function deleteEmptyGroupsNotPropagate($groups) + { + if ($this->displayAllGroups) { + return $groups; + } + + $new_groups = []; + foreach ($groups as $group) { + // Tray to remove the children groups + if (!empty($group['children'])) { + $children = $this->deleteEmptyGroupsNotPropagate($group['children']); + if (empty($children)) { + unset($group['children']); + // If a group is empty, do not add to new_groups. + if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { + $new_groups[] = $group; + } + } else { + $group['children'] = $children; + $new_groups[] = $group; + } + } else { + // If a group is empty, do not add to new_groups. + if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { + $new_groups[] = $group; + } + } + } + + return $new_groups; + } + + + private static function extractGroupsWithIDs($groups, $ids_hash) + { + $result_groups = []; + foreach ($groups as $group) { + if (isset($ids_hash[$group['id']])) { + $result_groups[] = $group; + } else if (!empty($group['children'])) { + $result = self::extractGroupsWithIDs($group['children'], $ids_hash); + + // Item found on children + if (!empty($result)) { + $result_groups = array_merge($result_groups, $result); + } + } + } + + return $result_groups; + } + + + private static function extractItemWithID($items, $item_id, $item_type='group', $strictACL=false) + { + foreach ($items as $item) { + if ($item['type'] != $item_type) { + continue; + } + + // Item found + if ($strictACL && is_metaconsole()) { + foreach ($item['id'] as $server_id => $id) { + if ($id == $item_id) { + return $item; + } + } + } else { + if ($item['id'] == $item_id) { + return $item; + } + } + + if ($item['type'] == 'group' && !empty($item['children'])) { + $result = self::extractItemWithID($item['children'], $item_id, $item_type, $strictACL); + + // Item found on children + if ($result !== false) { + return $result; + } + } + } + + // Item not found + return false; + } + + + protected function getDisplayHierarchy() + { + return $this->filter['searchHirearchy'] || + (empty($this->filter['searchAgent']) && empty($this->filter['searchModule'])); + } - protected function getDisplayHierarchy() { - return $this->filter['searchHirearchy'] || - (empty($this->filter['searchAgent']) && empty($this->filter['searchModule'])); - } } - -?> - diff --git a/pandora_console/include/class/TreeGroupEdition.class.php b/pandora_console/include/class/TreeGroupEdition.class.php index dea62da238..55efebe976 100644 --- a/pandora_console/include/class/TreeGroupEdition.class.php +++ b/pandora_console/include/class/TreeGroupEdition.class.php @@ -1,108 +1,120 @@ id == -1) { - $this->getFirstLevel(); - } - } - - protected function getProcessedGroups () { - $processed_groups = array(); - // Index and process the groups - $groups = $this->getGroupCounters(); - - // If user have not permissions in parent, set parent node to 0 (all) - // Avoid to do foreach for admins - if (!users_can_manage_group_all("AR")) { - foreach ($groups as $id => $group) { - if (!isset($this->userGroups[$groups[$id]['parent']])) { - $groups[$id]['parent'] = 0; - } - } - } - // Build the group hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = array(); - } - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } - - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], array("Tree", "cmpSortNames")); - } - } - //Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter($groups, function ($group) { - return !$group['have_parent']; - }); - - usort($groups, array("Tree", "cmpSortNames")); - return $groups; - } +class TreeGroupEdition extends TreeGroup +{ - protected function getGroupCounters() { - $messages = array( - 'confirm' => __('Confirm'), - 'cancel' => __('Cancel'), - 'messg' => __('Are you sure?') - ); - $sql = "SELECT id_grupo AS gid, + public function __construct($type, $rootType='', $id=-1, $rootID=-1, $serverID=false, $childrenMethod='on_demand', $access='AR') + { + global $config; + + parent::__construct($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + } + + + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } + } + + + protected function getProcessedGroups() + { + $processed_groups = []; + // Index and process the groups + $groups = $this->getGroupCounters(); + + // If user have not permissions in parent, set parent node to 0 (all) + // Avoid to do foreach for admins + if (!users_can_manage_group_all('AR')) { + foreach ($groups as $id => $group) { + if (!isset($this->userGroups[$groups[$id]['parent']])) { + $groups[$id]['parent'] = 0; + } + } + } + + // Build the group hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = []; + } + + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } + + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); + } + } + + // Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter( + $groups, + function ($group) { + return !$group['have_parent']; + } + ); + + usort($groups, ['Tree', 'cmpSortNames']); + return $groups; + } + + + protected function getGroupCounters() + { + $messages = [ + 'confirm' => __('Confirm'), + 'cancel' => __('Cancel'), + 'messg' => __('Are you sure?'), + ]; + $sql = 'SELECT id_grupo AS gid, nombre as name, parent, icon FROM tgrupo - "; + '; - $stats = db_get_all_rows_sql($sql); - $group_stats = array(); - foreach ($stats as $group) { - $group_stats[$group['gid']]['name'] = $group['name']; - $group_stats[$group['gid']]['parent'] = $group['parent']; - $group_stats[$group['gid']]['icon'] = $group['icon']; - $group_stats[$group['gid']]['id'] = $group['gid']; - $group_stats[$group['gid']]['type'] = 'group'; + $stats = db_get_all_rows_sql($sql); + $group_stats = []; + foreach ($stats as $group) { + $group_stats[$group['gid']]['name'] = $group['name']; + $group_stats[$group['gid']]['parent'] = $group['parent']; + $group_stats[$group['gid']]['icon'] = $group['icon']; + $group_stats[$group['gid']]['id'] = $group['gid']; + $group_stats[$group['gid']]['type'] = 'group'; + + $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); + $group_stats[$group['gid']]['delete']['messages'] = $messages; + $group_stats[$group['gid']]['edit'] = 1; + $group_stats[$group['gid']]['alerts'] = ''; + } + + return $group_stats; + } - $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); - $group_stats[$group['gid']]['delete']['messages'] = $messages; - $group_stats[$group['gid']]['edit'] = 1; - $group_stats[$group['gid']]['alerts'] = ''; - } - return $group_stats; - } } - -?> - diff --git a/pandora_console/include/class/TreeService.class.php b/pandora_console/include/class/TreeService.class.php index 46f9139427..bbddc8dc2a 100644 --- a/pandora_console/include/class/TreeService.class.php +++ b/pandora_console/include/class/TreeService.class.php @@ -114,8 +114,6 @@ class TreeService extends Tree { protected function getProcessedServices () { $fields = $this->getFirstLevelFields(); - - //hd($this->userGroupsArray, true); if (users_can_manage_group_all("AR")){ $groups_acl = ""; @@ -166,9 +164,6 @@ class TreeService extends Tree { $services[$service['id']]['serviceDetail']='http://localhost/pandora_console/index.php?sec=network&sec2=enterprise/operation/services/services&tab=service_map&id_service='.(int)$service['id']; } - hd("STATS:::::::::::::::::::::::::::::: ", true); -hd($services, true); - return $services; } @@ -227,9 +222,6 @@ hd($services, true); } } - hd("MODULESSSS::", true); -hd($data_modules, true); - $sql = $this->getSecondLevelServicesSql(); $data_services = db_process_sql($sql); diff --git a/pandora_console/include/javascript/tree/TreeController.js b/pandora_console/include/javascript/tree/TreeController.js index e22a17ced9..3fab4f6dab 100644 --- a/pandora_console/include/javascript/tree/TreeController.js +++ b/pandora_console/include/javascript/tree/TreeController.js @@ -750,7 +750,6 @@ var TreeController = { } // Load the status counters - console.log(element.counters); var hasCounters = _processNodeCounters($content, element.counters, element.type); //Don't show empty groups if (element.type == 'agent') { @@ -871,7 +870,6 @@ var TreeController = { .hide(); $node.append($group); } - //console.log(data.tree); _.each(data.tree, function(element) { element.jqObject = _processNode($group, element); diff --git a/pandora_console/operation/events/events.php b/pandora_console/operation/events/events.php index 5dc7caea1b..18e1e77ffc 100644 --- a/pandora_console/operation/events/events.php +++ b/pandora_console/operation/events/events.php @@ -314,7 +314,6 @@ if ($id_agent != 0) { $text_module = (string) get_parameter('module_search', ''); $id_agent_module = get_parameter('module_search_hidden', get_parameter('id_agent_module', 0)); -hd("------------------------------------>>>>>>> ".$id_agent_module." y id_agent: ".$id_agent, true); if ($id_agent_module != 0) { $text_module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $id_agent_module); if ($text_module == false) { From 2c1eb0fe03292e54ab7ffe48dd6cbd677858c8d4 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Fri, 22 Feb 2019 14:16:39 +0100 Subject: [PATCH 227/249] Added aws view menu Former-commit-id: a64079eb5e773d3fe36031bac856aa801728f79d --- pandora_console/operation/menu.php | 1 + 1 file changed, 1 insertion(+) diff --git a/pandora_console/operation/menu.php b/pandora_console/operation/menu.php index 7c7099580e..bf81ae5110 100644 --- a/pandora_console/operation/menu.php +++ b/pandora_console/operation/menu.php @@ -105,6 +105,7 @@ if (!empty($sub2)) { } enterprise_hook('cluster_menu'); +enterprise_hook('aws_menu'); if (!empty($sub)) { $menu_operation['estado']['text'] = __('Monitoring'); From 4abf19722bf1bf3fac32c0699775614b0e08c072 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 22 Feb 2019 18:12:01 +0100 Subject: [PATCH 228/249] Minor fixes and improvements. Discovery Former-commit-id: d4410ddca6aec18ed28b7b0236ee16a3e8a6d2b8 --- .../include/class/ConsoleSupervisor.php | 43 +++++++++++++++++++ pandora_console/include/functions_config.php | 2 +- pandora_server/lib/PandoraFMS/DB.pm | 2 + 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index c0a91480cc..ddce4b7e87 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -141,6 +141,48 @@ class ConsoleSupervisor } + /** + * Manage scheduled tasks (basic). + * + * @return void + */ + public function runBasic() + { + global $config; + + /* + * Check license. + * NOTIF.LICENSE.EXPIRATION + */ + + $this->checkLicense(); + + /* + * Check component statuses (servers down - frozen). + * NOTIF.SERVER.STATUS.ID_SERVER + */ + + $this->checkPandoraServers(); + + /* + * Check at least 1 server running in master mode. + * NOTIF.SERVER.MASTER + */ + + $this->checkPandoraServerMasterAvailable(); + + /* + * Check if CRON is running. + * NOTIF.CRON.CONFIGURED + */ + + if (enterprise_installed()) { + $this->checkCronRunning(); + } + + } + + /** * Manage scheduled tasks. * @@ -344,6 +386,7 @@ class ConsoleSupervisor * Check if CRON is running. * NOTIF.CRON.CONFIGURED */ + if (enterprise_installed()) { $this->checkCronRunning(); } diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index 2a301affd9..475ef2db79 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -2680,7 +2680,7 @@ function config_check() || (get_system_time() - $config['cron_last_run']) > 3600 ) { $supervisor = new ConsoleSupervisor(false); - $supervisor->checkCronRunning(); + $supervisor->runBasic(); } } diff --git a/pandora_server/lib/PandoraFMS/DB.pm b/pandora_server/lib/PandoraFMS/DB.pm index 20bece94e6..a257d5df07 100644 --- a/pandora_server/lib/PandoraFMS/DB.pm +++ b/pandora_server/lib/PandoraFMS/DB.pm @@ -20,6 +20,8 @@ package PandoraFMS::DB; use strict; use warnings; use DBI; + +use lib '/usr/lib/perl5'; use PandoraFMS::Tools; #use Data::Dumper; From 8b5f50f883f48180ec33cf1f0ff3028827ea49e4 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Fri, 22 Feb 2019 19:18:07 +0100 Subject: [PATCH 229/249] Discovery minor fixes Former-commit-id: 3914d7a99fb70d88c1a1f95d3c2aeb100f277266 --- .../godmode/wizards/HostDevices.class.php | 14 +++++- .../godmode/wizards/Wizard.main.php | 2 +- .../include/class/ConsoleSupervisor.php | 2 +- pandora_console/include/styles/discovery.css | 50 +++++++++++-------- 4 files changed, 44 insertions(+), 24 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index ef98b09d3a..6e31299b9a 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -124,8 +124,20 @@ class HostDevices extends Wizard ]; } + $this->prepareBreadcrum( + [ + [ + 'link' => ui_get_full_url( + 'index.php?sec=gservers&sec2=godmode/servers/discovery' + ), + 'label' => __('Discovery'), + ], + ] + ); + + $this->printHeader(); + $this->printBigButtonsList($buttons); - $this->printGoBackButton(); return; } diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index ba057475e3..c584e6a9b7 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -228,7 +228,7 @@ class Wizard */ public function printBreadcrum() { - return '

                '.implode('', $this->breadcrum).'

                '; + return '

                '.implode('', $this->breadcrum).'

                '; } diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index ddce4b7e87..d0386a59c0 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -377,7 +377,7 @@ class ConsoleSupervisor $this->checkMinorRelease(); - if ($this->verbose === true) { + if (enterprise_installed()) { // Release the lock. enterprise_hook('cron_supervisor_release_lock'); } diff --git a/pandora_console/include/styles/discovery.css b/pandora_console/include/styles/discovery.css index 33b1d3c0a9..36711a8474 100644 --- a/pandora_console/include/styles/discovery.css +++ b/pandora_console/include/styles/discovery.css @@ -13,8 +13,8 @@ li.discovery { li.discovery > a { text-decoration: none; + color: #333; } - li.discovery > a:hover { color: #000; } @@ -46,27 +46,33 @@ div.data_container:hover { height: auto; text-align: center; } +h1.wizard { + padding: 0; + margin: 0; + margin-top: -1.25em; +} +h1.wizard a { + margin-left: -20px; +} +h1.wizard a:hover { + color: #fff; +} #text_wizard { font-weight: bolder; text-decoration: none; font-size: 24px; } -.text_color { - color: white; - margin-left: 25px; -} -.text_color:hover { - text-decoration: none; -} -.arrow_box { +div.arrow_box { display: inline-block; position: relative; background: #ccc; - padding: 14px; + color: #888; + padding: 1.3em; margin-left: 20px; margin-bottom: 10px; + padding-left: 3em; } -.arrow_box:after, + .arrow_box:before { top: 50%; border: solid transparent; @@ -75,9 +81,11 @@ div.data_container:hover { width: 0; position: absolute; pointer-events: none; + z-index: 1; } .arrow_box.selected { - background: #82b92e; + background: #424242; + color: #ccc; } .arrow_box:after { @@ -86,20 +94,20 @@ div.data_container:hover { border-width: 20px; margin-top: -20px; } -.arrow_box:before { + +div.arrow_box:before { left: 100%; border-left-color: #ccc; border-width: 20px; margin-top: -20px; } .arrow_box.selected:before { - border-left-color: #82b92e; + border-left-color: #424242; } -.arrow_box { - display: inline-block; - position: relative; - padding: 14px; - margin-left: 20px; - margin-bottom: 10px; - padding-left: 3em; + +.arrow_box.selected:hover { + color: #fff; +} +.arrow_box:hover { + color: #000; } From 4289684e00748b6b4054aa4c46828bb679a54ba0 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Sat, 23 Feb 2019 00:01:59 +0100 Subject: [PATCH 230/249] Cloud Discovery RC1 Former-commit-id: 9933be0c76b44592783e686bfa2da9ab63df1022 --- .../include/class/ConsoleSupervisor.php | 14 ++++++++++++++ pandora_server/lib/PandoraFMS/DiscoveryServer.pm | 3 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index d0386a59c0..64643b4c58 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -150,6 +150,20 @@ class ConsoleSupervisor { global $config; + /* + * PHP configuration warnings: + * NOTIF.PHP.SAFE_MODE + * NOTIF.PHP.INPUT_TIME + * NOTIF.PHP.EXECUTION_TIME + * NOTIF.PHP.UPLOAD_MAX_FILESIZE + * NOTIF.PHP.MEMORY_LIMIT + * NOTIF.PHP.DISABLE_FUNCTIONS + * NOTIF.PHP.PHANTOMJS + * NOTIF.PHP.VERSION + */ + + $this->checkPHPSettings(); + /* * Check license. * NOTIF.LICENSE.EXPIRATION diff --git a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm index 137dffd822..7557ef8320 100644 --- a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -275,7 +275,8 @@ sub exec_recon_script ($$$) { } if (-x $command) { - `$command $args`; + my $exec_output = `$command $args`; + logger ($pa_config, "Execution output: \n", $exec_output); } else { logger ($pa_config, "Cannot execute recon task command $command."); } From febe2cc3a6cb92ec776d8855336a99303eb8aeec Mon Sep 17 00:00:00 2001 From: artica Date: Sat, 23 Feb 2019 00:02:37 +0100 Subject: [PATCH 231/249] Auto-updated build strings. Former-commit-id: 4f687af81ee7ab9541649e5f395c2e2aaf359609 --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index f10b529fae..28b7562888 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190222 +Version: 7.0NG.731-190223 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 643a45d94b..9560c00f1b 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190222" +pandora_version="7.0NG.731-190223" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 35e3778268..3c25dbba4e 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190222'; +use constant AGENT_BUILD => '190223'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index f3553ff260..0e142ca8bf 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190222 +%define release 190223 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 6e8c3e5e17..0c572c6b93 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190222 +%define release 190223 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index 66e4dff894..fdf0028dc4 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190222" +PI_BUILD="190223" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index 2adedc7f16..2272b46e86 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190222} +{190223} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index fc84e962be..553ad230b1 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190222)") +#define PANDORA_VERSION ("7.0NG.731(Build 190223)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index f7c69dbdb2..75f020eb2e 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190222))" + VALUE "ProductVersion", "(7.0NG.731(Build 190223))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 7909803fb6..f122760130 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190222 +Version: 7.0NG.731-190223 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 13c27c15d3..2d2270e67c 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190222" +pandora_version="7.0NG.731-190223" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index f4275aa61b..ccb98b98b7 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190222'; +$build_version = 'PC190223'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index b297466f99..2cb96ea7cc 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@
                [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 432a065155..6d3c447253 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190222 +%define release 190223 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 16e17d6699..8b3fac8f4f 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190222 +%define release 190223 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index 246c29ace3..f137c8589a 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190222" +PI_BUILD="190223" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 1c957ce03c..492d51efd7 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190222"; +my $version = "7.0NG.731 PS190223"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 61ae16c656..6b786f78ba 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190222"; +my $version = "7.0NG.731 PS190223"; # save program name for logging my $progname = basename($0); From 6105ef1116c1d1cccb89910b668f355b0539f4d1 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Sat, 23 Feb 2019 00:35:59 +0100 Subject: [PATCH 232/249] Quick fix DiscoveryServer Former-commit-id: 0dea07b53b993a82d233acec71a45f7a241a205e --- pandora_server/lib/PandoraFMS/DiscoveryServer.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm index 7557ef8320..bc4e1caa73 100644 --- a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -276,9 +276,9 @@ sub exec_recon_script ($$$) { if (-x $command) { my $exec_output = `$command $args`; - logger ($pa_config, "Execution output: \n", $exec_output); + logger($pa_config, "Execution output: \n". $exec_output, 10); } else { - logger ($pa_config, "Cannot execute recon task command $command."); + logger($pa_config, "Cannot execute recon task command $command.", 10); } # Only update the timestamp in case something went wrong. The script should set the status. From 797f922748b825d46cf3d4a749ec340b36afc672 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Sat, 23 Feb 2019 12:13:54 +0100 Subject: [PATCH 233/249] Discovery Tasklist minor fixes Former-commit-id: 693f181168f74f93ad9a3ce628d0defd9ef72d02 --- pandora_console/godmode/servers/discovery.php | 13 +---- .../wizards/DiscoveryTaskList.class.php | 53 +++++++++++++++---- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index d7ee26de86..9606e296bf 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -125,19 +125,10 @@ if ($classname_selected !== null) { $wiz = new $classname_selected($page); $result = $wiz->run(); if (is_array($result) === true) { - if ($result['result'] === 0) { - // Success. - ui_print_success_message($result['msg']); - // TODO: Show task progress before redirect to main discovery menu. - } else { - // Failed. - ui_print_error_message($result['msg']); - } - - // Redirect to Tasklist. + // Redirect control and messages to DiscoveryTasklist. $classname_selected = 'DiscoveryTaskList'; $wiz = new $classname_selected($page); - $result = $wiz->run(); + $result = $wiz->run($result['msg'], $result['result']); } } diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index c9ecaa8ec9..8112ff3a19 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -74,12 +74,30 @@ class DiscoveryTaskList extends Wizard * * @return mixed Returns null if wizard is ongoing. Result if done. */ - public function run() + public function run($message='', $status=null) { global $config; // Load styles. parent::run(); + $this->prepareBreadcrum( + [ + [ + 'link' => 'index.php?sec=gservers&sec2=godmode/servers/discovery', + 'label' => 'Discovery', + ], + ] + ); + + $this->printHeader(); + + // Show redirected messages from discovery.php. + if ($status === 0) { + ui_print_success_message($message); + } else if ($status !== null) { + ui_print_error_message($message); + } + $force_run = (bool) get_parameter('force_run'); if ($force_run === true) { return $this->forceConsoleTask(); @@ -349,7 +367,7 @@ class DiscoveryTaskList extends Wizard $table->head[4] = __('Status'); $table->align[4] = 'left'; - $table->head[5] = __('Template'); + $table->head[5] = __('Task type'); $table->align[5] = 'left'; $table->head[6] = __('Progress'); @@ -370,15 +388,24 @@ class DiscoveryTaskList extends Wizard ).'">'; $data[0] .= html_print_image('images/target.png', true, ['title' => __('Force')]); $data[0] .= ''; + } else if ($task['disabled'] == 2) { + $data[0] = ui_print_help_tip( + __('This task has not been completely defined, please edit it'), + true + ); } else { $data[0] = ''; } $data[1] = ''.$task['name'].''; - $data[2] = human_time_description_raw( - $task['interval_sweep'] - ); + if ($task['interval_sweep'] > 0) { + $data[2] = human_time_description_raw( + $task['interval_sweep'] + ); + } else { + $data[2] = __('Manual'); + } if ($task['id_recon_script'] == 0) { $data[3] = $task['subnet']; @@ -393,11 +420,11 @@ class DiscoveryTaskList extends Wizard } if ($task['id_recon_script'] == 0) { - // Network recon task. + // Discovery NetScan. $data[5] = html_print_image( 'images/network.png', true, - ['title' => __('Network recon task')] + ['title' => __('Discovery NetScan')] ).'  '; $data[5] .= network_profiles_get_name( $task['id_network_profile'] @@ -428,10 +455,14 @@ class DiscoveryTaskList extends Wizard ); } - $data[7] = ui_print_timestamp( - $task['utimestamp'], - true - ); + if ($task['utimestamp'] > 0) { + $data[7] = ui_print_timestamp( + $task['utimestamp'], + true + ); + } else { + $data[7] = __('Not executed yet'); + } if (check_acl( $config['id_user'], From a49f68e96b0cc49718fc7cfd9c912ea637b32739 Mon Sep 17 00:00:00 2001 From: artica Date: Sun, 24 Feb 2019 00:01:50 +0100 Subject: [PATCH 234/249] Auto-updated build strings. Former-commit-id: ee007a4042fe893b73e088abd7a7b6cd0bdc45d2 --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 28b7562888..627d0a04fc 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190223 +Version: 7.0NG.731-190224 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 9560c00f1b..2fea9ebfc6 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190223" +pandora_version="7.0NG.731-190224" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 3c25dbba4e..0e8c0a45fe 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190223'; +use constant AGENT_BUILD => '190224'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 0e142ca8bf..fca23d4657 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190223 +%define release 190224 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 0c572c6b93..707d664a64 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190223 +%define release 190224 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index fdf0028dc4..b6ce372e3f 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190223" +PI_BUILD="190224" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index 2272b46e86..ae1850232c 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190223} +{190224} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 553ad230b1..1b17129dd7 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190223)") +#define PANDORA_VERSION ("7.0NG.731(Build 190224)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 75f020eb2e..fca37ae1c4 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190223))" + VALUE "ProductVersion", "(7.0NG.731(Build 190224))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index f122760130..388c720b4f 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190223 +Version: 7.0NG.731-190224 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 2d2270e67c..2ca685c7dc 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190223" +pandora_version="7.0NG.731-190224" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index ccb98b98b7..01d9e15be0 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190223'; +$build_version = 'PC190224'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index 2cb96ea7cc..02100b39b6 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@
                [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 6d3c447253..7b3ee79268 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190223 +%define release 190224 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 8b3fac8f4f..92c2c7a823 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190223 +%define release 190224 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index f137c8589a..fa42f49086 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190223" +PI_BUILD="190224" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 492d51efd7..b9a42d89f1 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190223"; +my $version = "7.0NG.731 PS190224"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 6b786f78ba..8a7ec02805 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190223"; +my $version = "7.0NG.731 PS190224"; # save program name for logging my $progname = basename($0); From 9753faa17a61f3f4f96521c6c29a606d41b56022 Mon Sep 17 00:00:00 2001 From: artica Date: Mon, 25 Feb 2019 00:01:36 +0100 Subject: [PATCH 235/249] Auto-updated build strings. Former-commit-id: 01fee147745dfd638487449f20211abd8e83b71e --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 2 +- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 627d0a04fc..6af9c8cebe 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190224 +Version: 7.0NG.731-190225 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 2fea9ebfc6..885349a84a 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190224" +pandora_version="7.0NG.731-190225" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 0e8c0a45fe..1b0beb6592 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190224'; +use constant AGENT_BUILD => '190225'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index fca23d4657..479ec78469 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190224 +%define release 190225 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 707d664a64..958ec6edb9 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190224 +%define release 190225 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index b6ce372e3f..324749839f 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190224" +PI_BUILD="190225" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index ae1850232c..a9f356dcf9 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190224} +{190225} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 1b17129dd7..1cdb4731e9 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190224)") +#define PANDORA_VERSION ("7.0NG.731(Build 190225)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index fca37ae1c4..4ed34ac285 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190224))" + VALUE "ProductVersion", "(7.0NG.731(Build 190225))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 388c720b4f..84bd5108d8 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190224 +Version: 7.0NG.731-190225 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 2ca685c7dc..ed29060a70 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190224" +pandora_version="7.0NG.731-190225" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 01d9e15be0..42306dbfc1 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190224'; +$build_version = 'PC190225'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index 02100b39b6..fa60433a98 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -129,7 +129,7 @@
                [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 7b3ee79268..5da2297eb0 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190224 +%define release 190225 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 92c2c7a823..e56f0ab35b 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190224 +%define release 190225 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index fa42f49086..d06e349eb9 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190224" +PI_BUILD="190225" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index b9a42d89f1..881ded4495 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190224"; +my $version = "7.0NG.731 PS190225"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 8a7ec02805..7a04ff00f1 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190224"; +my $version = "7.0NG.731 PS190225"; # save program name for logging my $progname = basename($0); From 13e49f92db5f4cfc179bc945f2be1dfafb2e8db4 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 25 Feb 2019 11:09:29 +0100 Subject: [PATCH 236/249] added pcm_client and updated vmware-plugin path in pandora_update_version Former-commit-id: 378948c8f5b90133b67b40ef5ea43f269bc0f6ea --- extras/pandora_update_version.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extras/pandora_update_version.sh b/extras/pandora_update_version.sh index 90c4bf6519..10e5534459 100755 --- a/extras/pandora_update_version.sh +++ b/extras/pandora_update_version.sh @@ -54,7 +54,8 @@ AGENT_WIN_FILE="$CODEHOME/pandora_agents/win32/pandora.cc" AGENT_WIN_MPI_FILE="$CODEHOME/pandora_agents/win32/installer/pandora.mpi" AGENT_WIN_RC_FILE="$CODEHOME/pandora_agents/win32/versioninfo.rc" SATELLITE_FILE="$PANDHOME_ENT/satellite_server/satellite_server.pl" -PERL_PLUGIN_FILES="$PANDHOME_ENT/pandora_server/util/plugin/vmware-plugin.pl \ +PERL_PLUGIN_FILES="$PANDHOME_ENT/pandora_server/util/recon_script/vmware-plugin.pl \ +$PANDHOME_ENT/pandora_server/util/recon_script/pcm_client.pl \ $PANDHOME_ENT/pandora_plugins/NGINX/nginx_requests_queued.pl \ $PANDHOME_ENT/pandora_plugins/Sybase/sybase_plugin.pl \ $PANDHOME_ENT/pandora_plugins/SNMP/dynamic_snmp.pl \ From 4da8f54f8482e0694c0d0007a6df2d4e1f4aa977 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 25 Feb 2019 11:29:39 +0100 Subject: [PATCH 237/249] Updated message warnings in Tasklist Former-commit-id: 9f8324e4f882e14451bda7034b1ff081c14a7a41 --- .../wizards/DiscoveryTaskList.class.php | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index 8112ff3a19..934279ea47 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -113,6 +113,40 @@ class DiscoveryTaskList extends Wizard return $this->deleteTask(); } + if (enterprise_installed()) { + // This check only applies to enterprise users. + // Check if DiscoveryCronTasks is running. Warn user if not. + if ($config['cron_last_run'] == 0 + || (get_system_time() - $config['cron_last_run']) > 3600 + ) { + $message_conf_cron = __('DiscoveryConsoleTasks is not running properly'); + if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { + $message_conf_cron .= __('Discovery relies on a proper setup of cron, the time-based scheduling service'); + $message_conf_cron .= '. '.__('Please, add the following line to your crontab file:'); + $message_conf_cron .= '
                * * * * * <user> wget -q -O - --no-check-certificate ';
                +                    $message_conf_cron .= str_replace(
                +                        ENTERPRISE_DIR.'/meta/',
                +                        '',
                +                        ui_get_full_url(false)
                +                    );
                +                    $message_conf_cron .= ENTERPRISE_DIR.'/'.EXTENSIONS_DIR;
                +                    $message_conf_cron .= '/cron/cron.php >> ';
                +                    $message_conf_cron .= $config['homedir'].'/pandora_console.log
                '; + } + + if (isset($config['cron_last_run']) === true + && $config['cron_last_run'] > 0 + ) { + $message_conf_cron .= '

                '.__('Last execution').': '; + $message_conf_cron .= date('Y/m/d H:i:s', $config['cron_last_run']).'

                '; + $message_conf_cron .= '

                '; + $message_conf_cron .= __('Please check process is no locked.').'

                '; + } + + ui_print_warning_message($message_conf_cron, '', false); + } + } + $ret = $this->showListConsoleTask(); $ret2 = $this->showList(); From 1f26a8c4b351f979401ec8d1021f04ad0d308188 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 25 Feb 2019 11:30:09 +0100 Subject: [PATCH 238/249] Updated message warnings in Tasklist Former-commit-id: beb870813818ff8a7000ffaac7e09f326f0bf253 --- pandora_console/godmode/wizards/DiscoveryTaskList.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index 934279ea47..9f7c416854 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -119,7 +119,7 @@ class DiscoveryTaskList extends Wizard if ($config['cron_last_run'] == 0 || (get_system_time() - $config['cron_last_run']) > 3600 ) { - $message_conf_cron = __('DiscoveryConsoleTasks is not running properly'); + $message_conf_cron = __('DiscoveryConsoleTasks is not running properly').'. '; if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { $message_conf_cron .= __('Discovery relies on a proper setup of cron, the time-based scheduling service'); $message_conf_cron .= '. '.__('Please, add the following line to your crontab file:'); From be7eadeb2c01f008f7c788b4099218746a1250c5 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Mon, 25 Feb 2019 11:32:26 +0100 Subject: [PATCH 239/249] extend status change functionality in monitor detail view custom fields Former-commit-id: e48ae88416f50b47aac79ae28b9b4bcd08ebdf73 --- .../godmode/agentes/status_monitor_custom_fields.php | 4 ++-- pandora_console/operation/agentes/status_monitor.php | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/pandora_console/godmode/agentes/status_monitor_custom_fields.php b/pandora_console/godmode/agentes/status_monitor_custom_fields.php index e01839c40a..2c82c1e4f7 100644 --- a/pandora_console/godmode/agentes/status_monitor_custom_fields.php +++ b/pandora_console/godmode/agentes/status_monitor_custom_fields.php @@ -102,7 +102,7 @@ if ($fields_selected[0]!='') { $result = __('Timestamp'); break; case 'to_critical': - $result = __('Went to critical'); + $result = __('Last status change'); break; } $result_selected[$field_selected] = $result; @@ -138,7 +138,7 @@ $fields_available['graph'] = __('Graph'); $fields_available['warn'] = __('Warn'); $fields_available['data'] = __('Data'); $fields_available['timestamp'] = __('Timestamp'); -$fields_available['to_critical'] = __('Went to critical'); +$fields_available['to_critical'] = __('Last status change'); //remove fields already selected foreach ($fields_available as $key=>$available) { diff --git a/pandora_console/operation/agentes/status_monitor.php b/pandora_console/operation/agentes/status_monitor.php index 3bb1a6b2b2..b0a3762d72 100644 --- a/pandora_console/operation/agentes/status_monitor.php +++ b/pandora_console/operation/agentes/status_monitor.php @@ -1144,7 +1144,7 @@ if (!empty($result)) { } if (in_array('to_critical', $show_fields)) { - $table->head[11] = __('Went to critical'); + $table->head[11] = __('Last status change'); } $id_type_web_content_string = db_get_value('id_tipo', 'ttipo_modulo', @@ -1635,7 +1635,6 @@ if (!empty($result)) { $change_status_timestamp = db_get_sql ('SELECT utimestamp FROM tevento WHERE id_agentmodule=' . $row['id_agente_modulo'] . ' ORDER BY utimestamp DESC'); $data[11] = ui_print_timestamp ($change_status_timestamp, true, $option); - } array_push ($table->data, $data); From cdca720d9abb9a8d388ac5f5118baf0cf8496860 Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Mon, 25 Feb 2019 14:41:27 +0100 Subject: [PATCH 240/249] minor fix user_edig Former-commit-id: 2e13b75edd5625fa2d1d6d9360d55a19f0992ac0 --- pandora_console/godmode/servers/discovery.php | 15 --------------- pandora_console/operation/users/user_edit.php | 2 +- 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 9606e296bf..41f7fd1ffc 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -96,21 +96,6 @@ foreach ($classes as $classpath) { include_once $classpath; } -// Load enterprise wizards. -if (enterprise_installed() === true) { - $enterprise_classes = glob( - $config['homedir'].'/'.ENTERPRISE_DIR.'/wizards/*.class.php' - ); - foreach ($enterprise_classes as $classpath) { - $r = enterprise_include_once( - 'wizards/'.basename($classpath) - ); - } -} - -// Combine class paths. -$classes = array_merge($classes, $enterprise_classes); - // Sort output. uasort($classes, 'cl_load_cmp'); diff --git a/pandora_console/operation/users/user_edit.php b/pandora_console/operation/users/user_edit.php index 46ebe87999..3e3338ff96 100644 --- a/pandora_console/operation/users/user_edit.php +++ b/pandora_console/operation/users/user_edit.php @@ -600,7 +600,7 @@ $table->rowclass[] = ''; $table->rowstyle[] = ''; $table->data[] = $data; -echo '
                '; +echo ''; html_print_table($table); From 67e53bf7a7894006b5e06dccd135e634b16b34e0 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Mon, 25 Feb 2019 16:15:17 +0100 Subject: [PATCH 241/249] add new way of importing css for treeview Former-commit-id: d88bb38ac7d20ab5f554cfb1399b17ddf6f62fb2 --- pandora_console/include/styles/pandora.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 180c187db0..70a9c4920e 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -21,8 +21,8 @@ Description: The default Pandora FMS theme layout */ /* Tree view styles */ -@import url(tree.css); -@import url(fixed-bottom-box.css); +/*@import url(tree.css); +@import url(fixed-bottom-box.css);*/ /* * --------------------------------------------------------------------- From ac9452583a6103eaa8134f747f0f55812bc063f3 Mon Sep 17 00:00:00 2001 From: fermin831 Date: Mon, 25 Feb 2019 16:50:27 +0100 Subject: [PATCH 242/249] Added no data to show to some graphs where id not found Former-commit-id: 1697a482e80521666f679eb18d2f44fc3975e304 --- pandora_console/include/functions_graph.php | 25 ++++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/pandora_console/include/functions_graph.php b/pandora_console/include/functions_graph.php index cbdada69b9..71049d7804 100644 --- a/pandora_console/include/functions_graph.php +++ b/pandora_console/include/functions_graph.php @@ -549,12 +549,6 @@ function grafico_modulo_sparse($params) return false; } - if (!isset($params['agent_module_id'])) { - return false; - } else { - $agent_module_id = $params['agent_module_id']; - } - if (!isset($params['period'])) { return false; } @@ -710,6 +704,12 @@ function grafico_modulo_sparse($params) $params['projection'] = false; } + if (!isset($params['agent_module_id'])) { + return graph_nodata_image($params['width'], $params['height']); + } else { + $agent_module_id = $params['agent_module_id']; + } + // XXXX Configurable $params['grid_color'] = '#C1C1C1'; $params['legend_color'] = '#636363'; @@ -1318,6 +1318,10 @@ function graphic_combined_module( $array_data = []; foreach ($module_list as $key => $agent_module_id) { + if ((bool) $agent_module_id === false) { + continue; + } + if (is_metaconsole() && $params_combined['type_report'] == 'automatic_graph') { $server = metaconsole_get_connection_by_id($agent_module_id['server']); if (metaconsole_connect($server) != NOERR) { @@ -1394,6 +1398,15 @@ function graphic_combined_module( } } + if (empty($array_data)) { + if ($params_combined['return']) { + return graph_nodata_image($width, $height); + } + + echo graph_nodata_image($width, $height); + return false; + } + if ($params_combined['projection']) { // If projection doesn't have data then don't draw graph if ($output_projection != null) { From db5d2ceee142a2154e6a2a3b747cbd9e5e08edbe Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Mon, 25 Feb 2019 17:04:07 +0100 Subject: [PATCH 243/249] fix bad routes in services treeview Former-commit-id: 27bfcca5a7e0f7c3929e2a1f449c0f1d318891c9 --- pandora_console/include/class/TreeService.class.php | 4 ++-- .../include/javascript/tree/TreeController.js | 9 ++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/pandora_console/include/class/TreeService.class.php b/pandora_console/include/class/TreeService.class.php index bbddc8dc2a..d211cd1055 100644 --- a/pandora_console/include/class/TreeService.class.php +++ b/pandora_console/include/class/TreeService.class.php @@ -161,7 +161,7 @@ class TreeService extends Tree { $services[$service['id']]['counters'] = array('total_services'=>$service['total_services'], 'total_agents'=>$service['total_agents'], 'total_modules'=>$service['total_modules']); $services[$service['id']]['name'] = $service['name']; $services[$service['id']]['id'] = $service['id']; - $services[$service['id']]['serviceDetail']='http://localhost/pandora_console/index.php?sec=network&sec2=enterprise/operation/services/services&tab=service_map&id_service='.(int)$service['id']; + $services[$service['id']]['serviceDetail']='index.php?sec=network&sec2=enterprise/operation/services/services&tab=service_map&id_service='.(int)$service['id']; } return $services; @@ -241,7 +241,7 @@ class TreeService extends Tree { $service_stats[$service['id']]['rootType'] = $service['rootType']; $service_stats[$service['id']]['type'] = 'services'; $service_stats[$service['id']]['children']=array(); - $service_stats[$service['id']]['serviceDetail']='http://localhost/pandora_console/index.php?sec=network&sec2=enterprise/operation/services/services&tab=service_map&id_service='.(int)$service['id']; + $service_stats[$service['id']]['serviceDetail']='index.php?sec=network&sec2=enterprise/operation/services/services&tab=service_map&id_service='.(int)$service['id']; $service_stats[$service['id']]['counters']=array('total_services'=>$service['total_services'], 'total_agents'=>$service['total_agents'], 'total_modules'=>$service['total_modules']); } diff --git a/pandora_console/include/javascript/tree/TreeController.js b/pandora_console/include/javascript/tree/TreeController.js index 3fab4f6dab..3e177f3ae9 100644 --- a/pandora_console/include/javascript/tree/TreeController.js +++ b/pandora_console/include/javascript/tree/TreeController.js @@ -523,7 +523,8 @@ var TreeController = { if (typeof element.eventAgent != 'undefined') { $content.append(''); - var $eventImage = $(''); + var $eventImage = $(' '); $eventImage.addClass("agent-alerts-fired"); $eventImage .click(function (e) { @@ -550,7 +551,8 @@ var TreeController = { } - var $serviceDetailImage = $(''); + var $serviceDetailImage = $(' '); if (typeof element.serviceDetail != 'undefined') { @@ -585,7 +587,8 @@ var TreeController = { if (typeof element.eventModule != 'undefined') { $content.append(''); - var $moduleImage = $(''); + var $moduleImage = $(' '); $moduleImage .click(function (e) { e.preventDefault(); From 16f14746917d29b7c8a9b5016c4e6b18438bb0a4 Mon Sep 17 00:00:00 2001 From: Daniel Maya Date: Mon, 25 Feb 2019 17:45:37 +0100 Subject: [PATCH 244/249] Added models in tlog_graph_models Former-commit-id: 76d6f1358677c02eab4681a1bb290fda0476c91b --- pandora_console/extras/mr/25.sql | 24 ++++++++++++++++++ .../pandoradb_migrate_6.0_to_7.0.mysql.sql | 25 ++++++++++++++++++- pandora_console/pandoradb_data.sql | 24 ++++++++++++++++++ 3 files changed, 72 insertions(+), 1 deletion(-) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index 3f0c2f7c0b..828e6972e3 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -118,4 +118,28 @@ INSERT INTO `tnotification_source_user` (`id_source`, `id_user`, `enabled`, `als INSERT INTO `tnotification_source_group` SELECT `id`,0 FROM `tnotification_source` WHERE `description`="Message"; INSERT INTO `tnotification_user` (`id_mensaje`, `id_user`) SELECT `id_mensaje`, `id_usuario_destino` FROM `tmensajes` WHERE `id_usuario_destino` != ''; +INSERT INTO tlog_graph_models (`title`,`regexp`,`fields`,`average`) VALUES ('Apache accesses per client and status', +'(.*?)\ -.*1.1"\ (\d+)\ \d+', +'host,status', 1); + +INSERT INTO tlog_graph_models (`title`,`regexp`,`fields`,`average`) VALUES ('Apache time per requester and html code', +'(.*?)\ -.*1.1"\ (\d+)\ (\d+)', +'origin,respose,_time_', 1); + +INSERT INTO tlog_graph_models (`title`,`regexp`,`fields`,`average`) VALUES ('Count output', +'.*', +'Coincidences', 0); + +INSERT INTO tlog_graph_models (`title`,`regexp`,`fields`,`average`) VALUES ('Events replicated to metaconsole', +'.* (.*?) .* (\d+) events replicated to metaconsole', +'server,_events_', 0); + +INSERT INTO tlog_graph_models (`title`,`regexp`,`fields`,`average`) VALUES ('Pages with warnings', +'PHP Warning:.*in (.*?) on', +'page', 0); + +INSERT INTO tlog_graph_models (`title`,`regexp`,`fields`,`average`) VALUES ('Users login', +'Starting Session \d+\ of user (.*)', +'user', 0); + COMMIT; diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 21e46e3697..8e30b63487 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1820,7 +1820,30 @@ CREATE TABLE IF NOT EXISTS `tlog_graph_models` ( INSERT INTO tlog_graph_models VALUES (1, 'Apache log model', '^.*?\s+.*".*?\s(\/.*?)\?.*1.1"\s+(.*?)\s+(.*?)\s+', 'pagina, html_err_code, _tiempo_', 1); - + +INSERT INTO tlog_graph_models VALUES (2, 'Apache accesses per client and status', +'(.*?)\ -.*1.1"\ (\d+)\ \d+', +'host,status', 1); + +INSERT INTO tlog_graph_models VALUES (3, 'Apache time per requester and html code', +'(.*?)\ -.*1.1"\ (\d+)\ (\d+)', +'origin,respose,_time_', 1); + +INSERT INTO tlog_graph_models VALUES (4, 'Count output', +'.*', +'Coincidences', 0); + +INSERT INTO tlog_graph_models VALUES (5, 'Events replicated to metaconsole', +'.* (.*?) .* (\d+) events replicated to metaconsole', +'server,_events_', 0); + +INSERT INTO tlog_graph_models VALUES (6, 'Pages with warnings', +'PHP Warning:.*in (.*?) on', +'page', 0); + +INSERT INTO tlog_graph_models VALUES (7, 'Users login', +'Starting Session \d+\ of user (.*)', +'user', 0); -- ----------------------------------------------------- -- Add column in table `treport` -- ----------------------------------------------------- diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index 4f9c9c54ec..f5da1f12fa 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -1269,6 +1269,30 @@ INSERT INTO tlog_graph_models VALUES (1, 'Apache log model', '^.*?\s+.*".*?\s(\/.*?)\?.*1.1"\s+(.*?)\s+(.*?)\s+', 'pagina, html_err_code, _tiempo_', 1); +INSERT INTO tlog_graph_models VALUES (2, 'Apache accesses per client and status', +'(.*?)\ -.*1.1"\ (\d+)\ \d+', +'host,status', 1); + +INSERT INTO tlog_graph_models VALUES (3, 'Apache time per requester and html code', +'(.*?)\ -.*1.1"\ (\d+)\ (\d+)', +'origin,respose,_time_', 1); + +INSERT INTO tlog_graph_models VALUES (4, 'Count output', +'.*', +'Coincidences', 0); + +INSERT INTO tlog_graph_models VALUES (5, 'Events replicated to metaconsole', +'.* (.*?) .* (\d+) events replicated to metaconsole', +'server,_events_', 0); + +INSERT INTO tlog_graph_models VALUES (6, 'Pages with warnings', +'PHP Warning:.*in (.*?) on', +'page', 0); + +INSERT INTO tlog_graph_models VALUES (7, 'Users login', +'Starting Session \d+\ of user (.*)', +'user', 0); + -- -- Dumping data for table `tnotification_source` -- From 13cbc78fddf6ca417efb16e553f9a0551051b7e1 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Mon, 25 Feb 2019 18:41:24 +0100 Subject: [PATCH 245/249] change mr and migrate for table twidget Former-commit-id: d7d07f5e036a8dd81debcb974bd42217e2b59b26 --- pandora_console/extras/mr/25.sql | 5 +++++ .../extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 1 + 2 files changed, 6 insertions(+) create mode 100644 pandora_console/extras/mr/25.sql diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql new file mode 100644 index 0000000000..29da43216c --- /dev/null +++ b/pandora_console/extras/mr/25.sql @@ -0,0 +1,5 @@ +START TRANSACTION; + +UPDATE `twidget` SET `unique_name`='example2' WHERE `class_name` LIKE 'WelcomeWidget'; + +COMMIT; diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index bedb9927cd..bdbb4d958f 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1412,6 +1412,7 @@ ALTER TABLE trecon_task ADD `vlan_enabled` int(2) unsigned default '0'; -- --------------------------------------------------------------------- UPDATE twidget_dashboard SET id_widget = (SELECT id FROM twidget WHERE unique_name = 'graph_module_histogram') WHERE id_widget = (SELECT id FROM twidget WHERE unique_name = 'graph_availability'); DELETE FROM twidget WHERE unique_name = 'graph_availability'; +UPDATE `twidget` SET `unique_name`='example2' WHERE `class_name` LIKE 'WelcomeWidget'; -- --------------------------------------------------------------------- -- Table `tbackup` (Extension table. Modify only if exists) From 4bf746956509a9b2de4275ffa100ba3fca643857 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Mon, 25 Feb 2019 18:42:52 +0100 Subject: [PATCH 246/249] change mr and migrate for table twidget Former-commit-id: fb7bfc3771b2c019a7e70771d4e5bd47043ba99b --- pandora_console/extras/mr/25.sql | 2 +- pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pandora_console/extras/mr/25.sql b/pandora_console/extras/mr/25.sql index 29da43216c..35a0587abb 100644 --- a/pandora_console/extras/mr/25.sql +++ b/pandora_console/extras/mr/25.sql @@ -1,5 +1,5 @@ START TRANSACTION; -UPDATE `twidget` SET `unique_name`='example2' WHERE `class_name` LIKE 'WelcomeWidget'; +UPDATE `twidget` SET `unique_name`='example' WHERE `class_name` LIKE 'WelcomeWidget'; COMMIT; diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index bdbb4d958f..0b3292fd02 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1412,7 +1412,7 @@ ALTER TABLE trecon_task ADD `vlan_enabled` int(2) unsigned default '0'; -- --------------------------------------------------------------------- UPDATE twidget_dashboard SET id_widget = (SELECT id FROM twidget WHERE unique_name = 'graph_module_histogram') WHERE id_widget = (SELECT id FROM twidget WHERE unique_name = 'graph_availability'); DELETE FROM twidget WHERE unique_name = 'graph_availability'; -UPDATE `twidget` SET `unique_name`='example2' WHERE `class_name` LIKE 'WelcomeWidget'; +UPDATE `twidget` SET `unique_name`='example' WHERE `class_name` LIKE 'WelcomeWidget'; -- --------------------------------------------------------------------- -- Table `tbackup` (Extension table. Modify only if exists) From 88202977fa8baf2cd3d989b3aaf2a61866f333f1 Mon Sep 17 00:00:00 2001 From: artica Date: Tue, 26 Feb 2019 00:01:57 +0100 Subject: [PATCH 247/249] Auto-updated build strings. Former-commit-id: e3e3a3aba908a64a4743bd8b18337510e0c6e609 --- pandora_agents/unix/DEBIAN/control | 2 +- pandora_agents/unix/DEBIAN/make_deb_package.sh | 2 +- pandora_agents/unix/pandora_agent | 2 +- pandora_agents/unix/pandora_agent.redhat.spec | 2 +- pandora_agents/unix/pandora_agent.spec | 2 +- pandora_agents/unix/pandora_agent_installer | 2 +- pandora_agents/win32/installer/pandora.mpi | 2 +- pandora_agents/win32/pandora.cc | 2 +- pandora_agents/win32/versioninfo.rc | 2 +- pandora_console/DEBIAN/control | 2 +- pandora_console/DEBIAN/make_deb_package.sh | 2 +- pandora_console/include/config_process.php | 2 +- pandora_console/install.php | 4 ++-- pandora_console/pandora_console.redhat.spec | 2 +- pandora_console/pandora_console.spec | 2 +- pandora_server/DEBIAN/control | 2 +- pandora_server/DEBIAN/make_deb_package.sh | 2 +- pandora_server/lib/PandoraFMS/Config.pm | 2 +- pandora_server/lib/PandoraFMS/PluginTools.pm | 2 +- pandora_server/pandora_server.redhat.spec | 2 +- pandora_server/pandora_server.spec | 2 +- pandora_server/pandora_server_installer | 2 +- pandora_server/util/pandora_db.pl | 2 +- pandora_server/util/pandora_manage.pl | 2 +- 24 files changed, 25 insertions(+), 25 deletions(-) diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 6af9c8cebe..e9d22f629b 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.731-190225 +Version: 7.0NG.731-190226 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 885349a84a..64c13e926e 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190225" +pandora_version="7.0NG.731-190226" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 1b0beb6592..bb7d98e310 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -42,7 +42,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.731'; -use constant AGENT_BUILD => '190225'; +use constant AGENT_BUILD => '190226'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 479ec78469..d4e33903d4 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190225 +%define release 190226 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 958ec6edb9..87436366bb 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.731 -%define release 190225 +%define release 190226 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index 324749839f..3ff9b6a963 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190225" +PI_BUILD="190226" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index a9f356dcf9..abdf2e0ce4 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190225} +{190226} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 1cdb4731e9..01f027089d 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.731(Build 190225)") +#define PANDORA_VERSION ("7.0NG.731(Build 190226)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 4ed34ac285..cb30f2163d 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.731(Build 190225))" + VALUE "ProductVersion", "(7.0NG.731(Build 190226))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 84bd5108d8..fe87752dff 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.731-190225 +Version: 7.0NG.731-190226 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index ed29060a70..60d17de09e 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.731-190225" +pandora_version="7.0NG.731-190226" package_pear=0 package_pandora=1 diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 42306dbfc1..81ddb9f336 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,7 +20,7 @@ /** * Pandora build version and version */ -$build_version = 'PC190225'; +$build_version = 'PC190226'; $pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. diff --git a/pandora_console/install.php b/pandora_console/install.php index 063fa77556..ec9414274a 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -128,8 +128,8 @@
                [ qw() ] ); diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 5da2297eb0..076f19497a 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190225 +%define release 190226 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index e56f0ab35b..e3adf2711e 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -3,7 +3,7 @@ # %define name pandorafms_server %define version 7.0NG.731 -%define release 190225 +%define release 190226 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index d06e349eb9..55915d85a0 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.731" -PI_BUILD="190225" +PI_BUILD="190226" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 5885720b13..c8eb037f7a 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.731 PS190225"; +my $version = "7.0NG.731 PS190226"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 7a04ff00f1..33a9c811b8 100644 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.731 PS190225"; +my $version = "7.0NG.731 PS190226"; # save program name for logging my $progname = basename($0); From c38ac4b837aaa8ecb2a1a3de489889243ef8864e Mon Sep 17 00:00:00 2001 From: fbsanchez Date: Tue, 26 Feb 2019 10:34:37 +0100 Subject: [PATCH 248/249] Updated breadcrum Former-commit-id: 51c14ea50e6c7d419d610ef1b52c4769214495ef --- pandora_console/godmode/wizards/HostDevices.class.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index 6e31299b9a..aa5c94666c 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -476,6 +476,10 @@ class HostDevices extends Wizard $task_url = '&task='.$this->task['id_rt']; } + $breadcrum[] = [ + 'link' => 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=hd', + 'label' => __($this->label), + ]; for ($i = 0; $i < $this->maxPagesNetScan; $i++) { $breadcrum[] = [ 'link' => 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=hd&mode=netscan&page='.$i.$task_url, @@ -710,9 +714,6 @@ $("select#interval_manual_defined").change(function() { // XXX: Could be improved validating inputs before continue (JS) // Print NetScan page 0. $this->printForm($form); - $this->printGoBackButton( - $this->url.'&page='.($this->page - 1).$task_url - ); } } From 7791639b3545145dd9cd2a137dc93d76dd73cb67 Mon Sep 17 00:00:00 2001 From: alejandro-campos Date: Tue, 26 Feb 2019 13:31:35 +0100 Subject: [PATCH 249/249] fix bad image routes Former-commit-id: 236701131f5c2f5b11c01b878d8a04b71f76ddd3 --- .../include/class/TreeService.class.php | 24 +++++++++---------- .../include/javascript/tree/TreeController.js | 14 ++++++----- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/pandora_console/include/class/TreeService.class.php b/pandora_console/include/class/TreeService.class.php index d211cd1055..b55643219d 100644 --- a/pandora_console/include/class/TreeService.class.php +++ b/pandora_console/include/class/TreeService.class.php @@ -91,20 +91,20 @@ class TreeService extends Tree { switch ($status) { case SERVICE_STATUS_NORMAL: - $processed_items[$row['id']]['statusImageHTML']='NORMAL status.'; + $processed_items[$row['id']]['statusImageHTML']='NORMAL status.'; break; case SERVICE_STATUS_CRITICAL: - $processed_items[$row['id']]['statusImageHTML']='CRITICAL status.'; + $processed_items[$row['id']]['statusImageHTML']='CRITICAL status.'; break; case SERVICE_STATUS_WARNING: - $processed_items[$row['id']][$key]['statusImageHTML']='WARNING status.'; + $processed_items[$row['id']][$key]['statusImageHTML']='WARNING status.'; break; case SERVICE_STATUS_UNKNOWN: default: - $processed_items[$row['id']]['statusImageHTML']='UNKNOWN status.'; + $processed_items[$row['id']]['statusImageHTML']='UNKNOWN status.'; break; } } @@ -201,16 +201,16 @@ class TreeService extends Tree { foreach ($data_modules as $key => $module) { switch ($module['estado']) { case '0': - $data_modules[$key]['statusImageHTML'] = 'NORMAL status.'; + $data_modules[$key]['statusImageHTML'] = 'NORMAL status.'; break; case '1': - $data_modules[$key]['statusImageHTML'] = 'CRITICAL status.'; + $data_modules[$key]['statusImageHTML'] = 'CRITICAL status.'; break; case '2': - $data_modules[$key]['statusImageHTML'] = 'WARNING status.'; + $data_modules[$key]['statusImageHTML'] = 'WARNING status.'; break; case '4': - $data_modules[$key]['statusImageHTML'] = 'UNKNOWN status.'; + $data_modules[$key]['statusImageHTML'] = 'UNKNOWN status.'; break; default: # code... @@ -267,20 +267,20 @@ class TreeService extends Tree { switch ($status) { case SERVICE_STATUS_NORMAL: - $service_stats[$row['id']]['statusImageHTML']='NORMAL status.'; + $service_stats[$row['id']]['statusImageHTML']='NORMAL status.'; break; case SERVICE_STATUS_CRITICAL: - $service_stats[$row['id']]['statusImageHTML']='CRITICAL status.'; + $service_stats[$row['id']]['statusImageHTML']='CRITICAL status.'; break; case SERVICE_STATUS_WARNING: - $service_stats[$row['id']][$key]['statusImageHTML']='WARNING status.'; + $service_stats[$row['id']][$key]['statusImageHTML']='WARNING status.'; break; case SERVICE_STATUS_UNKNOWN: default: - $service_stats[$row['id']]['statusImageHTML']='UNKNOWN status.'; + $service_stats[$row['id']]['statusImageHTML']='UNKNOWN status.'; break; } } diff --git a/pandora_console/include/javascript/tree/TreeController.js b/pandora_console/include/javascript/tree/TreeController.js index 3e177f3ae9..04e67e670b 100644 --- a/pandora_console/include/javascript/tree/TreeController.js +++ b/pandora_console/include/javascript/tree/TreeController.js @@ -931,12 +931,14 @@ var TreeController = { } controller.recipient.empty(); - controller.recipient.html( - "
                " + - controller.foundMessage + ": " + controller.tree.length + - "
                " + - "
                " - ); + if (controller.tree.length !== undefined) { + controller.recipient.html( + "
                " + + controller.foundMessage + ": " + controller.tree.length + + "
                " + + "
                " + ); + } var $children = _processGroup(this.recipient, this.tree, true); $children.show();