Merge remote-tracking branch 'origin/develop' into ent-7202-fallos-visuales-discovery

This commit is contained in:
marcos 2021-03-29 09:21:04 +02:00
commit 3934096d03
104 changed files with 2186 additions and 399 deletions

View File

@ -1,5 +1,5 @@
package: pandorafms-agent-unix
Version: 7.0NG.752-210325
Version: 7.0NG.752-210329
Architecture: all
Priority: optional
Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.752-210325"
pandora_version="7.0NG.752-210329"
echo "Test if you has the tools for to make the packages."
whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null

View File

@ -1016,7 +1016,7 @@ my $Sem = undef;
my $ThreadSem = undef;
use constant AGENT_VERSION => '7.0NG.752';
use constant AGENT_BUILD => '210325';
use constant AGENT_BUILD => '210329';
# Agent log default file size maximum and instances
use constant DEFAULT_MAX_LOG_SIZE => 600000;

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_agent_unix
%define version 7.0NG.752
%define release 210325
%define release 210329
Summary: Pandora FMS Linux agent, PERL version
Name: %{name}

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_agent_unix
%define version 7.0NG.752
%define release 210325
%define release 210329
Summary: Pandora FMS Linux agent, PERL version
Name: %{name}

View File

@ -10,7 +10,7 @@
# **********************************************************************
PI_VERSION="7.0NG.752"
PI_BUILD="210325"
PI_BUILD="210329"
OS_NAME=`uname -s`
FORCE=0

View File

@ -186,7 +186,7 @@ UpgradeApplicationID
{}
Version
{210325}
{210329}
ViewReadme
{Yes}

View File

@ -30,7 +30,7 @@ using namespace Pandora;
using namespace Pandora_Strutils;
#define PATH_SIZE _MAX_PATH+1
#define PANDORA_VERSION ("7.0NG.752(Build 210325)")
#define PANDORA_VERSION ("7.0NG.752(Build 210329)")
string pandora_path;
string pandora_dir;

View File

@ -11,7 +11,7 @@ BEGIN
VALUE "LegalCopyright", "Artica ST"
VALUE "OriginalFilename", "PandoraAgent.exe"
VALUE "ProductName", "Pandora FMS Windows Agent"
VALUE "ProductVersion", "(7.0NG.752(Build 210325))"
VALUE "ProductVersion", "(7.0NG.752(Build 210329))"
VALUE "FileVersion", "1.0.0.0"
END
END

View File

@ -1,5 +1,5 @@
package: pandorafms-console
Version: 7.0NG.752-210325
Version: 7.0NG.752-210329
Architecture: all
Priority: optional
Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.752-210325"
pandora_version="7.0NG.752-210329"
package_pear=0
package_pandora=1

View File

@ -686,7 +686,7 @@ function mainAgentsModules()
echo '<tr>';
echo "<th width='140px' class='right pdd_r_10px'>".__('Agents').' / '.__('Modules').'</th>';
echo "<th width='140px' class='pdd_r_10px lign_right'>".__('Agents').' / '.__('Modules').'</th>';
if ($hor_offset > 0) {
$new_hor_offset = ($hor_offset - $block);

View File

@ -74,4 +74,7 @@ enterprise/extensions/ipam
enterprise/extensions/disabled/visual_console_manager.php
enterprise/extensions/visual_console_manager.php
pandora_console/extensions/net_tools.php
include/lib/WSManager.php
include/lib/WebSocketServer.php
include/lib/WebSocketUser.php
operation/network/network_explorer.php

View File

@ -27,8 +27,6 @@ if (! check_acl($config['id_user'], 0, 'AR')
return;
}
$update = get_parameter('upd_button', '');
$default = (int) get_parameter('default', 0);
@ -49,7 +47,7 @@ if ($default != 0) {
'value' => $status_monitor_fields,
];
// update 'status_monitor_fields' in tconfig table to keep the value at update.
// Update 'status_monitor_fields' in tconfig table to keep the value at update.
$result = db_process_sql_update(
'tconfig',
$values,
@ -67,7 +65,7 @@ $fields_selected = explode(',', $config['status_monitor_fields']);
$result_selected = [];
// show list of fields selected.
// Show list of fields selected.
if ($fields_selected[0] != '') {
foreach ($fields_selected as $field_selected) {
switch ($field_selected) {
@ -239,7 +237,7 @@ $(document).ready (function () {
if(selected_fields_total === current_fields_size){
display_confirm_dialog(
"<?php echo '<span class="transform_none">'.__('There must be at least one custom field. Timestamp will be set by default').'</span>'; ?>",
"<?php echo '<span style=text-transform:none;font-size:9.5pt;>'.__('There must be at least one custom field. Timestamp will be set by default').'</span>'; ?>",
"<?php echo __('Confirm'); ?>",
"<?php echo __('Cancel'); ?>",
function () {

View File

@ -201,7 +201,7 @@ if ($event_response_id == 0) {
echo '<form method="post" action="index.php?sec=geventos&sec2=godmode/events/events&section=responses&mode=list&action=create_response&amp;pure='.$config['pure'].'">';
html_print_table($table);
if (!defined('METACONSOLE')) {
echo '<div class="w100p right">';
echo '<div class="w100p right_align">';
} else {
echo '<div class="w100p right">';
}
@ -213,7 +213,7 @@ if ($event_response_id == 0) {
echo '<form method="post" action="index.php?sec=geventos&sec2=godmode/events/events&section=responses&mode=list&action=update_response&amp;pure='.$config['pure'].'">';
html_print_table($table);
if (!defined('METACONSOLE')) {
echo '<div class="w100p right">';
echo '<div class="w100p right_align">';
} else {
echo '<div class="w100p right">';
}

View File

@ -86,7 +86,7 @@ foreach ($event_responses as $response) {
html_print_table($table);
echo '<div class="w100p right">';
echo '<div class="w100p right_align">';
echo '<form method="post" action="index.php?sec=geventos&sec2=godmode/events/events&section=responses&mode=editor&amp;pure='.$config['pure'].'">';
html_print_submit_button(
__('Create response'),

View File

@ -536,7 +536,7 @@ $table->valign[1] = 'top';
$table->data = [];
$table->data[0][0] = '<h4>'.__('List of layers').'</h4>';
$table->data[0][1] = '<divclass="right">'.html_print_button(__('New layer'), 'new_layer', false, 'newLayer();', 'class="sub add"', true).'</div>';
$table->data[0][1] = '<div class="right">'.html_print_button(__('New layer'), 'new_layer', false, 'newLayer();', 'class="sub add "', true).'</div>';
$table->data[1][0] = '<table class="databox" border="0" cellpadding="4" cellspacing="4" id="list_layers"></table>';
$table->data[1][1] = '<div id="form_layer" class="invisible">
@ -972,15 +972,7 @@ function getAgentRow (layerId, agentId, agentAlias) {
var $deleteCol = $("<td />");
var $agentAlias = $("<span class=\"agent_alias\" data-agent-id=\"" + agentId + "\">" + agentAlias + "</span>");
var $removeBtn = $('<a class="delete_row" href="javascript:;">
<?php
echo html_print_image(
'images/cross.png',
true,
['class' => 'invert_filter']
);
?>
</a>');
var $removeBtn = $('<a class="delete_row" href="javascript:" <?php echo html_print_image('images/cross.png', true, ['class' => 'invert_filter']); ?> </a>');
$removeBtn.click(function (event) {
var $layerRow = $("tr#layer_row_" + layerId);

View File

@ -515,9 +515,9 @@ if (!$maps && !is_metaconsole()) {
if ($maps) {
if (!is_metaconsole()) {
echo '<div class="action-buttons w100p right">';
echo '<div class="action-buttons w100p right_align">';
} else {
echo '<div class="w100p right_align">';
echo '<div class="w100p right right_align">';
}
}

View File

@ -3283,7 +3283,7 @@ function print_SLA_list($width, $action, $idItem=null)
echo '</tbody>';
?>
<tbody id="sla_template">
<tr id="row" class="datos invisible">
<tr id="row" class="datos" style="display: none">
<td class="sla_list_agent_col agent_name"></td>
<td class="sla_list_module_col module_name"></td>
<?php
@ -3687,7 +3687,7 @@ function print_General_list($width, $action, $idItem=null, $type='general')
?>
<tbody id="general_template">
<tr id="row" class="datos invisible">
<tr id="row" class="datos" style="display: none">
<td class="agent_name"></td>
<td class="module_name"></td>
<?php

View File

@ -664,7 +664,7 @@ if (defined('METACONSOLE')) {
if (check_acl($config['id_user'], 0, 'RM')) {
html_print_input_hidden('ids_items_to_delete', '');
html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete right"');
html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete right mrgn_btn_15px"');
}
echo '</div>';

View File

@ -122,10 +122,10 @@ if ($action == 'new') {
src="">';
} else {
if (defined('METACONSOLE')) {
$table->data[0][2] = '<img id="imagen2"
$table->data[0][2] = '<img id="imagen2" style="width:230px;"
src="../../images/console/background/'.$background.'">';
} else {
$table->data[0][2] = '<img id="imagen2"
$table->data[0][2] = '<img id="imagen2" style="width:230px;"
src="images/console/background/'.$background.'">';
}

View File

@ -20,10 +20,13 @@ require_once $config['homedir'].'/include/functions_visual_map.php';
require_once $config['homedir'].'/include/functions_agents.php';
enterprise_include_once('include/functions_visual_map.php');
// Retrieve the visual console id
// Retrieve the visual console id.
set_unless_defined($idVisualConsole, 0);
// Set default
// Set default.
$idVisualConsole = get_parameter('id_visual_console', $idVisualConsole);
if (empty($idVisualConsole) === true) {
$idVisualConsole = get_parameter('id_visualmap', 0);
}
if (!defined('METACONSOLE')) {
$action_name_parameter = 'action';
@ -795,7 +798,7 @@ $buttons['view'] = [
'text' => '<a href="'.$url_view.'">'.html_print_image('images/operation.png', true, ['title' => __('View'), 'class' => 'invert_filter']).'</a>',
];
if ($action == 'new' || $idVisualConsole === false) {
if ($idVisualConsole === false) {
$buttons = ['data' => $buttons['data']];
// Show only the data tab
// If it is a fail try, reset the values
@ -822,7 +825,7 @@ if ($statusProcessInDB !== null) {
echo $statusProcessInDB['message'];
}
// The source code for PAINT THE PAGE
// The source code for PAINT THE PAGE.
switch ($activeTab) {
case 'wizard':
include_once $config['homedir'].'/godmode/reporting/visual_console_builder.wizard.php';

View File

@ -16,7 +16,7 @@ global $config;
check_login();
// Visual console required.
if (empty($visualConsole)) {
if (empty($visualConsole) === true) {
db_pandora_audit(
'ACL Violation',
'Trying to access report builder'

View File

@ -29,7 +29,10 @@
// Load global vars.
global $config;
require_once 'include/config.php';
require_once $config['homedir'].'/include/config.php';
require_once $config['homedir'].'/vendor/autoload.php';
use PandoraFMS\Core\Config;
check_login();
@ -388,44 +391,11 @@ if ($config['history_db_enabled'] == 1) {
);
}
$config_history = false;
if ($config['history_db_connection']) {
$history_connect = mysql_db_process_sql(
'DESCRIBE tconfig',
'affected_rows',
$config['history_db_connection'],
false
);
if ($history_connect !== false) {
$config_history_array = mysql_db_process_sql(
'SELECT * FROM tconfig',
'affected_rows',
$config['history_db_connection'],
false
);
if (isset($config_history_array) && is_array($config_history_array)) {
foreach ($config_history_array as $key => $value) {
$config_history[$value['token']] = $value['value'];
$config_history = true;
}
}
} else {
echo ui_print_error_message(
__('The tconfig table does not exist in the historical database')
);
}
}
if ($config_history === false) {
$config_history = [];
$config_history['days_purge'] = 180;
$config_history['days_compact'] = 120;
$config_history['step_compact'] = 1;
$config_history['event_purge'] = 180;
$config_history['string_purge'] = 180;
}
$config_history['days_purge'] = Config::get('days_purge', 180, true);
$config_history['days_compact'] = Config::get('days_compact', 120, true);
$config_history['step_compact'] = Config::get('step_compact', 1, true);
$config_history['event_purge'] = Config::get('event_purge', 180, true);
$config_history['string_purge'] = Config::get('string_purge', 180, true);
$table_historical = new StdClass();
$table_historical->width = '100%';

View File

@ -337,6 +337,18 @@ if (isset($config['error_config_update_config'])) {
ui_print_success_message(__('Correct update the setup options'));
}
if (is_array($config['error_config_update_config']['errors']) === true) {
foreach ($config['error_config_update_config']['errors'] as $msg) {
ui_print_error_message($msg);
}
}
if (is_array($config['error_config_update_config']['warnings']) === true) {
foreach ($config['error_config_update_config']['warnings'] as $msg) {
ui_print_warning_message($msg);
}
}
unset($config['error_config_update_config']);
}

View File

@ -77,6 +77,7 @@ is not working on the metaconsole and there is no time to fix it -->
var click_on_the_file_below_to_begin = "<?php echo __('Click on the file below to begin.'); ?>\n";
var updating = "<?php echo __('Updating'); ?>\n";
var package_updated_successfully = "<?php echo __('Package updated successfully.'); ?>\n";
var package_not_updated = "<?php echo __('Package not updated.'); ?>\n";
var if_there_are_any_database_change = "<?php echo __('If there are any database change, it will be applied.'); ?>\n";
var mr_available = "<?php echo __('Minor release available'); ?>\n";
var package_available = "<?php echo __('New package available'); ?>\n";

View File

@ -88,6 +88,11 @@ if (is_ajax()) {
$file_dest = $config['homedir']."/extras/mr/updated/$number.sql";
copy($file, $file_dest);
// After successfully update, schedule history
// database upgrade.
enterprise_include_once('include/functions_config.php');
enterprise_hook('history_db_install');
}
} else {
$error_file = fopen($config['homedir'].'/extras/mr/error.txt', 'w');

View File

@ -148,7 +148,8 @@ class ConsoleSupervisor
*/
public function runBasic()
{
global $config;
// Ensure functions are installed and up to date.
enterprise_hook('cron_extension_install_functions');
/*
* PHP configuration warnings:

View File

@ -1075,7 +1075,7 @@ class CredentialStore extends Wizard
item.options = '<a href="javascript:" onclick="show_form(\'';
item.options += id;
item.options += '\')" ><?php echo html_print_image('images/eye.png', true, ['title' => __('Show')]); ?></a>';
item.options += '\')" ><?php echo html_print_image('images/operation.png', true, ['title' => __('Show')]); ?></a>';
item.options += '<a href="javascript:" onclick="delete_key(\'';
item.options += id;

View File

@ -236,6 +236,7 @@ class HelpFeedBack extends Wizard
*/
public function sendMailMethod()
{
global $config;
$suggestion = get_parameter('type', 'false');
$feedback_text = get_parameter('feedback_text', null);
$feedback_mail = get_parameter('feedback_email', null);

View File

@ -3062,7 +3062,7 @@ class NetworkMap
$table->data['template_row']['node_target'] = '';
$table->data['template_row']['edit'] = '';
$table->data['template_row']['edit'] .= '<span class="edit_icon_correct invisible">'.html_print_image('images/dot_green.png', true).'</span><span class="edit_icon_fail invisible" >'.html_print_image('images/dot_red.png', true).'</span><span class="edit_icon_progress invisible">'.html_print_image('images/spinner.gif', true).'</span><span class="edit_icon"><a class="edit_icon_link" title="'.__('Update').'" href="#">'.html_print_image('images/config.png', true).'</a></span>';
$table->data['template_row']['edit'] .= '<span class="edit_icon_correct" style="display: none">'.html_print_image('images/dot_green.png', true).'</span><span class="edit_icon_fail" style="display: none" >'.html_print_image('images/dot_red.png', true).'</span><span class="edit_icon_progress" style="display: none">'.html_print_image('images/spinner.gif', true).'</span><span class="edit_icon"><a class="edit_icon_link" title="'.__('Update').'" href="#">'.html_print_image('images/config.png', true).'</a></span>';
$table->data['template_row']['edit'] .= '<a class="delete_icon" href="#">'.html_print_image('images/delete.png', true).'</a>';

View File

@ -104,7 +104,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Tactical View'),
'icon' => ui_get_full_url(
'images/op_monitoring.menu_gray.png'
'images/menu/op_monitoring.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=view&sec2=operation/agentes/tactical'
@ -122,7 +122,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Agent Management'),
'icon' => ui_get_full_url(
'images/gm_resources.menu_gray.png'
'images/menu/gm_resources.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=gagente&sec2=godmode/agentes/modificar_agente'
@ -140,7 +140,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('General Setup'),
'icon' => ui_get_full_url(
'images/gm_setup.menu_gray.png'
'images/menu/gm_setup.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=general&sec2=godmode/setup/setup&section=general'
@ -156,7 +156,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Manage Policies'),
'icon' => ui_get_full_url(
'images/gm_configuration.menu_gray.png'
'images/menu/gm_configuration.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=gmodules&sec2=enterprise/godmode/policies/policies'
@ -170,7 +170,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('List Alerts'),
'icon' => ui_get_full_url(
'images/gm_alerts.menu_gray.png'
'images/menu/gm_alerts.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=galertas&sec2=godmode/alerts/alert_list'
@ -194,7 +194,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('View Events'),
'icon' => ui_get_full_url(
'images/op_events.menu_gray.png'
'images/menu/op_events.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=eventos&sec2=operation/events/events'
@ -218,7 +218,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Dashboard'),
'icon' => ui_get_full_url(
'images/op_reporting.menu_gray.png'
'images/menu/op_reporting.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=reporting&sec2=operation/dashboard/dashboard'
@ -232,7 +232,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Visual Console'),
'icon' => ui_get_full_url(
'images/op_network.menu_gray.png'
'images/menu/op_network.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=network&sec2=godmode/reporting/map_builder'
@ -246,7 +246,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Manage Servers'),
'icon' => ui_get_full_url(
'images/gm_servers.menu_gray.png'
'images/menu/gm_servers.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=gservers&sec2=godmode/servers/modificar_server'
@ -260,7 +260,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Edit User'),
'icon' => ui_get_full_url(
'images/gm_users.menu_gray.png'
'images/menu/gm_users.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=workspace&sec2=operation/users/user_edit'
@ -270,7 +270,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Tree View'),
'icon' => ui_get_full_url(
'images/op_monitoring.menu_gray.png'
'images/menu/op_monitoring.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=view&sec2=operation/tree'
@ -280,7 +280,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Network Component'),
'icon' => ui_get_full_url(
'images/gm_configuration.menu_gray.png'
'images/menu/gm_configuration.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=gmodules&sec2=godmode/modules/manage_network_components'
@ -294,7 +294,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Task List'),
'icon' => ui_get_full_url(
'images/gm_discovery.menu.png'
'images/menu/gm_discovery.menu.png'
),
'url' => ui_get_full_url(
'index.php?sec=discovery&sec2=godmode/servers/discovery&wiz=tasklist'
@ -338,7 +338,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Update Manager'),
'icon' => ui_get_full_url(
'images/um_messages.menu_gray.png'
'images/menu/um_messages.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=messages&sec2=godmode/update_manager/update_manager&tab=setup'
@ -352,7 +352,7 @@ class OrderInterpreter extends Wizard
[
'name' => __('Manage Agent Groups'),
'icon' => ui_get_full_url(
'images/gm_users.menu_gray.png'
'images/menu/gm_users.menu_gray.png'
),
'url' => ui_get_full_url(
'index.php?sec=gagente&sec2=godmode/groups/group_list&tab=groups'

View File

@ -20,7 +20,7 @@
/**
* Pandora build version and version
*/
$build_version = 'PC210325';
$build_version = 'PC210329';
$pandora_version = 'v7.0NG.752';
// Do not overwrite default timezone set if defined.
@ -97,7 +97,7 @@ require_once $ownDir.'functions.php';
// We need a timezone BEFORE calling config_process_config.
// If not we will get ugly warnings. Set Europe/Madrid by default
// Later will be replaced by the good one.
if (!is_dir($_SERVER['DOCUMENT_ROOT'].$config['homeurl']) || !is_dir($_SERVER['DOCUMENT_ROOT'].$config['homeurl_static'])) {
if (!is_dir($config['homedir'])) {
$url = explode('/', $_SERVER['REQUEST_URI']);
$flag_url = 0;
foreach ($url as $key => $value) {

View File

@ -1496,6 +1496,7 @@ function db_run_sql_file($location)
// Undo results
}
$config['db_run_sql_file_error'] = $mysqli->error;
return false;
}
}

View File

@ -149,7 +149,7 @@ function agents_locate_agent(string $field)
*
* @param string $alias Agent alias.
*
* @return integer Id from the agent.
* @return array|boolean Agents ids or false if error.
*/
function agents_get_agent_id_by_alias($alias)
{

View File

@ -6992,114 +6992,6 @@ function api_set_planned_downtimes_additem($id, $thrash1, $other, $thrash3)
}
/**
* Add data module to policy. And return id from new module.
*
* @param string $id Id of the target policy.
* @param $thrash1 Don't use.
* @param array $other it's array, $other as param is <module_name>;<id_module_type>;<description>;
* <id_module_group>;<min>;<max>;<post_process>;<module_interval>;<min_warning>;<max_warning>;<str_warning>;
* <min_critical>;<max_critical>;<str_critical>;<history_data>;<configuration_data>;
* <disabled_types_event>;<module_macros>;<ff_threshold>;<each_ff>;<ff_threshold_normal>;
* <ff_threshold_warning>;<ff_threshold_critical>;<ff_timeout> in this order
* and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
* example:
*
* example:
*
* api.php?op=set&op2=add_data_module_policy&id=1&other=data_module_policy_example_name~2~data%20module%20created%20by%20Api~2~0~0~50.00~10~20~180~~21~35~~1~module_begin%0dmodule_name%20pandora_process%0dmodule_type%20generic_data%0dmodule_exec%20ps%20aux%20|%20grep%20pandora%20|%20wc%20-l%0dmodule_end&other_mode=url_encode_separator_~
*
* @param $thrash3 Don't use
*/
function api_set_add_data_module_policy($id, $thrash1, $other, $thrash3)
{
if (defined('METACONSOLE')) {
return;
}
if ($id == '') {
returnError('The data module could not be added to policy. Id_policy cannot be left blank.');
return;
}
if (enterprise_hook('policies_check_user_policy', [$id]) === false) {
returnError('forbidden', 'string');
return;
}
if ($other['data'][0] == '') {
returnError('The data module could not be added to policy. Module_name cannot be left blank.');
return;
}
// Check if the module is already in the policy
$name_module_policy = enterprise_hook('policies_get_modules', [$id, ['name' => $other['data'][0]], 'name']);
if ($name_module_policy === ENTERPRISE_NOT_HOOK) {
returnError('The data module could not be added to policy.');
return;
}
$disabled_types_event = [];
$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][16];
$disabled_types_event = json_encode($disabled_types_event);
$values = [];
$values['id_tipo_modulo'] = $other['data'][1];
$values['description'] = $other['data'][2];
$values['id_module_group'] = $other['data'][3];
$values['min'] = $other['data'][4];
$values['max'] = $other['data'][5];
$values['post_process'] = $other['data'][6];
$values['module_interval'] = $other['data'][7];
$values['min_warning'] = $other['data'][8];
$values['max_warning'] = $other['data'][9];
$values['str_warning'] = $other['data'][10];
$values['min_critical'] = $other['data'][11];
$values['max_critical'] = $other['data'][12];
$values['str_critical'] = $other['data'][13];
$values['history_data'] = $other['data'][14];
$values['configuration_data'] = $other['data'][15];
$values['disabled_types_event'] = $disabled_types_event;
$values['module_macros'] = $other['data'][17];
$values['min_ff_event'] = $other['data'][18];
$values['each_ff'] = $other['data'][19];
$values['min_ff_event_normal'] = $other['data'][20];
$values['min_ff_event_warning'] = $other['data'][21];
$values['min_ff_event_critical'] = $other['data'][22];
$values['ff_timeout'] = $other['data'][23];
$values['ff_type'] = $other['data'][24];
if ($name_module_policy !== false) {
if ($name_module_policy[0]['name'] == $other['data'][0]) {
returnError(
'The data module could not be added to policy. The module is already in the policy.'
);
return;
}
}
$success = enterprise_hook(
'policies_create_module',
[
$other['data'][0],
$id,
1,
$values,
false,
]
);
if ($success) {
// returnData('string', array('type' => 'string', 'data' => __('Data module added to policy. Is necessary to apply the policy in order to changes take effect.')));
returnData('string', ['type' => 'string', 'data' => $success]);
} else {
returnError('The data module could not be added to policy.');
}
}
/**
* Update data module in policy. And return id from new module.
*

View File

@ -26,7 +26,12 @@
* ============================================================================
*/
// Config functions.
// Config functions.
require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/functions.php';
enterprise_include_once('include/functions_config.php');
use PandoraFMS\Core\DBMaintainer;
use PandoraFMS\Core\Config;
/**
@ -147,6 +152,8 @@ function config_update_config()
}
$error_update = [];
$errors = [];
$warnings = [];
$sec2 = get_parameter('sec2');
@ -1452,6 +1459,31 @@ function config_update_config()
break;
case 'hist_db':
if ($config['dbname'] == get_parameter('history_db_name')
&& $config['dbport'] == get_parameter('history_db_port')
&& $config['dbhost'] == io_input_password(get_parameter('history_db_host'))
) {
// Same definition for active and historical database!
// This is a critical error.
$config['error_config_update_config']['correct'] = false;
$config['error_config_update_config']['message'] = __(
'Active and historical database cannot be the same.'
);
return;
} else {
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_enabled', get_parameter('history_db_enabled'))) {
$error_update[] = __('Enable history database');
}
@ -1460,18 +1492,6 @@ function config_update_config()
$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');
}
@ -1511,6 +1531,68 @@ function config_update_config()
) {
$error_update[] = __('Delay');
}
if ((bool) $config['history_db_enabled'] === true) {
$dbm = new DBMaintainer(
[
'host' => $config['history_db_host'],
'port' => $config['history_db_port'],
'name' => $config['history_db_name'],
'user' => $config['history_db_user'],
'pass' => $config['history_db_pass'],
]
);
// Performs several checks and installs if needed.
if ($dbm->checkDatabaseDefinition() === true
&& $dbm->isInstalled() === false
) {
// Target is ready but several tasks are pending.
$dbm->process();
} else if ($dbm->check() !== true) {
$errors[] = $dbm->getLastError();
}
}
// Historical configuration tokens (stored in historical db).
if (Config::set(
'days_purge',
get_parameter('history_dbh_purge'),
true
) !== true
) {
$error_update[] = __('Historical database purge');
}
if (Config::set(
'history_partitions_auto',
get_parameter_switch('history_partitions_auto', 0),
true
) !== true
) {
$error_update[] = __('Historical database partitions');
}
if (Config::set(
'event_purge',
get_parameter('history_dbh_events_purge'),
true
) !== true
) {
$error_update[] = __('Historical database events purge');
}
if (Config::set(
'string_purge',
get_parameter('history_dbh_string_purge'),
true
) !== true
) {
$error_update[] = __('Historical database string purge');
}
// Disable history db in history db.
Config::set('history_db_enabled', 0, true);
break;
case 'ehorus':
@ -1685,6 +1767,14 @@ function config_update_config()
$config['error_config_update_config']['correct'] = true;
}
if (count($errors) > 0) {
$config['error_config_update_config']['errors'] = $errors;
}
if (count($warnings) > 0) {
$config['error_config_update_config']['warnings'] = $warnings;
}
enterprise_include_once('include/functions_policies.php');
$enterprise = enterprise_include_once('include/functions_skins.php');
if ($enterprise !== ENTERPRISE_NOT_HOOK) {

View File

@ -113,7 +113,7 @@ function custom_graphs_create(
* @param $returnAllGroup Wheter to return graphs of group All or not.
* @param $privileges Privileges to check in user group
*
* @return Custom graphs of a an user. Empty array if none.
* @return array graphs of a an user. Empty array if none.
*/
function custom_graphs_get_user($id_user=0, $only_names=false, $returnAllGroup=true, $privileges='RR')
{

View File

@ -2208,24 +2208,26 @@ function html_print_input_text_extended(
/**
* Render an input password element.
* Render a section <div> html element.
*
* The element will have an id like: "password-$name"
*
* @param mixed parameters:
* @param array $options Parameters:
* - id: string
* - style: string
* - class: string
* - title: string
* - hidden: boolean
* - content: string
* @param bool return or echo flag
* - content: string.
* @param boolean $return Return or echo flag.
*
* @return string HTML code if return parameter is true.
*/
function html_print_div($options, $return=false)
{
function html_print_div(
array $options,
bool $return=false
) {
$output = '<div';
// Valid attributes (invalid attributes get skipped)
// Valid attributes (invalid attributes get skipped).
$attrs = [
'id',
'style',
@ -2262,13 +2264,14 @@ function html_print_div($options, $return=false)
/**
* Render an anchor html element.
* Render an anchor <a> html element.
*
* @param array $options Parameters
* - id: string
* - style: string
* - title: string
* - id: string.
* - style: string.
* - title: string.
* - href: string.
* - content: string.
* @param boolean $return Return or echo flag.
*
* @return string HTML code if return parameter is true.

View File

@ -12807,7 +12807,7 @@ function reporting_get_stats_servers()
$tdata[0] = html_print_image('images/database.png', true, ['title' => __('Local modules'), 'class' => 'invert_filter']);
$tdata[1] = '<span class="big_data">'.format_numeric($server_performance['total_local_modules']).'</span>';
$tdata[2] = '<span class="med_data">'.format_numeric($server_performance['local_modules_rate'], 2).'</span>';
$tdata[3] = html_print_image('images/database.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'class' => 'invert_filter']).'/sec </span>';
$tdata[3] = html_print_image('images/module.png', true, ['title' => __('Ratio').': '.__('Modules by second'), 'class' => 'invert_filter']).'/sec </span>';
$table_srv->rowclass[] = '';
$table_srv->data[] = $tdata;

View File

@ -473,7 +473,7 @@ function treeview_printAlertsTable($id_module, $server_data=[], $no_head=false)
if ($user_access_node && check_acl($config['id_user'], $id_group, 'LW')) {
// Actions table
echo '<div class="w100p right mw300px">';
echo '<div class="w100p right mw300px right_align">';
echo '<a target=_blank href="'.$console_url.'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=alert&search=1&module_name='.$module_name.'&id_agente='.$agent_id.$url_hash.'" target="_blank">';
html_print_submit_button(__('Go to alerts edition'), 'upd_button', false, 'class="sub search"');
echo '</a>';

View File

@ -333,7 +333,7 @@ function ui_print_message($message, $class='', $attributes='', $return=false, $t
$output .= '</td>
</tr>
<tr>
<td class="black pdd_t_10px">'.$text_message.'</td>
<td class="black pdd_t_10px" style="color: #000">'.$text_message.'</td>
<td></td>
</tr>
</table>';
@ -3770,6 +3770,7 @@ function ui_print_event_priority(
* @param string $attributes_switch Switch attributes.
* @param string $toggl_attr Main box extra attributes.
* @param boolean|null $switch_on Switch enabled disabled or depending on hidden_Default.
* @param string|null $switch_name Use custom switch input name or generate one.
*
* @return string HTML.
*/
@ -3790,7 +3791,8 @@ function ui_toggle(
$switch=false,
$attributes_switch='',
$toggl_attr='',
$switch_on=null
$switch_on=null,
$switch_name=null
) {
// Generate unique Id.
$uniqid = uniqid('');
@ -3826,7 +3828,7 @@ function ui_toggle(
$main_class = '';
}
if (empty($container_class) === true) {
if ($container_class == 'white-box-content') {
$container_class = 'white-box-content-clean';
}
}
@ -3836,11 +3838,15 @@ function ui_toggle(
$output .= '<div class="'.$header_class.'" style="cursor: pointer;" id="tgl_ctrl_'.$uniqid.'">';
if ($reverseImg === false) {
if ($switch === true) {
if (empty($switch_name) === true) {
$switch_name = 'box_enable_toggle'.$uniqid;
}
$output .= html_print_div(
[
'class' => 'float-left',
'content' => html_print_checkbox_switch_extended(
'box_enable_toggle'.$uniqid,
$switch_name,
1,
($switch_on === null) ? (($hidden_default === true) ? 0 : 1) : $switch_on,
false,
@ -3910,7 +3916,7 @@ function ui_toggle(
$output .= ' var hide_tgl_ctrl_'.$uniqid.' = '.(int) $hidden_default.";\n";
$output .= ' /* <![CDATA[ */'."\n";
$output .= " $(document).ready (function () {\n";
$output .= " $('#checkbox-box_enable_toggle".$uniqid."').click(function() {\n";
$output .= " $('#checkbox-".$switch_name."').click(function() {\n";
$output .= ' if (hide_tgl_ctrl_'.$uniqid.") {\n";
$output .= ' hide_tgl_ctrl_'.$uniqid." = 0;\n";
$output .= " $('#tgl_div_".$uniqid."').toggle();\n";
@ -3925,13 +3931,13 @@ function ui_toggle(
$output .= ' hide_tgl_ctrl_'.$uniqid." = 0;\n";
$output .= " $('#tgl_div_".$uniqid."').toggle();\n";
$output .= " $('#image_".$uniqid."').attr({src: '".$image_a."'});\n";
$output .= " $('#checkbox-box_enable_toggle".$uniqid."').prop('checked', true);\n";
$output .= " $('#checkbox-".$switch_name."').prop('checked', true);\n";
$output .= " }\n";
$output .= " else {\n";
$output .= ' hide_tgl_ctrl_'.$uniqid." = 1;\n";
$output .= " $('#tgl_div_".$uniqid."').toggle();\n";
$output .= " $('#image_".$uniqid."').attr({src: '".$image_b."'});\n";
$output .= " $('#checkbox-box_enable_toggle".$uniqid."').prop('checked', false);\n";
$output .= " $('#checkbox-".$switch_name."').prop('checked', false);\n";
$output .= " }\n";
$output .= " });\n";
$output .= " });\n";
@ -3951,23 +3957,24 @@ function ui_toggle(
* Simplified way of ui_toggle ussage.
*
* @param array $data Arguments:
* 'content'
* 'name'
* 'title'
* 'id'
* 'hidden_default'
* 'return'
* 'toggle_class'
* 'container_class'
* 'main_class'
* 'img_a'
* 'img_b'
* 'clean'
* 'reverseImg'
* 'switch'
* 'attributes_switch'
* 'toggl_attr'
* 'switch_on'.
* - content
* - name
* - title
* - id
* - hidden_default
* - return
* - toggle_class
* - container_class
* - main_class
* - img_a
* - img_b
* - clean
* - reverseImg
* - switch
* - attributes_switch
* - toggl_attr
* - switch_on
* - switch_name.
*
* @return string HTML code with toggle content.
*/
@ -3990,7 +3997,8 @@ function ui_print_toggle($data)
(isset($data['switch']) === true) ? $data['switch'] : false,
(isset($data['attributes_switch']) === true) ? $data['attributes_switch'] : '',
(isset($data['toggl_attr']) === true) ? $data['toggl_attr'] : '',
(isset($data['switch_on']) === true) ? $data['switch_on'] : null
(isset($data['switch_on']) === true) ? $data['switch_on'] : null,
(isset($data['switch_name']) === true) ? $data['switch_name'] : null
);
}
@ -5705,6 +5713,12 @@ function ui_print_module_string_value(
$value = io_safe_input($value);
}
$is_snapshot = is_snapshot_data($module['datos']);
$is_large_image = is_text_to_black_string($module['datos']);
if (($config['command_snapshot']) && ($is_snapshot || $is_large_image)) {
$row[7] = ui_get_snapshot_image($link, $is_snapshot).'&nbsp;&nbsp;';
}
$is_snapshot = is_snapshot_data($value);
$is_large_image = is_text_to_black_string($value);
if (($config['command_snapshot']) && ($is_snapshot || $is_large_image)) {

View File

@ -69,6 +69,10 @@ var TreeController = {
messageLength = childGroupsLength + controller.tree.length;
}
group_message = controller.foundMessage + ": " + messageLength;
if (controller.foundMessage == "") {
group_message = "";
}
$group
.addClass("tree-root")
.hide()
@ -78,9 +82,7 @@ var TreeController = {
(controller.baseURL.length > 0 ? controller.baseURL : "") +
'images/pandora.png" />' +
"<span class='margin-left-1'>" +
(controller.tree.length > 0
? controller.foundMessage + ": " + messageLength
: "") +
(controller.tree.length > 0 ? group_message : "") +
"</div>"
);
} else {
@ -1222,7 +1224,9 @@ var TreeController = {
if (typeof data.auth_hash !== "undefined") {
this.auth_hash = data.auth_hash;
}
if (data.tree[0]["rootType"] == "services") {
this.foundMessage = "";
}
this.load();
},
remove: function() {

View File

@ -0,0 +1,188 @@
<?php
/**
* Config class.
*
* @category Class
* @package Pandora FMS
* @subpackage OpenSource
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2021 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.
* ============================================================================
*/
// Begin.
namespace PandoraFMS\Core;
require_once __DIR__.'/../../config.php';
require_once __DIR__.'/../../functions_config.php';
/**
* Config class to operate console configuration.
*/
final class Config
{
/**
* History database settings (tconfig).
*
* @var array
*/
private static $settings = [];
/**
* Load history database settings.
*
* @return void
*/
private static function loadHistoryDBSettings()
{
global $config;
if ((bool) $config['history_db_enabled'] === false) {
return;
}
// Connect if needed.
if (isset($config['history_db_connection']) === false
|| $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) {
$data = \db_get_all_rows_sql(
'SELECT * FROM `tconfig`',
false,
false,
$config['history_db_connection']
);
}
if (is_array($data) !== true) {
return [];
}
self::$settings = array_reduce(
$data,
function ($carry, $item) {
$carry[$item['token']] = $item['value'];
return $carry;
},
[]
);
}
/**
* Retrieve configuration token.
*
* @param string $token Token to retrieve.
* @param mixed $default Default value if not found.
* @param boolean $history_db Search for token in history_db.
*
* @return mixed Configuration token.
*/
public static function get(
string $token,
$default=null,
bool $history_db=false
) {
if ($history_db === true) {
self::loadHistoryDBSettings();
if (isset(self::$settings[$token]) === true) {
return self::$settings[$token];
}
return $default;
} else {
global $config;
if (isset($config[$token]) === true) {
return $config[$token];
}
}
return $default;
}
/**
* Set configuration token.
*
* @param string $token Token to set.
* @param mixed $value Value to be.
* @param boolean $history_db Save to history_db settings.
*
* @return boolean Success or not.
*/
public static function set(string $token, $value, bool $history_db=false)
{
global $config;
$rs = false;
if ($history_db !== false) {
if (self::get($token, null, $history_db) === null) {
// Create.
$rs = \db_process_sql(
sprintf(
'INSERT INTO `tconfig` (`token`, `value`)
VALUES ("%s", "%s")',
$token,
$value
),
'affected_rows',
$config['history_db_connection']
);
} else {
// Update.
$rs = \db_process_sql(
sprintf(
'UPDATE `tconfig`
SET `value`= "%s"
WHERE `token` = "%s"',
$value,
$token
),
'affected_rows',
$config['history_db_connection']
);
}
} else {
$rs = \config_update_value($token, $value);
}
return ($rs !== false);
}
}

View File

@ -0,0 +1,765 @@
<?php
/**
* Database mantainer class.
*
* @category Class
* @package Pandora FMS
* @subpackage OpenSource
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2021 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.
* ============================================================================
*/
// Begin.
namespace PandoraFMS\Core;
/**
* Class to handle database mantainer (not queries).
*/
final class DBMaintainer
{
const ESSENTIAL_TABLES = [
'tagente_datos',
'tagente_datos_string',
'tevento',
'tconfig',
];
/**
* Database user.
*
* @var string
*/
private $user;
/**
* Database pass.
*
* @var string
*/
private $pass;
/**
* Database port.
*
* @var integer
*/
private $port;
/**
* Database name.
*
* @var string
*/
private $name;
/**
* Database host.
*
* @var string
*/
private $host;
/**
* Charset forced.
*
* @var string
*/
private $charset;
/**
* Verifies if PandoraFMS DB schema is installed.
*
* @var boolean
*/
private $installed;
/**
* Verifies if endpoint is connected.
*
* @var boolean
*/
private $connected;
/**
* Connection link.
*
* @var mixed|null
*/
private $dbh;
/**
* Last error registered.
*
* @var string
*/
private $lastError;
/**
* Connected to engine and database.
*
* @var boolean
*/
private $ready;
/**
* Initialize DBMaintainer object.
*
* @param array $params Database connection definition, including:
* - user
* - pass
* - database name
* - host (default 127.0.0.1)
* - port (default 3306)
* If not defined some fields will use default values.
*/
public function __construct(array $params)
{
$this->user = $params['user'];
$this->pass = $params['pass'];
$this->host = $params['host'];
$this->port = $params['port'];
$this->name = $params['name'];
$this->charset = $params['charset'];
// Try to connect.
$this->connect();
}
/**
* Connects (if not connected) to current definition.
*
* @return boolean True if successfully connected, false if not.
*/
private function connect()
{
if ($this->connected === true) {
return true;
}
$dbc = new \mysqli(
$this->host,
$this->user,
$this->pass,
null,
$this->port
);
if ((bool) $dbc->connect_error === true) {
$this->dbh = null;
$this->connected = false;
$this->lastError = $dbc->connect_errno.': '.$dbc->connect_error;
} else {
$this->dbh = $dbc;
if (empty($this->charset) === false) {
$dbc->set_charset($this->charset);
}
if ($this->dbh->select_db($this->name) === false) {
$this->lastError = $this->dbh->errno.': '.$this->dbh->error;
$this->ready = false;
} else {
$this->lastError = null;
$this->ready = true;
}
$this->connected = true;
}
}
/**
* Return connection statuis.
*
* @return boolean
*/
public function isConnected()
{
return $this->connected;
}
/**
* Retrieve last error.
*
* @return string Error message.
*/
public function getLastError()
{
if ($this->lastError !== null) {
return $this->lastError;
}
return '';
}
/**
* Retrieve all rows from given query in array format.
*
* @param string $query Query.
*
* @return array Results.
*/
private function getAllRows(string $query)
{
if ($this->ready !== true) {
$this->lastError = $this->dbh->errno.': '.$this->dbh->error;
return [];
}
$rs = $this->dbh->query($query);
$results = [];
if ($rs !== false) {
do {
$row = $rs->fetch_array(MYSQLI_ASSOC);
if ((bool) $row !== false) {
$results[] = $row;
}
} while ((bool) $row !== false);
}
return $results;
}
/**
* Return first row available for given query.
*
* @param string $query Query to retrieve (1 row only).
*
* @return array Row.
*/
private function getRow(string $query)
{
if ($this->ready !== true) {
$this->lastError = $this->dbh->errno.': '.$this->dbh->error;
return [];
}
$query .= ' LIMIT 1';
$rs = $this->dbh->query($query);
if ($rs !== false) {
return $rs->fetch_array(MYSQLI_ASSOC);
}
// Error.
return false;
}
/**
* Retrieve value from given query.
*
* @param string $table Table to query.
* @param string $key Field to retrieve.
* @param array $filter Filters to apply.
* @param string $join AND by default.
*
* @return mixed|null Value retrieved or null if not found.
*/
private function getValue(
string $table,
string $key,
array $filter,
string $join='AND'
) {
$query = sprintf(
'SELECT %s FROM %s WHERE %s',
$key,
$table,
\db_format_array_where_clause_sql($filter, $join)
);
$result = $this->getRow($query);
if ($result !== false) {
return $result[$key];
}
return false;
}
/**
* Verifies schema against running db.
*
* @return boolean Success or not.
*/
public function verifySchema()
{
if ($this->ready !== true) {
return false;
}
$missing_essential_tables = $this->verifyTables();
return !(bool) count($missing_essential_tables);
}
/**
* Verifies tables against running db.
*
* @return boolean Applied or not.
*/
public function verifyTables()
{
global $config;
$t = \db_get_all_rows_sql(
sprintf(
'SHOW TABLES FROM %s',
$config['dbname']
)
);
$tables = [];
foreach ($t as $v) {
$tables[] = array_shift($v);
}
$t = $this->getAllRows(
sprintf(
'SHOW TABLES FROM %s',
$this->name
)
);
$myTables = [];
foreach ($t as $k => $v) {
$myTables[] = array_shift($v);
}
$differences = array_diff($tables, $myTables);
if (count($differences) > 0) {
$this->lastError = sprintf(
'Warning, following tables does not exist in target: %s',
join(', ', $differences)
);
}
// Exclude extension tables.
$differences = array_intersect($differences, self::ESSENTIAL_TABLES);
return $differences;
}
/**
* Updates or creates a token in remote tconfig.
*
* @param string $token Token to be set.
* @param mixed $value Value for given token.
*
* @return boolean Success or not.
*/
private function setConfigToken(string $token, $value)
{
$prev = $this->getValue('tconfig', 'value', ['token' => $token]);
// If failed or not found, then insert.
if ($prev === false || $prev === null) {
// Create.
$rs = $this->dbh->query(
sprintf(
'INSERT INTO `tconfig` (`token`, `value`)
VALUES ("%s", "%s")',
$token,
$value
)
);
} else {
// Update.
$rs = $this->dbh->query(
sprintf(
'UPDATE `tconfig`
SET `value`= "%s"
WHERE `token` = "%s"',
$value,
$token
)
);
}
return ($rs !== false);
}
/**
* Create database only (not schema) in target.
*
* @return boolean Success or not.
*/
public function checkDatabaseDefinition()
{
if ($this->ready === true) {
return true;
}
if ($this->dbh === null) {
return false;
}
$rc = $this->dbh->query(
sprintf(
'CREATE DATABASE %s',
$this->name
)
);
if ($rc === false) {
$this->lastError = $this->dbh->errno.': '.$this->dbh->error;
return false;
}
if ($this->dbh->select_db($this->name) === false) {
$this->lastError = $this->dbh->errno.': '.$this->dbh->error;
return false;
}
// Already connected and ready to execute commands.
$this->ready = true;
return true;
}
/**
* Install PandoraFMS database schema in current target.
*
* @param boolean $check_only Check and return, do not perform actions.
*
* @return boolean Installation is success or not.
*/
public function install(bool $check_only=false)
{
if ($this->connect() !== true) {
return false;
}
if ($this->installed === true) {
return true;
}
if ($this->ready !== true) {
// Not ready, create database in target.
if ($check_only === true) {
$this->lastError = 'Database does not exist in target';
return false;
}
if ($this->checkDatabaseDefinition() === false) {
return false;
}
} else if ($this->verifySchema() === true) {
$this->installed = true;
$this->lastError = null;
return true;
}
if ($check_only === true) {
$this->lastError = 'Schema not applied in target';
return false;
}
$result = $this->applyDump(Config::get('homedir', '').'/pandoradb.sql');
// Set MR version according pandoradb_data.
$data_content = file_get_contents(
Config::get('homedir', '').'/pandoradb_data.sql'
);
if (preg_match('/\(\'MR\'\,\s*(\d+)\)/', $data_content, $matches) > 0) {
$target_mr = $matches[1];
}
$cnf_update = $this->setConfigToken('MR', (int) $target_mr);
return $result && $cnf_update;
}
/**
* Updates PandoraFMS database schema in current target.
*
* @param boolean $check_only Perform only test without update.
*
* @return boolean Current installation is up to date.
*/
public function update(bool $check_only=false)
{
if ($this->connect() !== true) {
return false;
}
if ($this->install($check_only) !== true) {
return false;
}
// Set MR version according pandoradb_data.
$data_content = file_get_contents(
Config::get('homedir', '').'/pandoradb_data.sql'
);
if (preg_match('/\(\'MR\'\,\s*(\d+)\)/', $data_content, $matches) > 0) {
$target_mr = $matches[1];
}
// Active database MR version.
$active_mr = (int) Config::get('MR', 0);
// Historical database MR version.
$last_mr_curr = (int) $this->getValue(
'tconfig',
'value',
['token' => 'MR']
);
if ($check_only === true) {
if ($active_mr === $last_mr_curr) {
return true;
}
$this->lastError = sprintf(
'Database schema not up to date: #%d should be #%d',
$last_mr_curr,
$active_mr
);
if ($active_mr < $target_mr) {
$this->lastError .= sprintf(
' (latest available: #%d)',
$target_mr
);
}
return false;
}
if ($last_mr_curr < $active_mr) {
while ($last_mr_curr < $active_mr) {
$last_mr_curr++;
$path = Config::get('homedir', '');
$file = sprintf('/extras/mr/%d.sql', $last_mr_curr);
$updated_file = sprintf(
'/extras/mr/updated/%d.sql',
$last_mr_curr
);
$filename = $path.$file;
if (file_exists($path.$file) !== true) {
// File does not exist, maybe already udpated in active DB?
$filename = $path.$updated_file;
if (file_exists($filename) !== false) {
$this->lastError = 'Unable to locate MR update #';
$this->lastError .= $last_mr_curr;
return false;
}
}
if ($this->applyDump($filename, true) !== true) {
$err = 'Unable to apply MR update #';
$err .= $last_mr_curr.': ';
$this->lastError = $err.$this->lastError;
return false;
} else {
// Update MR value.
$this->setConfigToken('MR', $last_mr_curr);
}
}
}
if ($last_mr_curr !== $active_mr) {
$this->lastError = 'Unknown database schema version, check MR in both active and historical database';
return false;
}
return true;
}
/**
* Process database checks perform required actions.
* Returns true if it is connected, installed and updated.
*
* @return boolean Status of the installation.
*/
public function process()
{
if ($this->connect() !== true) {
return false;
}
if ($this->install() !== true) {
return false;
}
if ($this->update() !== true) {
return false;
}
return true;
}
/**
* Check if target has schema updated.
*
* @return boolean
*/
public function isUpdated()
{
return $this->update(true);
}
/**
* Check if target has schema installed.
*
* @return boolean
*/
public function isInstalled()
{
return $this->install(true);
}
/**
* Checks if target is ready to connect.
*
* @return boolean
*/
public function isReady()
{
if ($this->ready === true) {
return true;
}
$this->connect();
return $this->ready;
}
/**
* Checks if current target is connected, installed and updated.
*
* @return boolean Status of the database schema.
*/
public function check()
{
if ($this->connect() !== true) {
return false;
}
if ($this->isInstalled() !== true) {
return false;
}
if ($this->isUpdated() !== true) {
return false;
}
return true;
}
/**
* This function keeps same functionality as install.php:parse_mysqli_dump.
*
* @param string $path Path where SQL dump file is stored.
* @param boolean $transactional Use transactions from file (true) (MRs).
*
* @return boolean Success or not.
*/
private function applyDump(string $path, bool $transactional=false)
{
if (file_exists($path) === true) {
if ($transactional === true) {
global $config;
// Adapt to PandoraFMS classic way to do things...
$backup_dbhost = $config['dbhost'];
$backup_dbuser = $config['dbuser'];
$backup_dbpass = $config['dbpass'];
$backup_dbname = $config['dbname'];
$backup_dbport = $config['dbport'];
$backup_mysqli = $config['mysqli'];
$config['dbhost'] = $this->host;
$config['dbuser'] = $this->user;
$config['dbpass'] = $this->pass;
$config['dbname'] = $this->name;
$config['dbport'] = $this->port;
// Not using mysqli in > php 7 is a completely non-sense.
$config['mysqli'] = true;
// MR are loaded in transactions.
include_once $config['homedir'].'/include/db/mysql.php';
$return = db_run_sql_file($path);
if ($return === false) {
$this->lastError = $config['db_run_sql_file_error'];
}
// Revert global variable.
$config['dbhost'] = $backup_dbhost;
$config['dbuser'] = $backup_dbuser;
$config['dbpass'] = $backup_dbpass;
$config['dbname'] = $backup_dbname;
$config['dbport'] = $backup_dbport;
$config['mysqli'] = $backup_mysqli;
return (bool) $return;
} else {
$file_content = file($path);
$query = '';
foreach ($file_content as $sql_line) {
if (trim($sql_line) !== ''
&& strpos($sql_line, '-- ') === false
) {
$query .= $sql_line;
if ((bool) preg_match("/;[\040]*\$/", $sql_line) === true) {
$result = $this->dbh->query($query);
if ((bool) $result === false) {
$this->lastError = $this->dbh->errno.': ';
$this->lastError .= $this->dbh->error;
return false;
}
$query = '';
}
}
}
}
return true;
}
// File does not exist.
$this->lastError = sprintf(
'File %s does not exist',
$path
);
return false;
}
}

View File

@ -245,17 +245,26 @@ class CustomGraphWidget extends Widget
$return_all_group = false;
if (users_can_manage_group_all('RM')) {
if (users_can_manage_group_all('RM') === true) {
$return_all_group = true;
}
// Custom graph.
$fields = \custom_graphs_get_user(0, false, $return_all_group);
// If currently selected graph is not included in fields array (it belongs to a group over which user has no permissions), then add it to fields array.
// This is aimed to avoid overriding this value when a user with narrower permissions edits widget configuration.
if ($values['id_graph'] !== null && !array_key_exists($values['id_graph'], $fields)) {
$selected_graph = db_get_row('tgraph', 'id_graph', $values['id_graph']);
// If currently selected graph is not included in fields array
// (it belongs to a group over which user has no permissions),
// then add it to fields array.
// This is aimed to avoid overriding this value when a user
// with narrower permissions edits widget configuration.
if ($values['id_graph'] !== null
&& array_key_exists($values['id_graph'], $fields) === false
) {
$selected_graph = db_get_row(
'tgraph',
'id_graph',
$values['id_graph']
);
$fields[$values['id_graph']] = $selected_graph;
}
@ -366,7 +375,8 @@ class CustomGraphWidget extends Widget
);
$hackLegendHight = (30 * count($sources));
if ($hackLegendHight > ($size['height'] - 10 - $hackLegendHight)) {
$operation = ($size['height'] - 10 - $hackLegendHight);
if ($hackLegendHight < $operation) {
$height = ($size['height'] - $hackLegendHight);
} else {
$height = ($size['height'] - 10);
@ -406,7 +416,6 @@ class CustomGraphWidget extends Widget
'height' => $height,
'only_image' => false,
'homeurl' => $config['homeurl'],
'percentil' => $percentil,
'backgroundColor' => 'transparent',
'menu' => false,
'show_legend' => $this->values['showLegend'],

View File

@ -620,7 +620,7 @@ class EventsListWidget extends Widget
// Filter.
$filter,
// Offset.
null,
0,
// Limit.
$this->values['limit'],
// Order.

View File

@ -164,6 +164,9 @@ class SystemGroupStatusWidget extends Widget
// This forces at least a first configuration.
$this->configurationRequired = false;
if (empty($this->values['groupId']) === true) {
$this->configurationRequired = true;
}
$this->overflow_scrollbars = false;
}
@ -299,6 +302,7 @@ class SystemGroupStatusWidget extends Widget
'return' => true,
'multiple' => true,
'returnAllGroup' => $return_all_group,
'required' => true,
],
];

View File

@ -163,7 +163,10 @@ abstract class Entity
{
// Prioritize written methods over dynamic ones.
if (method_exists($this, $methodName) === true) {
return $this->{$methodName}($params);
return call_user_func_array(
$this->{$methodName},
$params
);
}
// Enterprise capabilities.

View File

@ -91,4 +91,54 @@ class ModuleType extends Entity
}
/**
* Validate id_module and id_module_type pair.
*
* @param integer $id_module_type Id module_type.
* @param integer $id_modulo Id modulo.
*
* @return boolean True success, false if not.
*/
public static function validate(int $id_module_type, int $id_modulo)
{
switch ($id_modulo) {
case MODULE_PLUGIN:
case MODULE_PREDICTION:
case MODULE_DATA:
case MODULE_WMI:
if (($id_module_type < 6 || $id_module_type > 18) === false
&& ($id_module_type < 29 || $id_module_type > 34) === false
&& ($id_module_type === 25)
) {
return false;
}
break;
case MODULE_NETWORK:
case MODULE_SNMP:
if ($id_module_type < 6 || $id_module_type > 18) {
return false;
}
break;
case MODULE_WEB:
if ($id_module_type !== 25) {
return false;
}
break;
case MODULE_WUX:
if ($id_module_type < 29 || $id_module_type > 34) {
return false;
}
break;
default:
return false;
}
return true;
}
}

View File

@ -40,14 +40,12 @@
*/
// Begin.
namespace PandoraFMS\WebSockets;
namespace PandoraFMS\Websockets;
use \PandoraFMS\Websockets\WebSocketServer;
use \PandoraFMS\Websockets\WebSocketUser;
use \PandoraFMS\User;
require_once __DIR__.'/../functions.php';
require_once __DIR__.'/../../functions.php';
/**
* Redirects ws communication between two endpoints.
@ -212,7 +210,7 @@ class WSManager extends WebSocketServer
*/
public function readSocket($user)
{
$buffer;
$buffer = '';
$numBytes = socket_recv(
$user->socket,
@ -271,7 +269,7 @@ class WSManager extends WebSocketServer
{
global $config;
$match;
$match = [];
$php_session_id = '';
\preg_match(
'/PHPSESSID=(.*)/',

View File

@ -50,7 +50,7 @@
width: 100%;
}
li:hover ul {
.menu_full li:hover ul {
display: block;
}

View File

@ -805,6 +805,11 @@ select:-internal-list-box {
.flex-nowrap {
flex-wrap: nowrap;
}
.flex-evenly {
justify-content: space-evenly;
}
.flex-row-baseline {
display: flex;
flex-direction: row;
@ -8441,3 +8446,6 @@ div.stat-win-spinner img {
width: 100px;
height: 100px;
}
.lign_right {
text-align: right;
}

View File

@ -0,0 +1,33 @@
span.subtitle {
font-size: 1.3em;
font-weight: normal;
font-family: "lato-bolder";
}
span.subtitle-2 {
font-size: 1em;
font-weight: normal;
font-family: "lato-bolder";
}
.no-borders {
border: 0 !important;
}
input[type="text"],
input[type="number"] {
width: 220px;
}
.fit > tbody > tr > td img {
width: 15px;
}
.clean-toggles .white_table_graph_header {
border: none;
}
.dbhist tr td:first-child {
width: 45%;
min-width: 450px;
}

View File

@ -7,6 +7,7 @@
div.external-visual-console-container {
width: 100%;
overflow-x: auto;
overflow-y: hidden;
}
div#vc-controls {

View File

@ -165,3 +165,11 @@ ul.wizard li > textarea {
justify-content: space-evenly !important;
flex: 1 1 auto;
}
ul.wizard li.mrgn_0px {
margin: 0;
}
ul.wizard li.pdd_0px {
padding: 0;
}

View File

@ -129,7 +129,7 @@
<div style='height: 10px'>
<?php
$version = '7.0NG.752';
$build = '210325';
$build = '210329';
$banner = "v$version Build $build";
error_reporting(0);

View File

@ -364,7 +364,7 @@ ui_toggle(
ui_require_css_file('cluetip', 'include/styles/js/');
ui_require_jquery_file('cluetip');
echo "<div id='module_details_dialog' class='invisible'></div>";
echo "<div id='module_details_dialog' class='display:none'></div>";
ui_include_time_picker();
ui_require_jquery_file('ui.datepicker-'.get_user_language(), 'include/javascript/i18n/');
@ -386,15 +386,7 @@ ui_require_jquery_file('ui.datepicker-'.get_user_language(), 'include/javascript
cluetipClass: 'default',
sticky: true,
mouseOutClose: 'both',
closeText: '
<?php
html_print_image(
'images/cancel.png',
false,
['class' => 'invert_filter']
);
?>
'
closeText: '<?php html_print_image('images/cancel.png', false, ['class' => 'invert_filter']); ?>'
});
// Show the modal window of an module

View File

@ -266,7 +266,7 @@ $table->data[] = $data;
$table->rowclass[] = '';
$form_table = html_print_table($table, true);
$form_table .= '<div class="w100p right">';
$form_table .= '<div class="w100p right right_align">';
$form_table .= html_print_submit_button(
__('Reload'),
'submit',

View File

@ -265,7 +265,7 @@ if (is_ajax()) {
$return['correct'] = true;
$return['content'] = '<div class="border_1px_black">
<div class="w100p right"><a class="no_decoration black" href="javascript: hide_tooltip();">X</a></div>
<div class="w100p right right_align"><a class="no_decoration black" href="javascript: hide_tooltip();">X</a></div>
<div class="mrgn_5px">
';

View File

@ -386,7 +386,7 @@ ui_print_message_dialog(
);
$form_table = html_print_table($table, true);
$form_table .= '<div class="w100p right mrgn_top_15px">';
$form_table .= '<div class="w100p right mrgn_top_15px right_align">';
$form_table .= html_print_submit_button(
__('Reload'),
'submit',

View File

@ -120,18 +120,23 @@ echo '<td class="tactical_left_column" id="leftcolumn">';
// ---------------------------------------------------------------------
// The status horizontal bars (Global health, Monitor sanity...
// ---------------------------------------------------------------------
$bg_color = 'background-color: #222';
if ($config['style'] !== 'pandora_black') {
$bg_color = 'background-color: #fff';
}
$table = new stdClass();
$table->width = '100%';
$table->class = 'info_table no-td-borders td-bg-white';
$table->class = 'info_table no-td-borders';
$table->cellpadding = 2;
$table->cellspacing = 2;
$table->border = 0;
$table->head = [];
$table->data = [];
$table->style = [];
$table->style = [$bg_color];
$stats = reporting_get_stats_indicators($data, 120, 10, false);
$status = '<table class="status_tactical">';
$status = '<table class="status_tactical bg_white">';
foreach ($stats as $stat) {
$status .= '<tr><td><b>'.$stat['title'].'</b>'.'</td><td>'.$stat['graph'].'</td></tr>';
}
@ -175,7 +180,7 @@ ui_toggle(
echo '</td>';
// Left column
echo '<td class="align-top w75p pdd_t_0px" id="rightcolumn">';
echo '<td class="w75p pdd_t_0px" id="rightcolumn">';
// ---------------------------------------------------------------------
// Last events information

View File

@ -994,7 +994,7 @@ if ($group_rep == 2) {
if (check_acl($config['id_user'], 0, 'EW')) {
if ($config['event_replication'] != 1) {
echo '<div class="w100p right">';
echo '<div class="w100p right right_align">';
echo '<form method="post" id="form_event_response">';
html_print_select($array_events_actions, 'response_id', '', '', '', 0, false, false, false);
echo '&nbsp&nbsp';

View File

@ -238,7 +238,7 @@ if (reporting_get_description($id_report)) {
$table->data[0][1] = '<div class="float-left">'.reporting_get_name($id_report).'</div>';
}
$table->data[0][1] .= '<div class="right w100p mrgn_right_50px">'.__('Set initial date').html_print_checkbox('enable_init_date', 1, $enable_init_date, true);
$table->data[0][1] .= '<div class="right w100p mrgn_right_50px right_align">'.__('Set initial date').html_print_checkbox('enable_init_date', 1, $enable_init_date, true);
$html_enterprise = enterprise_hook(
'reporting_print_button_PDF',
[$id_report]

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_console
%define version 7.0NG.752
%define release 210325
%define release 210329
# User and Group under which Apache is running
%define httpd_name httpd

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_console
%define version 7.0NG.752
%define release 210325
%define release 210329
# User and Group under which Apache is running
%define httpd_name httpd

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_console
%define version 7.0NG.752
%define release 210325
%define release 210329
%define httpd_name httpd
# User and Group under which Apache is running
%define httpd_name apache2

View File

@ -37,8 +37,8 @@ namespace Composer\Autoload;
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
@ -60,7 +60,7 @@ class ClassLoader
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();

View File

@ -6,6 +6,7 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'DeepCopy\\DeepCopy' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/DeepCopy.php',
'DeepCopy\\Exception\\CloneException' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php',
'DeepCopy\\Exception\\PropertyException' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Exception/PropertyException.php',
@ -44,7 +45,6 @@ return array(
'Egulias\\EmailValidator\\Exception\\DomainHyphened' => $vendorDir . '/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php',
'Egulias\\EmailValidator\\Exception\\DotAtEnd' => $vendorDir . '/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php',
'Egulias\\EmailValidator\\Exception\\DotAtStart' => $vendorDir . '/egulias/email-validator/EmailValidator/Exception/DotAtStart.php',
'Egulias\\EmailValidator\\Exception\\ExpectedQPair' => $vendorDir . '/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php',
'Egulias\\EmailValidator\\Exception\\ExpectingAT' => $vendorDir . '/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php',
'Egulias\\EmailValidator\\Exception\\ExpectingATEXT' => $vendorDir . '/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php',
'Egulias\\EmailValidator\\Exception\\ExpectingCTEXT' => $vendorDir . '/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php',
@ -309,49 +309,22 @@ return array(
'Mpdf\\Utils\\PdfDate' => $vendorDir . '/mpdf/mpdf/src/Utils/PdfDate.php',
'Mpdf\\Utils\\UtfString' => $vendorDir . '/mpdf/mpdf/src/Utils/UtfString.php',
'PandoraFMS\\Agent' => $baseDir . '/include/lib/Agent.php',
'PandoraFMS\\Dashboard\\AgentModuleWidget' => $baseDir . '/include/lib/Dashboard/Widgets/agent_module.php',
'PandoraFMS\\Dashboard\\AlertsFiredWidget' => $baseDir . '/include/lib/Dashboard/Widgets/alerts_fired.php',
'PandoraFMS\\Core\\Config' => $baseDir . '/include/lib/Core/Config.php',
'PandoraFMS\\Core\\DBMaintainer' => $baseDir . '/include/lib/Core/DBMaintainer.php',
'PandoraFMS\\Dashboard\\Cell' => $baseDir . '/include/lib/Dashboard/Cell.php',
'PandoraFMS\\Dashboard\\ClockWidget' => $baseDir . '/include/lib/Dashboard/Widgets/clock.php',
'PandoraFMS\\Dashboard\\CustomGraphWidget' => $baseDir . '/include/lib/Dashboard/Widgets/custom_graph.php',
'PandoraFMS\\Dashboard\\EventsListWidget' => $baseDir . '/include/lib/Dashboard/Widgets/events_list.php',
'PandoraFMS\\Dashboard\\GraphModuleHistogramWidget' => $baseDir . '/include/lib/Dashboard/Widgets/graph_module_histogram.php',
'PandoraFMS\\Dashboard\\GroupsStatusWidget' => $baseDir . '/include/lib/Dashboard/Widgets/groups_status.php',
'PandoraFMS\\Dashboard\\Manager' => $baseDir . '/include/lib/Dashboard/Manager.php',
'PandoraFMS\\Dashboard\\MapsMadeByUser' => $baseDir . '/include/lib/Dashboard/Widgets/maps_made_by_user.php',
'PandoraFMS\\Dashboard\\MapsStatusWidget' => $baseDir . '/include/lib/Dashboard/Widgets/maps_status.php',
'PandoraFMS\\Dashboard\\ModuleIconWidget' => $baseDir . '/include/lib/Dashboard/Widgets/module_icon.php',
'PandoraFMS\\Dashboard\\ModuleStatusWidget' => $baseDir . '/include/lib/Dashboard/Widgets/module_status.php',
'PandoraFMS\\Dashboard\\ModuleTableValueWidget' => $baseDir . '/include/lib/Dashboard/Widgets/module_table_value.php',
'PandoraFMS\\Dashboard\\ModuleValueWidget' => $baseDir . '/include/lib/Dashboard/Widgets/module_value.php',
'PandoraFMS\\Dashboard\\MonitorHealthWidget' => $baseDir . '/include/lib/Dashboard/Widgets/monitor_health.php',
'PandoraFMS\\Dashboard\\NetworkMapWidget' => $baseDir . '/include/lib/Dashboard/Widgets/network_map.php',
'PandoraFMS\\Dashboard\\PostWidget' => $baseDir . '/include/lib/Dashboard/Widgets/post.php',
'PandoraFMS\\Dashboard\\ReportsWidget' => $baseDir . '/include/lib/Dashboard/Widgets/reports.php',
'PandoraFMS\\Dashboard\\SLAPercentWidget' => $baseDir . '/include/lib/Dashboard/Widgets/sla_percent.php',
'PandoraFMS\\Dashboard\\ServiceMapWidget' => $baseDir . '/include/lib/Dashboard/Widgets/service_map.php',
'PandoraFMS\\Dashboard\\SingleGraphWidget' => $baseDir . '/include/lib/Dashboard/Widgets/single_graph.php',
'PandoraFMS\\Dashboard\\SystemGroupStatusWidget' => $baseDir . '/include/lib/Dashboard/Widgets/system_group_status.php',
'PandoraFMS\\Dashboard\\TacticalWidget' => $baseDir . '/include/lib/Dashboard/Widgets/tactical.php',
'PandoraFMS\\Dashboard\\TopNEventByGroupWidget' => $baseDir . '/include/lib/Dashboard/Widgets/top_n_events_by_group.php',
'PandoraFMS\\Dashboard\\TopNEventByModuleWidget' => $baseDir . '/include/lib/Dashboard/Widgets/top_n_events_by_module.php',
'PandoraFMS\\Dashboard\\TopNWidget' => $baseDir . '/include/lib/Dashboard/Widgets/top_n.php',
'PandoraFMS\\Dashboard\\TreeViewWidget' => $baseDir . '/include/lib/Dashboard/Widgets/tree_view.php',
'PandoraFMS\\Dashboard\\UrlWidget' => $baseDir . '/include/lib/Dashboard/Widgets/url.php',
'PandoraFMS\\Dashboard\\WelcomeWidget' => $baseDir . '/include/lib/Dashboard/Widgets/example.php',
'PandoraFMS\\Dashboard\\Widget' => $baseDir . '/include/lib/Dashboard/Widget.php',
'PandoraFMS\\Dashboard\\WuxStatsWidget' => $baseDir . '/include/lib/Dashboard/Widgets/wux_transaction_stats.php',
'PandoraFMS\\Dashboard\\WuxWidget' => $baseDir . '/include/lib/Dashboard/Widgets/wux_transaction.php',
'PandoraFMS\\Entity' => $baseDir . '/include/lib/Entity.php',
'PandoraFMS\\Event' => $baseDir . '/include/lib/Event.php',
'PandoraFMS\\Group' => $baseDir . '/include/lib/Group.php',
'PandoraFMS\\Module' => $baseDir . '/include/lib/Module.php',
'PandoraFMS\\ModuleStatus' => $baseDir . '/include/lib/ModuleStatus.php',
'PandoraFMS\\ModuleType' => $baseDir . '/include/lib/ModuleType.php',
'PandoraFMS\\User' => $baseDir . '/include/lib/User.php',
'PandoraFMS\\View' => $baseDir . '/include/lib/View.php',
'PandoraFMS\\WebSockets\\WSManager' => $baseDir . '/include/lib/WSManager.php',
'PandoraFMS\\Websockets\\WebSocketServer' => $baseDir . '/include/lib/WebSocketServer.php',
'PandoraFMS\\Websockets\\WebSocketUser' => $baseDir . '/include/lib/WebSocketUser.php',
'PandoraFMS\\Websockets\\WSManager' => $baseDir . '/include/lib/Websockets/WSManager.php',
'PandoraFMS\\Websockets\\WebSocketServer' => $baseDir . '/include/lib/Websockets/WebSocketServer.php',
'PandoraFMS\\Websockets\\WebSocketUser' => $baseDir . '/include/lib/Websockets/WebSocketUser.php',
'Psr\\Log\\AbstractLogger' => $vendorDir . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => $vendorDir . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => $vendorDir . '/psr/log/Psr/Log/LogLevel.php',
@ -360,7 +333,6 @@ return array(
'Psr\\Log\\LoggerInterface' => $vendorDir . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => $vendorDir . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => $vendorDir . '/psr/log/Psr/Log/NullLogger.php',
'Psr\\Log\\Test\\DummyTest' => $vendorDir . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => $vendorDir . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'fpdi_pdf_parser' => $vendorDir . '/setasign/fpdi/fpdi_pdf_parser.php',
'pdf_context' => $vendorDir . '/setasign/fpdi/pdf_context.php',

View File

@ -22,13 +22,15 @@ class ComposerAutoloaderInitfdecadadce22e6dde51e9535fe4ad7aa
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInitfdecadadce22e6dde51e9535fe4ad7aa', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitfdecadadce22e6dde51e9535fe4ad7aa', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitfdecadadce22e6dde51e9535fe4ad7aa::getInitializer($loader));
} else {

View File

@ -88,6 +88,7 @@ class ComposerStaticInitfdecadadce22e6dde51e9535fe4ad7aa
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'DeepCopy\\DeepCopy' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/DeepCopy.php',
'DeepCopy\\Exception\\CloneException' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php',
'DeepCopy\\Exception\\PropertyException' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/Exception/PropertyException.php',
@ -126,7 +127,6 @@ class ComposerStaticInitfdecadadce22e6dde51e9535fe4ad7aa
'Egulias\\EmailValidator\\Exception\\DomainHyphened' => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator/Exception/DomainHyphened.php',
'Egulias\\EmailValidator\\Exception\\DotAtEnd' => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator/Exception/DotAtEnd.php',
'Egulias\\EmailValidator\\Exception\\DotAtStart' => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator/Exception/DotAtStart.php',
'Egulias\\EmailValidator\\Exception\\ExpectedQPair' => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator/Exception/ExpectingQPair.php',
'Egulias\\EmailValidator\\Exception\\ExpectingAT' => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator/Exception/ExpectingAT.php',
'Egulias\\EmailValidator\\Exception\\ExpectingATEXT' => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator/Exception/ExpectingATEXT.php',
'Egulias\\EmailValidator\\Exception\\ExpectingCTEXT' => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator/Exception/ExpectingCTEXT.php',
@ -391,49 +391,22 @@ class ComposerStaticInitfdecadadce22e6dde51e9535fe4ad7aa
'Mpdf\\Utils\\PdfDate' => __DIR__ . '/..' . '/mpdf/mpdf/src/Utils/PdfDate.php',
'Mpdf\\Utils\\UtfString' => __DIR__ . '/..' . '/mpdf/mpdf/src/Utils/UtfString.php',
'PandoraFMS\\Agent' => __DIR__ . '/../..' . '/include/lib/Agent.php',
'PandoraFMS\\Dashboard\\AgentModuleWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/agent_module.php',
'PandoraFMS\\Dashboard\\AlertsFiredWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/alerts_fired.php',
'PandoraFMS\\Core\\Config' => __DIR__ . '/../..' . '/include/lib/Core/Config.php',
'PandoraFMS\\Core\\DBMaintainer' => __DIR__ . '/../..' . '/include/lib/Core/DBMaintainer.php',
'PandoraFMS\\Dashboard\\Cell' => __DIR__ . '/../..' . '/include/lib/Dashboard/Cell.php',
'PandoraFMS\\Dashboard\\ClockWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/clock.php',
'PandoraFMS\\Dashboard\\CustomGraphWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/custom_graph.php',
'PandoraFMS\\Dashboard\\EventsListWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/events_list.php',
'PandoraFMS\\Dashboard\\GraphModuleHistogramWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/graph_module_histogram.php',
'PandoraFMS\\Dashboard\\GroupsStatusWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/groups_status.php',
'PandoraFMS\\Dashboard\\Manager' => __DIR__ . '/../..' . '/include/lib/Dashboard/Manager.php',
'PandoraFMS\\Dashboard\\MapsMadeByUser' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/maps_made_by_user.php',
'PandoraFMS\\Dashboard\\MapsStatusWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/maps_status.php',
'PandoraFMS\\Dashboard\\ModuleIconWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/module_icon.php',
'PandoraFMS\\Dashboard\\ModuleStatusWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/module_status.php',
'PandoraFMS\\Dashboard\\ModuleTableValueWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/module_table_value.php',
'PandoraFMS\\Dashboard\\ModuleValueWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/module_value.php',
'PandoraFMS\\Dashboard\\MonitorHealthWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/monitor_health.php',
'PandoraFMS\\Dashboard\\NetworkMapWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/network_map.php',
'PandoraFMS\\Dashboard\\PostWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/post.php',
'PandoraFMS\\Dashboard\\ReportsWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/reports.php',
'PandoraFMS\\Dashboard\\SLAPercentWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/sla_percent.php',
'PandoraFMS\\Dashboard\\ServiceMapWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/service_map.php',
'PandoraFMS\\Dashboard\\SingleGraphWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/single_graph.php',
'PandoraFMS\\Dashboard\\SystemGroupStatusWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/system_group_status.php',
'PandoraFMS\\Dashboard\\TacticalWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/tactical.php',
'PandoraFMS\\Dashboard\\TopNEventByGroupWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/top_n_events_by_group.php',
'PandoraFMS\\Dashboard\\TopNEventByModuleWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/top_n_events_by_module.php',
'PandoraFMS\\Dashboard\\TopNWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/top_n.php',
'PandoraFMS\\Dashboard\\TreeViewWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/tree_view.php',
'PandoraFMS\\Dashboard\\UrlWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/url.php',
'PandoraFMS\\Dashboard\\WelcomeWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/example.php',
'PandoraFMS\\Dashboard\\Widget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widget.php',
'PandoraFMS\\Dashboard\\WuxStatsWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/wux_transaction_stats.php',
'PandoraFMS\\Dashboard\\WuxWidget' => __DIR__ . '/../..' . '/include/lib/Dashboard/Widgets/wux_transaction.php',
'PandoraFMS\\Entity' => __DIR__ . '/../..' . '/include/lib/Entity.php',
'PandoraFMS\\Event' => __DIR__ . '/../..' . '/include/lib/Event.php',
'PandoraFMS\\Group' => __DIR__ . '/../..' . '/include/lib/Group.php',
'PandoraFMS\\Module' => __DIR__ . '/../..' . '/include/lib/Module.php',
'PandoraFMS\\ModuleStatus' => __DIR__ . '/../..' . '/include/lib/ModuleStatus.php',
'PandoraFMS\\ModuleType' => __DIR__ . '/../..' . '/include/lib/ModuleType.php',
'PandoraFMS\\User' => __DIR__ . '/../..' . '/include/lib/User.php',
'PandoraFMS\\View' => __DIR__ . '/../..' . '/include/lib/View.php',
'PandoraFMS\\WebSockets\\WSManager' => __DIR__ . '/../..' . '/include/lib/WSManager.php',
'PandoraFMS\\Websockets\\WebSocketServer' => __DIR__ . '/../..' . '/include/lib/WebSocketServer.php',
'PandoraFMS\\Websockets\\WebSocketUser' => __DIR__ . '/../..' . '/include/lib/WebSocketUser.php',
'PandoraFMS\\Websockets\\WSManager' => __DIR__ . '/../..' . '/include/lib/Websockets/WSManager.php',
'PandoraFMS\\Websockets\\WebSocketServer' => __DIR__ . '/../..' . '/include/lib/Websockets/WebSocketServer.php',
'PandoraFMS\\Websockets\\WebSocketUser' => __DIR__ . '/../..' . '/include/lib/Websockets/WebSocketUser.php',
'Psr\\Log\\AbstractLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/AbstractLogger.php',
'Psr\\Log\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/log/Psr/Log/InvalidArgumentException.php',
'Psr\\Log\\LogLevel' => __DIR__ . '/..' . '/psr/log/Psr/Log/LogLevel.php',
@ -442,7 +415,6 @@ class ComposerStaticInitfdecadadce22e6dde51e9535fe4ad7aa
'Psr\\Log\\LoggerInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerInterface.php',
'Psr\\Log\\LoggerTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerTrait.php',
'Psr\\Log\\NullLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/NullLogger.php',
'Psr\\Log\\Test\\DummyTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'Psr\\Log\\Test\\LoggerInterfaceTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php',
'fpdi_pdf_parser' => __DIR__ . '/..' . '/setasign/fpdi/fpdi_pdf_parser.php',
'pdf_context' => __DIR__ . '/..' . '/setasign/fpdi/pdf_context.php',

View File

@ -0,0 +1,26 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 70000)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.0.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}

View File

@ -28,7 +28,7 @@
// Begin.
require_once __DIR__.'/vendor/autoload.php';
use \PandoraFMS\WebSockets\WSManager;
use \PandoraFMS\Websockets\WSManager;
// Set to true to get full output.
$debug = false;

View File

@ -0,0 +1,3 @@
{
"python.pythonPath": "slack/venv/bin/python"
}

View File

@ -0,0 +1 @@
venv

View File

@ -0,0 +1,173 @@
import requests, argparse, sys, os
from datetime import datetime
from re import search
from base64 import b64decode
from discord_webhook import DiscordWebhook, DiscordEmbed
### Variables and arg parser ###
parser = argparse.ArgumentParser(description='Test parser dic')
parser.add_argument('-d', '--data', help='Data in coma separate keypairs. Ex: test=5,house=2', required=True)
parser.add_argument('-u', '--url', help='Discord webhook URL', required=True)
parser.add_argument('-t', '--alert_tittle', help='Alert tittle', default='PandoraFMS alert fired')
parser.add_argument('-D', '--alert_desc', help='Alert description', default='alert')
parser.add_argument('-m', '--message', help='Discord message', default='')
parser.add_argument('-T','--tittle_color', help='Alert tittle descripcion in HEX EX: 53e514', default="53e514")
parser.add_argument('-A','--author', help='Alert custom author', default='PandoraFMS')
parser.add_argument('-F','--footer', help='Custom footer', default='')
parser.add_argument('--avatar_url', help='Custom avatar URL for the user which send the alert', default='')
parser.add_argument('--author_url', help='Alert custom url author', default='')
parser.add_argument('--author_icon_url', help='Alert custom author icon url ', default='')
parser.add_argument('--thumb', help='Custom thumbnail url', default='')
parser.add_argument('--api_conf', help='Api configuration parameters in coma separate keypairs. EX "user=admin,pass=pandora,api_pass=1234,api_url=http://test.artica.es/pandora_console/include/api.php"')
parser.add_argument('--module_graph', help='Uses pandora API to generate a module graph and attach it to the alert needs module_id and interval parameters in coma separate keypairs. EX "module_id=55,interval=3600"')
parser.add_argument('--tmp_dir', help='Temporary path to store grph images', default='/tmp')
args = parser.parse_args()
### Functions:
def parse_dic(cValues):
"""convert coma separate keypairs into a dic. EX "test=5,house=8,market=2" wil return "{'test': '5', 'casa': '8', 'mercado': '2'}" """
data={}
try :
for kv in cValues.split(","):
k,v = kv.strip().split("=")
data[k.strip()]=v.strip()
except Exception as e :
print(f"Warning, error parsing keypairs values: {e}")
return data
def add_embed_itmes(data):
"""iterate dictionary and set webhook fields, one for eacj keypair"""
for k, v in data.items() :
embed.add_embed_field(name=k, value=v)
def parse_api_conf(cConf):
if args.api_conf :
# Parse Api config
print ("Api config enable")
apid = parse_dic(cConf)
if apid.get("user") is None:
print ("Error no user defined in api_conf keypairs, skiping graph generation.")
return
if apid.get("pass") is None:
print ("Error no password defined in api_conf keypairs, skiping graph generation.")
return
if apid.get("api_pass") is None:
print ("Error no Api pass defined in api_conf keypairs, skiping graph generation.")
return
if apid.get("api_url") is None:
apid['api_url'] = "http://127.0.0.1/pandora_console/include/api.php"
#print(f"api_url: {apid['api_url']}")
return apid
else:
return None
def parse_graph_conf(cGraph):
if not args.api_conf:
print ("To get graph data api conf shoul be provided please set an api config")
return
if cGraph :
# Parse Api config
graphd = parse_dic(cGraph)
if graphd.get("module_id") is None:
print ("error no module_id defined in module_graph keypairs, skiping graph generation.")
return
if graphd.get("interval") is None:
graphd["interval"] = 3600
return graphd
else:
return None
def get_graph_by_moduleid (baseUrl,pUser, pPass, apiPass, moduleId, graphInterval) :
sep="url_encode_separator_%7C"
try:
url = f"{baseUrl}?op=get&op2=module_graph&id={moduleId}&other={graphInterval}%7C1&other_mode={sep}C&apipass={apiPass}&api=1&user={pUser}&pass={pPass}"
graph = requests.get(url)
if graph.status_code != 200:
print (f"Error requested api url, status code: {graph.status_code}. Skiping graph generation")
return None
if graph.text == "auth error":
print (f"Error requested Pandora api url, status code: {graph.text}. Skiping graph generation")
return None
if graph.text == "Id does not exist in database.":
print (f"Error requested Pandora api url, status code: {graph.text}. Skiping graph generation")
return None
except:
print("Error requested api url. Skiping graph generation")
return None
return graph
## Main
## Basic message
webhook = DiscordWebhook(url=args.url, content=args.message, avatar_url=args.avatar_url)
# create embed object for webhook
embed = DiscordEmbed(title=args.alert_tittle, description=args.alert_desc, color=int(args.tittle_color, 16))
# set author
embed.set_author(name=args.author, url=args.author_url, icon_url=args.author_icon_url)
# set thumbnail
if args.thumb: embed.set_thumbnail(url=args.thumb)
# set footer
if args.footer : embed.set_footer(text=args.footer)
# set timestamp (default is now)
embed.set_timestamp()
# Parse data keys
data = parse_dic(args.data)
# add fields to embed
add_embed_itmes(data)
# Parse api config
api = parse_api_conf(args.api_conf)
# Parse graph config
graph_cfg = parse_graph_conf(args.module_graph)
## Generate module graph
if graph_cfg is not None and api is not None:
graph = get_graph_by_moduleid (api["api_url"],api["user"], api["pass"], api["api_pass"], graph_cfg["module_id"], graph_cfg["interval"])
if graph is not None:
try:
namef = f"graph_{graph_cfg['module_id']}.{datetime.now().strftime('%s')}.png"
filename = f"{args.tmp_dir}/{namef}"
with open(filename, "wb") as f:
f.write(b64decode(graph.text))
f.close
print (f"Graph generated on temporary file {filename}")
except Exception as e :
print(f"Error, cant generate graph file: {e}")
filename = None
try:
with open(filename, "rb") as F:
webhook.add_file(file=F.read(), filename=namef)
f.close
embed.set_image(url=f'attachment://{namef}')
except Exception as e :
print(f"Error, cant add graph file: {e}")
filename = None
# add embed object to webhook
webhook.add_embed(embed)
# Execute webhook send
response = webhook.execute()
# clean temp file if exist
try:
os.remove(filename)
except:
pass
# print response
print (f"Message sent. status code: {response[0].status_code}") if response[0].status_code == 200 else print (f"Error status code: {response[0].status_code}")

View File

@ -0,0 +1,6 @@
certifi==2020.11.8
chardet==3.0.4
discord-webhook==0.11.0
idna==2.10
requests==2.24.0
urllib3==1.25.11

View File

@ -0,0 +1,19 @@
#exetution example
python3 pandora_discord_cli.py -d "Agent=Server22,Module=test_module,Group=Servers,State=Critical,Data=22,Timestamp=2020-11-04 11:14:00" \
-u https://discord.com/api/webhooks/702868786843353179/YI1LOUzC64EcYcpPVB_ \
--tittle_color ed2512 \
--footer "PandoraFMS Alert" \
-A "Sauron Systems" \
--author_icon_url "https://pandorafms.com/wp-content/uploads/2019/04/software-de-monitorizacion-pandorafms-logo.png" \
-m "We have bad news for you. Something is on CRITICAL status 2" \
--author_url https://pandorafms.com/ \
-D "Module test is going to critical" \
--thumb https://pandorafms.com/images/alerta_roja.png \
--avatar_url https://pandorafms.com/images/alerta_roja.png \
--api_conf "user=admin,pass=pandora,api_pass=pandora,api_url=http://192.168.80.222/pandora_console/include/api.php" \
--module_graph "module_id=6266, interval=3600" \
--tmp_dir /tmp
# Pandora FMS command definition example
python3 /usr/share/pandora_server/util/pandora-discord/pandora_discord_cli.py -u "_field1_" -d "_field2_" -D "_field3_" --tittle_color _field4_ --thumb _field5_ --api_conf "_field6_" --module_graph "_field7_" -A "Pandora FMS Alert system" --footer "PandoraFMS" --author_icon_url "https://pandorafms.com/wp-content/uploads/2019/04/software-de-monitorizacion-pandorafms-logo.png" --author_url https://pandorafms.com/ --tmp_dir /tmp

View File

@ -0,0 +1,111 @@
import requests
import argparse
import sys
import os
import json
### Variables and arg parser ###
parser = argparse.ArgumentParser(description='Google chat webhook conector')
parser.add_argument(
'-d', '--data', help='Data in coma separate keypairs. Ex: test=5,house=2', required=True)
parser.add_argument(
'-u', '--url', help='Google chat webhook URL', required=True)
parser.add_argument('-t', '--alert_title', help='Alert title',
default='PandoraFMS alert system')
parser.add_argument('-D', '--alert_desc',
help='Alert description', default='Alert Fired')
parser.add_argument('--thumb', help='Custom thumbnail url',
default="https://pandorafms.com/images/alerta_roja.png")
parser.add_argument('--btn_desc', help='button description', default=None)
parser.add_argument('--btn_url', help='button url',
default="https://pandorafms.com/")
args = parser.parse_args()
# classes
class Message():
def __init__(self, title, subtitle, imageurl='https://goo.gl/aeDtrS'):
""" Initialize message object, setting header options"""
self.dic = {
'cards': []
}
header = {'header': {'title': title,
'subtitle': subtitle, 'imageUrl': imageurl}}
self.dic['cards'].append(header)
sections = {'sections': []}
self.dic['cards'].append(sections)
def add_header(self, title, subtitle, imageurl='https://goo.gl/aeDtrS'):
"""Add header to message object"""
header = {'header': {'title': title,
'subtitle': subtitle, 'imageUrl': imageurl}}
self.dic['cards'].append(header)
def add_value(self, keyval):
"""Add key value pairs data to message object, keyval should be a dictionary"""
m = ''
arr = []
for k, v in keyval.items():
m += f"<b>{k}</b>: {v} \n"
arr.append({'textParagraph': {'text': m}})
widgets = {'widgets': arr}
self.dic['cards'][1]['sections'].append(widgets)
def add_buttom(self, desc, url):
"""Add button to message object"""
btn = [{"textButton": {"text": desc, "onClick": {"openLink": {'url': url}}}}]
arr = [({'buttons': btn})]
widgets = {'widgets': arr}
self.dic['cards'][1]['sections'].append(widgets)
# functions
def parse_dic(cValues):
"""convert coma separate keypairs into a dic. EX "test=5,house=8,market=2" wil return "{'test': '5', 'casa': '8', 'mercado': '2'}" """
data = {}
try:
for kv in cValues.split(","):
k, v = kv.strip().split("=")
data[k.strip()] = v.strip()
except Exception as e:
print(f"Warning, error parsing keypairs values: {e}")
return data
def sendMessage(url, message):
"""sends google chat message"""
message = json.dumps(message)
try:
header = {'Content-Type': 'application/json; charset: UTF-8'}
response = requests.post(url, headers=header, data=message)
print(f"Mesage sent succefuly: {response.status_code}")
except:
print("Error requested api url. Skiping graph generation")
return None
return response
if __name__ == '__main__':
# Initializaate message object
a = Message(args.alert_title, args.alert_desc, args.thumb)
# Parse data values
data = parse_dic(args.data)
# Add datavalues into message object
a.add_value(data)
# Chek button parameters and add it to the message object
if args.btn_desc != None:
a.add_buttom(args.btn_desc, args.btn_url)
# Send message
sendMessage(args.url, a.dic)

View File

@ -0,0 +1,5 @@
certifi==2020.12.5
chardet==3.0.4
idna==2.10
requests==2.25.0
urllib3==1.26.2

View File

@ -0,0 +1,14 @@
#exetution example
python3 pandora-gchat-cli.py \
-d 'Agent=Server22,Module=test_module,Group=Servers,State=Critical,Data=22,Timestamp=2020-11-04 11:14:00' \
-u https://chat.googleapis.com/v1/spaces/AAAA6-AOZQ8/messages\?key\=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI\&token\=_ZGwKN4lue8ZiDKGVMLfMay3hLRrYjmgYr2fXPqPy0c%3D \
-t 'PandoraFMS Alert' \
-D 'Alert Fired' \
--thumb https://pandorafms.com/images/alerta_roja.png \
--btn_desc pandorafms.com \
--btn_url https://pandorafms.com/
# Pandora FMS command definition example
python3 /usr/share/pandora_server/util/pandora-gchat/pandora-gchat-cli.py -d '_field1_' -u '_field2_' -t '_field3_' -D '_field4_' --thumb '_field5_' --btn_desc pandorafms.com --btn_url https://pandorafms.com/

View File

@ -0,0 +1,83 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse, pymsteams
parser = argparse.ArgumentParser(description='MS Teams connector')
parser.add_argument('-d', '--data', help='Data in coma separate keypairs. Ex: test=5,house=2', required=True)
parser.add_argument('-u', '--url', help='Teams webhook URL', required=True)
parser.add_argument('-t', '--alert_tittle', help='Alert tittle', default='PandoraFMS alert fired')
parser.add_argument('-D', '--alert_desc', help='Alert description', default='Alert Fired')
parser.add_argument('-m', '--message', help='Alert message', default='')
parser.add_argument('-T','--tittle_color', help='Alert tittle descripcion in HEX EX: 53e514', default="ff0000")
parser.add_argument('--sub_desc', help='Alert sub description', default='Alert Fired')
parser.add_argument('--thumb', help='Custom thumbnail url', default="https://pandorafms.com/images/alerta_roja.png")
parser.add_argument('--button', help='Pandora button Url', default='https://pandorafms.com')
parser.add_argument('--button_desc', help='Pandora button description', default='Open web console')
args = parser.parse_args()
### Functions:
def parse_dic(cValues):
"""convert coma separate keypairs into a dic. EX "test=5,house=8,market=2" wil return "{'test': '5', 'casa': '8', 'mercado': '2'}" """
data={}
try :
for kv in cValues.split(","):
k,v = kv.strip().split("=")
data[k.strip()]=v.strip()
except Exception as e :
print(f"Warning, error parsing keypairs values: {e}")
return data
def add_embed_itmes(data):
"""iterate dictionary and set webhook fields, one for eacj keypair"""
for k, v in data.items() :
myMessageSection.addFact(f"{k}:", v)
##Main
# You must create the connectorcard object with the Microsoft Webhook URL
myTeamsMessage = pymsteams.connectorcard(args.url)
# Set Summary
myTeamsMessage.summary('Pandora FMS')
# Set Alert tittle
myTeamsMessage.title(args.alert_tittle)
# Set link buttom
myTeamsMessage.addLinkButton(args.button_desc, args.button)
# Set message color
myTeamsMessage.color(args.tittle_color)
# create the section
myMessageSection = pymsteams.cardsection()
# Section Title
myMessageSection.title(args.message)
# Activity Elements
myMessageSection.activityTitle(args.alert_desc)
myMessageSection.activitySubtitle(args.sub_desc)
myMessageSection.activityImage(args.thumb)
# Facts are key value pairs displayed in a list.
data = parse_dic(args.data)
add_embed_itmes(data)
# Section Text
# myMessageSection.text("This is my section text")
# Section Images
# myMessageSection.addImage("http://i.imgur.com/c4jt321l.png", ititle="This Is Fine")
# Add your section to the connector card object before sending
myTeamsMessage.addSection(myMessageSection)
# Then send the card
try:
myTeamsMessage.send()
except Exception as e :
exit(f"Error sending to message: {e}")
print (f"Mesage sent succefuly: {myTeamsMessage.last_http_status}")

View File

@ -0,0 +1,81 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse, pymsteams
parser = argparse.ArgumentParser(description='MsTeams connector')
parser.add_argument('-d', '--data', help='Data in coma separate keypairs. Ex: test=5,house=2', required=True)
parser.add_argument('-u', '--url', help='Teams webhook URL', required=True)
parser.add_argument('-t', '--alert_tittle', help='Alert tittle', default='PandoraFMS alert fired')
parser.add_argument('-D', '--alert_desc', help='Alert description', default='Alert Fired')
parser.add_argument('-m', '--message', help='Alert message', default='')
parser.add_argument('-T','--tittle_color', help='Alert tittle descripcion in HEX EX: 53e514', default="53e514")
parser.add_argument('--sub_desc', help='Alert sub description', default='Alert Fired')
parser.add_argument('--thumb', help='Custom thumbnail url', default="https://pandorafms.com/images/alerta_roja.png")
parser.add_argument('--button', help='Pandora button Url', default='https://pandorafms.com')
parser.add_argument('--button_desc', help='Pandora button description', default='Open web console')
args = parser.parse_args()
### Functions:
def parse_dic(cValues):
"""convert coma separate keypairs into a dic. EX "test=5,house=8,market=2" wil return "{'test': '5', 'casa': '8', 'mercado': '2'}" """
data={}
try :
for kv in cValues.split(","):
k,v = kv.strip().split("=")
data[k.strip()]=v.strip()
except Exception as e :
print(f"Warning, error parsing keypairs values: {e}")
return data
def add_embed_itmes(data):
"""iterate dictionary and set webhook fields, one for eacj keypair"""
for k, v in data.items() :
myMessageSection.addFact(f"{k}:", v)
##Main
# You must create the connectorcard object with the Microsoft Webhook URL
myTeamsMessage = pymsteams.connectorcard(args.url)
# Set Summary
myTeamsMessage.summary(args.message)
# Set Alert tittle
myTeamsMessage.title(args.alert_tittle)
# Set link buttom
myTeamsMessage.addLinkButton(args.button_desc, args.button)
# Set message color
myTeamsMessage.color(args.tittle_color)
# create the section
myMessageSection = pymsteams.cardsection()
# Section Title
myMessageSection.title(args.message)
# Activity Elements
myMessageSection.activityTitle(args.alert_desc)
myMessageSection.activitySubtitle(args.sub_desc)
myMessageSection.activityImage(args.thumb)
# Facts are key value pairs displayed in a list.
data = parse_dic(args.data)
add_embed_itmes(data)
# Section Text
# myMessageSection.text("This is my section text")
# Section Images
# myMessageSection.addImage("http://i.imgur.com/c4jt321l.png", ititle="This Is Fine")
# Add your section to the connector card object before sending
myTeamsMessage.addSection(myMessageSection)
# Then send the card
try:
myTeamsMessage.send()
except Exception as e :
print(f"Error sending to message: {e}")

View File

@ -0,0 +1,6 @@
certifi==2020.11.8
chardet==3.0.4
idna==2.10
pymsteams==0.1.14
requests==2.25.0
urllib3==1.26.2

View File

@ -0,0 +1,15 @@
#exetution example
python3 pandora-teams-cli.py -d "Agent=Server22,Module=test_module,Group=Servers,State=Critical,Data=22,Timestamp=2020-11-04 11:14:00" \
-u https://outlook.office.com/webhook/6f819e54-9c3f-4f87-94f4-90159496ef12@b3b55021-a812-46af-a5ef-127cc662d5b7/IncomingWebhook/634dafb7fe6549c9a214dd7fa9b97416/76c50d52-8678-49c2-9279-9f7bb3bb5a07 \
-t "Alert Tittle" \
-D "Alert description" \
-m "Pandora FMS Alert message" \
-T 53e514 \
--sub_desc "Alert subdescription" \
--thumb "https://pandorafms.com/images/alerta_roja.png" \
--button https://pandorafms.com \
--button_desc "Open PandoraFMS"
# Pandora FMS command definition example
python3 /usr/share/pandora_server/util/pandora-teams/pandora-msteams-cli.py -d "_field1_" -u "_field2_" -t "_field3_" -D "_field4_" -m "_field5_" -T _field6_ --sub_desc "_field7_" --thumb "_field8_" --button http://newfork.artica.es/pandora_console/ --button_desc "Open PandoraFMS Console"

View File

@ -0,0 +1 @@
venv

View File

@ -0,0 +1,177 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests, argparse, sys, os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from datetime import datetime
from re import search
from base64 import b64decode
### Variables and arg parser ###
parser = argparse.ArgumentParser(description='Slack BOT APP conector')
parser.add_argument('-d', '--data', help='Data in coma separate keypairs. Ex: test=5,house=2', required=True)
parser.add_argument('-t', '--token', help='BOT Token', required=True)
parser.add_argument('-c', '--channel', help='Slack channel id/name', required=True)
parser.add_argument('-e', '--emoji', help='Slack emoji for tittle, default: :red_circle:', default=':red_circle:')
parser.add_argument('-T', '--tittle', help='Alert tittle, default: PandoraFMS alert', default='PandoraFMS alert')
parser.add_argument('-D', '--desc', help='Slack description message', default='')
parser.add_argument('-F','--footer', help='Custom footer, default: PandoraFMS', default='PandoraFMS')
parser.add_argument('--api_conf', help='Api configuration parameters in coma separate keypairs. EX "user=admin,pass=pandora,api_pass=1234,api_url=http://test.artica.es/pandora_console/include/api.php"')
parser.add_argument('--module_graph', help='Uses pandora API to generate a module graph and attach it to the alert needs module_id and interval parameters in coma separate keypairs. EX "module_id=55,interval=3600"')
parser.add_argument('--tmp_dir', help='Temporary path to store grph images', default='/tmp')
args = parser.parse_args()
filename = None
#Functions
def parse_dic(cValues):
"""convert coma separate keypairs into a dic. EX "test=5,house=8,market=2" wil return "{'test': '5', 'casa': '8', 'mercado': '2'}" """
data={}
try :
for kv in cValues.split(","):
k,v = kv.strip().split("=")
data[k.strip()]=v.strip()
except Exception as e :
print(f"Warning, error parsing keypairs values: {e}")
return data
def compose_message (values, tittle, emoji, message, footer):
"""Format Text"""
values = parse_dic(values)
m = f"{emoji} *{tittle}*\n_{message}_\n\n"
for k, v in values.items() :
m += f"*{k}* : {v}\n"
return m
def parse_api_conf(cConf):
"""Check apiconfiguration parameters """
if args.api_conf :
# Parse Api config
print ("Api config enable")
apid = parse_dic(cConf)
if apid.get("user") is None:
print ("Warning. no user defined in api_conf keypairs, skiping graph generation.")
return None
if apid.get("pass") is None:
print ("Warning. no password defined in api_conf keypairs, skiping graph generation.")
return None
if apid.get("api_pass") is None:
print ("Warning. no api pass defined in api_conf keypairs, skiping graph generation.")
return None
if apid.get("api_url") is None:
apid['api_url'] = "http://127.0.0.1/pandora_console/include/api.php"
#print(f"api_url: {apid['api_url']}")
return apid
else:
return None
def parse_graph_conf(cGraph):
"""Check module graph parameters """
if cGraph :
# Parse Api config
graphd = parse_dic(cGraph)
if graphd.get("module_id") is None:
print ("Warning. no module_id defined in module_graph keypairs, skiping graph generation.")
return
if graphd.get("interval") is None:
graphd["interval"] = 3600
return graphd
else:
print("Warning. no module_graph keypairs defined, skiping graph generation")
return None
def get_graph_by_moduleid (baseUrl,pUser, pPass, apiPass, moduleId, graphInterval, sep="url_encode_separator_%7C") :
"""Call Pandorafms api to get graph"""
try:
url = f"{baseUrl}?op=get&op2=module_graph&id={moduleId}&other={graphInterval}%7C1&other_mode={sep}C&apipass={apiPass}&api=1&user={pUser}&pass={pPass}"
graph = requests.get(url)
if graph.status_code != 200:
print (f"Error requested api url, status code: {graph.status_code}. Skiping graph generation")
return None
if graph.text == "auth error":
print (f"Error requested Pandora api url, status code: {graph.text}. Skiping graph generation")
return None
if graph.text == "Id does not exist in database.":
print (f"Error requested Pandora api url, status code: {graph.text}. Skiping graph generation")
return None
except:
print("Error requested api url. Skiping graph generation")
return None
return graph
def send_message(message, channel, client, feddback=None):
"""Send text message as slack bot"""
try:
response = client.chat_postMessage(channel=channel, text=message)
assert response["message"]["text"] == message
if feddback is not None: print(feddback)
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an Slack auth error: {e.response['error']}")
exit()
def send_image(imagepath, channel, client) :
"""Send file as slack bot"""
try:
response = client.files_upload(channels=channel, file=imagepath)
assert response["file"] # the uploaded file
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"File Got an error: {e.response['error']}")
# Main
# Intance the client object
client = WebClient(token=args.token)
# Compose message
messageString = compose_message(args.data, args.tittle, args.emoji, args.desc, args.footer)
# Parse api config
if args.api_conf :
api = parse_api_conf(args.api_conf)
# Parse graph config
if api is not None:
graph_cfg = parse_graph_conf(args.module_graph)
## Generate graph
if graph_cfg is not None :
graph = get_graph_by_moduleid (api["api_url"],api["user"], api["pass"], api["api_pass"], graph_cfg["module_id"], graph_cfg["interval"])
if graph is not None:
try:
filename = f"{args.tmp_dir}/graph_{graph_cfg['module_id']}.{datetime.now().strftime('%s')}.png"
with open(filename, "wb") as f:
f.write(b64decode(graph.text))
f.close
print (f"Graph generated on temporary file {filename}")
except Exception as e :
print(f"Error, cant generate graph file: {e}")
filename = None
else: filename = None
# Send message
send_message(messageString, args.channel, client, "> Mesage sent succefuly")
if filename is not None:
if os.path.isfile(filename): send_image(filename, args.channel, client)
if args.footer: send_message(args.footer, args.channel, client)
try:
os.remove(filename)
except:
exit()

View File

@ -0,0 +1,6 @@
certifi==2020.11.8
chardet==3.0.4
idna==2.10
requests==2.24.0
slack-sdk==3.0.0
urllib3==1.25.11

View File

@ -0,0 +1,14 @@
#exetution example
python3 pandora-slack-cli.py -d "Agent=Server22,Module=test_module,Group=Servers,State=Critical,Data=22,Timestamp=2020-11-04 11:14:00" \
-t xoxb-1506287138481-1518221486533-V3QVzyBbS6lQnTKdfrdwCqYI \
-c "varios" \
-e ":red_circle:" \
-T "PandoraFMS alert" \
-D "El agente x esta en estado critico" \
-F "Pandora FMS" \
--api_conf "user=admin,pass=pandora,api_pass=pandora,api_url=http://192.168.80.43/pandora_console/include/api.php" \
--module_graph "module_id=62, interval=3600" --tmp_dir /tmp
# Pandora FMS command definition example
python3 /usr/share/pandora_server/util/pandora-slack/pandora-slack-cli.py -d "_field1_" -t _field2_ -c "_field3_" -e "_field4_" -T "_field5_" -D "_field6_" -F "Pandora FMS" --api_conf "_field7_" --module_graph "_field8_" --tmp_dir /tmp

View File

@ -0,0 +1,27 @@
import requests, argparse, json, sys, os
### Variables and arg parser ###
parser = argparse.ArgumentParser(description='Bot telegram cli')
parser.add_argument('-m', '--message', help='Message to be send', required=True)
parser.add_argument('-t', '--token', help='Bot token', required=True)
parser.add_argument('-c', '--chat_id', help='chat id to send messages', required=True)
args = parser.parse_args()
def send(mssg, chatId, token):
url = f"https://api.telegram.org/bot{token}/sendMessage"
headers = {'content-type': 'application/json'}
data = {
"chat_id": chatId,
"text": mssg
}
response = requests.get(url, data=json.dumps(data), headers=headers)
r = response.json()
print(r)
send(mssg=args.message, chatId=args.chat_id, token=args.token)

View File

@ -0,0 +1,5 @@
certifi==2020.11.8
chardet==3.0.4
idna==2.10
requests==2.24.0
urllib3==1.25.11

View File

@ -0,0 +1,6 @@
#exetution example
python3 pandora-telegram-cli.py -t 1412764845:AAG-OxOKISOXwhITLFFNm6oq5YD2KI72fTQ -c -432610056 -m "Testing pandora telegram cli"
# Pandora FMS command definition example
python3 pandora-telegram-cli.py -t _field1_ -c _field2_ -m" _field3_"

View File

@ -1,5 +1,5 @@
package: pandorafms-server
Version: 7.0NG.752-210325
Version: 7.0NG.752-210329
Architecture: all
Priority: optional
Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.752-210325"
pandora_version="7.0NG.752-210329"
package_cpan=0
package_pandora=1

View File

@ -45,7 +45,7 @@ our @EXPORT = qw(
# version: Defines actual version of Pandora Server for this module only
my $pandora_version = "7.0NG.752";
my $pandora_build = "210325";
my $pandora_build = "210329";
our $VERSION = $pandora_version." ".$pandora_build;
# Setup hash

View File

@ -34,7 +34,7 @@ our @ISA = qw(Exporter);
# version: Defines actual version of Pandora Server for this module only
my $pandora_version = "7.0NG.752";
my $pandora_build = "210325";
my $pandora_build = "210329";
our $VERSION = $pandora_version." ".$pandora_build;
our %EXPORT_TAGS = ( 'all' => [ qw() ] );

View File

@ -2116,17 +2116,17 @@ sub snmp_get_command {
my $command = "snmpwalk -M$DEVNULL -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") {
$command .= " -u$self->{'snmp_auth_user'} -a$self->{'snmp_auth_method'} -A$self->{'snmp_auth_pass'} ";
$command .= " -u$self->{'snmp_auth_user'} -a $self->{'snmp_auth_method'} -A \'$self->{'snmp_auth_pass'}\' ";
}
if ($self->{'snmp_security_level'} eq "authPriv") {
$command .= " -x$self->{'snmp_privacy_method'} -X$self->{'snmp_privacy_pass'} ";
$command .= " -x$self->{'snmp_privacy_method'} -X \'$self->{'snmp_privacy_pass'}\' ";
}
} else {
$command .= " -c$community$vlan ";
$command .= " -c\'$community\'$vlan ";
}
return "$command $device $oid 2>$DEVNULL";

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_server
%define version 7.0NG.752
%define release 210325
%define release 210329
Summary: Pandora FMS Server
Name: %{name}

Some files were not shown because too many files have changed in this diff Show More