Merge remote-tracking branch 'origin/develop' into ent-5205-rpm-deb-pandora_server_enterprise

This commit is contained in:
fbsanchez 2020-04-20 10:46:30 +02:00
commit a71bf13498
94 changed files with 11156 additions and 9974 deletions

View File

@ -1,5 +1,5 @@
package: pandorafms-agent-unix package: pandorafms-agent-unix
Version: 7.0NG.744-200413 Version: 7.0NG.744-200420
Architecture: all Architecture: all
Priority: optional Priority: optional
Section: admin Section: admin

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@
# ********************************************************************** # **********************************************************************
PI_VERSION="7.0NG.744" PI_VERSION="7.0NG.744"
PI_BUILD="200413" PI_BUILD="200420"
OS_NAME=`uname -s` OS_NAME=`uname -s`
FORCE=0 FORCE=0

View File

@ -186,7 +186,7 @@ UpgradeApplicationID
{} {}
Version Version
{200413} {200420}
ViewReadme ViewReadme
{Yes} {Yes}

View File

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

View File

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

View File

@ -1,2 +1,8 @@
# pandora disable listing # pandora disable listing
Options -Indexes Options -Indexes
<Files ~ "\.log$">
Order Allow,Deny
Deny from All
</Files>

View File

@ -1,5 +1,5 @@
package: pandorafms-console package: pandorafms-console
Version: 7.0NG.744-200413 Version: 7.0NG.744-200420
Architecture: all Architecture: all
Priority: optional Priority: optional
Section: admin Section: admin

View File

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

View File

@ -1,5 +1,54 @@
START TRANSACTION; START TRANSACTION;
ALTER TABLE tagente_modulo MODIFY COLUMN `custom_string_1` MEDIUMTEXT;
ALTER TABLE `trecon_task` MODIFY COLUMN `id_network_profile` TEXT;
ALTER TABLE `trecon_task` CHANGE COLUMN `create_incident` `review_mode` TINYINT(1) UNSIGNED DEFAULT 0;
ALTER TABLE `trecon_task` ADD COLUMN `subnet_csv` TINYINT(1) UNSIGNED DEFAULT 1;
UPDATE `trecon_task` SET `review_mode` = 1;
ALTER TABLE trecon_task add column `auto_monitor` TINYINT(1) UNSIGNED DEFAULT 1 AFTER `auth_strings`;
UPDATE `trecon_task` SET `auto_monitor` = 0;
CREATE TABLE `tdiscovery_tmp_agents` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`label` varchar(600) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`data` MEDIUMTEXT,
`review_date` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_rt` (`id_rt`),
INDEX `label` (`label`),
CONSTRAINT `tdta_trt` FOREIGN KEY (`id_rt`) REFERENCES `trecon_task` (`id_rt`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tdiscovery_tmp_connections` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`dev_1` text,
`dev_2` text,
`if_1` text,
`if_2` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tpen` (
`pen` int(10) unsigned NOT NULL,
`manufacturer` TEXT,
`description` TEXT,
PRIMARY KEY (`pen`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `tnetwork_profile_pen` (
`pen` int(10) unsigned NOT NULL,
`id_np` int(10) unsigned NOT NULL,
CONSTRAINT `fk_network_profile_pen_pen` FOREIGN KEY (`pen`)
REFERENCES `tpen` (`pen`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_network_profile_pen_id_np` FOREIGN KEY (`id_np`)
REFERENCES `tnetwork_profile` (`id_np`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `twidget_dashboard` ADD COLUMN `position` TEXT NOT NULL default ''; ALTER TABLE `twidget_dashboard` ADD COLUMN `position` TEXT NOT NULL default '';
ALTER TABLE `tagente_estado` ADD COLUMN `last_status_change` bigint(20) NOT NULL default '0'; ALTER TABLE `tagente_estado` ADD COLUMN `last_status_change` bigint(20) NOT NULL default '0';
@ -10,4 +59,111 @@ ALTER TABLE `talert_templates` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0;
ALTER TABLE `tevent_alert` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0; ALTER TABLE `tevent_alert` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0;
ALTER TABLE `talert_snmp` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0; ALTER TABLE `talert_snmp` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0;
UPDATE twidget SET description='Show a visual console' WHERE class_name='MapsMadeByUser';
UPDATE twidget SET description='Clock' WHERE class_name='ClockWidget';
UPDATE twidget SET description='Group status' WHERE class_name='SystemGroupStatusWidget';
INSERT IGNORE INTO `tpen` VALUES (9,'cisco','Cisco&#x20;System'),(11,'hp','Hewlett&#x20;Packard'),(2021,'general_snmp','U.C.&#x20;Davis,&#x20;ECE&#x20;Dept.&#x20;Tom'),(2636,'juniper','Juniper&#x20;Networks'),(3375,'f5','F5&#x20;Labs'),(8072,'general_snmp','Net&#x20;SNMP'),(12356,'fortinet','Fortinet');
SET @template_name = 'Network&#x20;Management';
SET @template_description = 'Basic network monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Network Management')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Cisco&#x20;MIBS';
SET @template_description = 'Cisco devices monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Cisco MIBS' OR g.name = 'Catalyst 2900')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 9)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Linux&#x20;System';
SET @template_description = 'Linux system monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
SET @module_group = 'Linux';
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Linux' OR g.name = 'UCD Mibs (Linux, UCD-SNMP)')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 2021 OR p.pen = 2636)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;System';
SET @template_description = 'Windows system monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Microsoft&#x20;Windows' OR g.name = 'Windows System')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Hardware';
SET @template_description = 'Windows hardware monitoring templae (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Hardware Layer')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Active&#x20;Directory';
SET @template_description = 'Active directory monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows AD' OR g.name = 'AD&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;IIS';
SET @template_description = 'IIS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows IIS' OR g.name = 'IIS&#x20;services')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Exchange';
SET @template_description = 'Exchange monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Exchange' OR g.name = 'Exchange&#x20;Services' OR g.name = 'Exchange&#x20;TCP&#x20;Ports')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;LDAP';
SET @template_description = 'LDAP monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows LDAP')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MDSTC';
SET @template_description = 'MDSTC monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows MSDTC')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Printers';
SET @template_description = 'Windows printers monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Printers')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;DNS';
SET @template_description = 'Windows DNS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows&#x20;DNS' OR g.name = 'DNS&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MS&#x20;SQL&#x20;Server';
SET @template_description = 'MS SQL Server monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MS&#x20;SQL&#x20;Server')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Oracle';
SET @template_description = 'Oracle monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Oracle')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'MySQL';
SET @template_description = 'MySQL monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MySQL')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Antivirus';
SET @template_description = 'Windows antivirus monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Norton' OR g.name = 'Panda' OR g.name = 'McAfee' OR g.name = 'Bitdefender' OR g.name = 'BullGuard' OR g.name = 'AVG' OR g.name = 'Kaspersky')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
COMMIT; COMMIT;

View File

@ -1448,6 +1448,7 @@ ALTER TABLE `tagente_modulo` DROP COLUMN `ff_normal`,
MODIFY COLUMN `ff_type` tinyint(1) unsigned NULL DEFAULT '0', MODIFY COLUMN `ff_type` tinyint(1) unsigned NULL DEFAULT '0',
MODIFY COLUMN `dynamic_next` bigint(20) NOT NULL DEFAULT '0', MODIFY COLUMN `dynamic_next` bigint(20) NOT NULL DEFAULT '0',
MODIFY COLUMN `dynamic_two_tailed` tinyint(1) unsigned NULL DEFAULT '0'; MODIFY COLUMN `dynamic_two_tailed` tinyint(1) unsigned NULL DEFAULT '0';
ALTER TABLE tagente_modulo MODIFY COLUMN `custom_string_1` MEDIUMTEXT;
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- Table `tagente_datos` -- Table `tagente_datos`
@ -1476,6 +1477,28 @@ ALTER TABLE tnetwork_component ADD COLUMN `dynamic_two_tailed` tinyint(1) unsign
ALTER TABLE `tnetwork_component` ADD COLUMN `ff_type` tinyint(1) unsigned default '0'; ALTER TABLE `tnetwork_component` ADD COLUMN `ff_type` tinyint(1) unsigned default '0';
ALTER TABLE `tnetwork_component` MODIFY COLUMN `ff_type` tinyint(1) unsigned NULL DEFAULT '0'; ALTER TABLE `tnetwork_component` MODIFY COLUMN `ff_type` tinyint(1) unsigned NULL DEFAULT '0';
-- ----------------------------------------------------------------------
-- Table `tpen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tpen` (
`pen` int(10) unsigned NOT NULL,
`manufacturer` TEXT,
`description` TEXT,
PRIMARY KEY (`pen`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tnetwork_profile_pen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tnetwork_profile_pen` (
`pen` int(10) unsigned NOT NULL,
`id_np` int(10) unsigned NOT NULL,
CONSTRAINT `fk_network_profile_pen_pen` FOREIGN KEY (`pen`)
REFERENCES `tpen` (`pen`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_network_profile_pen_id_np` FOREIGN KEY (`id_np`)
REFERENCES `tnetwork_profile` (`id_np`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- Table `tagente` -- Table `tagente`
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
@ -1661,7 +1684,39 @@ ALTER TABLE `trecon_task` ADD COLUMN `type` int(11) NOT NULL DEFAULT '0',
MODIFY COLUMN `wmi_enabled` tinyint(1) unsigned NULL DEFAULT '0', MODIFY COLUMN `wmi_enabled` tinyint(1) unsigned NULL DEFAULT '0',
MODIFY COLUMN `auth_strings` text NULL, MODIFY COLUMN `auth_strings` text NULL,
MODIFY COLUMN `autoconfiguration_enabled` tinyint(1) unsigned NULL DEFAULT '0', MODIFY COLUMN `autoconfiguration_enabled` tinyint(1) unsigned NULL DEFAULT '0',
MODIFY COLUMN `summary` text NULL; MODIFY COLUMN `summary` text NULL,
MODIFY COLUMN `id_network_profile` text,
CHANGE COLUMN `create_incident` `review_mode` TINYINT(1) UNSIGNED DEFAULT 1,
ADD COLUMN `subnet_csv` TINYINT(1) UNSIGNED DEFAULT 0;
-- Old recon always report.
UPDATE `trecon_task` SET `review_mode` = 1;
-- ----------------------------------------------------------------------
-- Table `tdiscovery_tmp`
-- ----------------------------------------------------------------------
CREATE TABLE `tdiscovery_tmp_agents` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`label` varchar(600) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`data` MEDIUMTEXT,
`review_date` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_rt` (`id_rt`),
INDEX `label` (`label`),
CONSTRAINT `tdta_trt` FOREIGN KEY (`id_rt`) REFERENCES `trecon_task` (`id_rt`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tdiscovery_tmp_connections` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`dev_1` text,
`dev_2` text,
`if_1` text,
`if_2` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- Table `twidget` AND Table `twidget_dashboard` -- Table `twidget` AND Table `twidget_dashboard`
@ -2128,6 +2183,8 @@ ALTER TABLE `trecon_task` ADD COLUMN `snmp_auth_method` varchar(25) NOT NULL def
ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_method` varchar(25) NOT NULL default ''; ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_method` varchar(25) NOT NULL default '';
ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_pass` varchar(255) NOT NULL default ''; ALTER TABLE `trecon_task` ADD COLUMN `snmp_privacy_pass` varchar(255) NOT NULL default '';
ALTER TABLE `trecon_task` ADD COLUMN `snmp_security_level` varchar(25) NOT NULL default ''; ALTER TABLE `trecon_task` ADD COLUMN `snmp_security_level` varchar(25) NOT NULL default '';
ALTER TABLE trecon_task add column `auto_monitor` TINYINT(1) UNSIGNED DEFAULT 1 AFTER `auth_strings`;
UPDATE `trecon_task` SET `auto_monitor` = 0;
-- --------------------------------------------------------------------- -- ---------------------------------------------------------------------
-- Table `tagent_custom_fields_filter` -- Table `tagent_custom_fields_filter`
@ -2536,3 +2593,132 @@ INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `ma
INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;system&#x20;load','Current&#x20;load&#x20;&#40;5&#x20;min&#41;',43,34,0,0,300,0,'uptime&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;,&#039;','','','',6,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0); INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;system&#x20;load','Current&#x20;load&#x20;&#40;5&#x20;min&#41;',43,34,0,0,300,0,'uptime&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;,&#039;','','','',6,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0);
INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;memory&#x20;percent','Available&#x20;memory&#x20;%',43,34,0,0,300,0,'free&#x20;|&#x20;grep&#x20;Mem&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$NF/$2&#x20;*&#x20;100}&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'%','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0); INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;memory&#x20;percent','Available&#x20;memory&#x20;%',43,34,0,0,300,0,'free&#x20;|&#x20;grep&#x20;Mem&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$NF/$2&#x20;*&#x20;100}&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'',0.00,0.00,'',0,'','linux','',0,0,0.000000000000000,'%','nowizard','','','','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0);
INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;disk&#x20;/','Available&#x20;free&#x20;space&#x20;in&#x20;mountpoint&#x20;/',43,34,0,0,300,0,'df&#x20;/&#x20;|&#x20;tail&#x20;-n&#x20;+2&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;%&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'0.00',0.00,0.00,'',0,'','inherited','',0,0,0.000000000000000,'','nowizard','','nowizard','0','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0); INSERT INTO `tnetwork_component` (`name`, `description`, `id_group`, `type`, `max`, `min`, `module_interval`, `tcp_port`, `tcp_send`, `tcp_rcv`, `snmp_community`, `snmp_oid`, `id_module_group`, `id_modulo`, `id_plugin`, `plugin_user`, `plugin_pass`, `plugin_parameter`, `max_timeout`, `max_retries`, `history_data`, `min_warning`, `max_warning`, `max_critical`, `str_warning`, `min_ff_event`, `min_critical`, `custom_string_2`, `str_critical`, `custom_integer_1`, `custom_string_1`, `post_process`, `custom_string_3`, `wizard_level`, `custom_integer_2`, `critical_instructions`, `unit`, `unknown_instructions`, `macros`, `warning_inverse`, `warning_instructions`, `tags`, `critical_inverse`, `module_macros`, `id_category`, `min_ff_event_warning`, `disabled_types_event`, `ff_type`, `min_ff_event_normal`, `dynamic_interval`, `min_ff_event_critical`, `dynamic_min`, `each_ff`, `dynamic_two_tailed`, `dynamic_max`, `dynamic_next`) VALUES ('Linux&#x20;available&#x20;disk&#x20;/','Available&#x20;free&#x20;space&#x20;in&#x20;mountpoint&#x20;/',43,34,0,0,300,0,'df&#x20;/&#x20;|&#x20;tail&#x20;-n&#x20;+2&#x20;|&#x20;awk&#x20;&#039;{print&#x20;$&#40;NF-1&#41;}&#039;&#x20;|&#x20;tr&#x20;-d&#x20;&#039;%&#039;','','','',4,2,0,'','','',0,0,1,0.00,0.00,'0.00',0.00,0.00,'',0,'','inherited','',0,0,0.000000000000000,'','nowizard','','nowizard','0','',0,0,0,'','{\"going_unknown\":1}','',0,0,0,0,0,0,0,0,0,0);
--
-- Dumping data for table `tpen`
--
INSERT IGNORE INTO `tpen`
VALUES
(9,'cisco','Cisco&#x20;System'),
(11,'hp','Hewlett&#x20;Packard'),
(2021,'general_snmp','U.C.&#x20;Davis,&#x20;ECE&#x20;Dept.&#x20;Tom'),
(2636,'juniper','Juniper&#x20;Networks'),
(3375,'f5','F5&#x20;Labs'),
(8072,'general_snmp','Net&#x20;SNMP'),
(12356,'fortinet','Fortinet')
;
--
-- Dumping data for table `tnetwork_profile` and `tnetwork_profile_pen`
--
SET @template_name = 'Network&#x20;Management';
SET @template_description = 'Basic network monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Network Management')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Cisco&#x20;MIBS';
SET @template_description = 'Cisco devices monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Cisco MIBS' OR g.name = 'Catalyst 2900')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 9)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Linux&#x20;System';
SET @template_description = 'Linux system monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
SET @module_group = 'Linux';
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Linux' OR g.name = 'UCD Mibs (Linux, UCD-SNMP)')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 2021 OR p.pen = 2636)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;System';
SET @template_description = 'Windows system monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Microsoft&#x20;Windows' OR g.name = 'Windows System')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Hardware';
SET @template_description = 'Windows hardware monitoring templae (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Hardware Layer')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Active&#x20;Directory';
SET @template_description = 'Active directory monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows AD' OR g.name = 'AD&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;IIS';
SET @template_description = 'IIS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows IIS' OR g.name = 'IIS&#x20;services')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Exchange';
SET @template_description = 'Exchange monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Exchange' OR g.name = 'Exchange&#x20;Services' OR g.name = 'Exchange&#x20;TCP&#x20;Ports')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;LDAP';
SET @template_description = 'LDAP monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows LDAP')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MDSTC';
SET @template_description = 'MDSTC monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows MSDTC')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Printers';
SET @template_description = 'Windows printers monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Printers')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;DNS';
SET @template_description = 'Windows DNS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows&#x20;DNS' OR g.name = 'DNS&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MS&#x20;SQL&#x20;Server';
SET @template_description = 'MS SQL Server monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MS&#x20;SQL&#x20;Server')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Oracle';
SET @template_description = 'Oracle monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Oracle')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'MySQL';
SET @template_description = 'MySQL monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MySQL')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Antivirus';
SET @template_description = 'Windows antivirus monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Norton' OR g.name = 'Panda' OR g.name = 'McAfee' OR g.name = 'Bitdefender' OR g.name = 'BullGuard' OR g.name = 'AVG' OR g.name = 'Kaspersky')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
-- Update widget.
UPDATE twidget SET description='Show a visual console' WHERE class_name='MapsMadeByUser';
UPDATE twidget SET description='Clock' WHERE class_name='ClockWidget';
UPDATE twidget SET description='Group status' WHERE class_name='SystemGroupStatusWidget';

View File

@ -283,7 +283,6 @@ if ($id_agent_module) {
// Security level Could be noAuthNoPriv | authNoPriv | authPriv. // Security level Could be noAuthNoPriv | authNoPriv | authPriv.
$snmp3_security_level = $module['custom_string_3']; $snmp3_security_level = $module['custom_string_3'];
$ip_target = $module['ip_target']; $ip_target = $module['ip_target'];
$disabled = $module['disabled']; $disabled = $module['disabled'];
$id_export = $module['id_export']; $id_export = $module['id_export'];
@ -297,6 +296,7 @@ if ($id_agent_module) {
$custom_integer_2 = $module['custom_integer_2']; $custom_integer_2 = $module['custom_integer_2'];
$custom_string_1 = $module['custom_string_1']; $custom_string_1 = $module['custom_string_1'];
$custom_string_2 = $module['custom_string_2']; $custom_string_2 = $module['custom_string_2'];
$custom_string_3 = $module['custom_string_3'];
$max_timeout = $module['max_timeout']; $max_timeout = $module['max_timeout'];
$max_retries = $module['max_retries']; $max_retries = $module['max_retries'];
$custom_id = $module['custom_id']; $custom_id = $module['custom_id'];

View File

@ -137,11 +137,31 @@ if (!empty($sub)) {
$sub = []; $sub = [];
if (check_acl($config['id_user'], 0, 'PM')) { if (check_acl($config['id_user'], 0, 'PM')) {
$sub['godmode/modules/manage_network_components']['text'] = __('Network components'); // enterprise_hook('components_submenu');
$sub['godmode/modules/manage_network_components']['id'] = 'Network components'; $sub['templates']['text'] = __('Templates');
enterprise_hook('components_submenu'); $sub['templates']['id'] = 'Templates';
$sub['godmode/modules/manage_network_templates']['text'] = __('Module templates'); $sub['templates']['type'] = 'direct';
$sub['godmode/modules/manage_network_templates']['id'] = 'Module templates'; $sub['templates']['subtype'] = 'nolink';
$sub2 = [];
$sub2['godmode/modules/manage_module_templates']['text'] = __('Module templates');
$sub2['godmode/modules/manage_module_templates']['id'] = 'Module templates';
$sub2['godmode/modules/private_enterprise_numbers']['text'] = __('Private Enterprise Numbers');
$sub2['godmode/modules/private_enterprise_numbers']['id'] = 'Private Enterprise Numbers';
$sub2['enterprise/godmode/modules/local_components']['text'] = __('Local components');
$sub2['enterprise/godmode/modules/local_components']['id'] = 'Local components';
$sub2['godmode/modules/manage_network_components']['text'] = __('Remote components');
$sub2['godmode/modules/manage_network_components']['id'] = 'Network components';
$sub['templates']['sub2'] = $sub2;
/*
$sub2['godmode/modules/manage_snmp_modules']['text'] = __('SNMP Modules');
$sub2['godmode/modules/manage_snmp_modules']['id'] = 'SNMP Modules';
$sub2['godmode/modules/manage_wmi_modules']['text'] = __('WMI Modules');
$sub2['godmode/modules/manage_wmi_modules']['id'] = 'WMI Modules';
$sub['godmode/modules/manage_block_templates']['text'] = __('Module blocks');
$sub['godmode/modules/manage_block_templates']['id'] = 'Module blocks';
*/
enterprise_hook('inventory_submenu'); enterprise_hook('inventory_submenu');
enterprise_hook('autoconfiguration_menu'); enterprise_hook('autoconfiguration_menu');
enterprise_hook('agent_repository_menu'); enterprise_hook('agent_repository_menu');

View File

@ -0,0 +1,35 @@
<?php
// Pandora FMS - http://pandorafms.com
// ==================================================
// Copyright (c) 2005-2020 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.
// Load global vars
// TESTING
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/
// END
global $config;
check_login();
if (! check_acl($config['id_user'], 0, 'PM')) {
db_pandora_audit(
'ACL Violation',
'Trying to access Network Profile Management'
);
include 'general/noaccess.php';
return;
}
echo 'HOLA PRINCIPAL';

View File

@ -0,0 +1,68 @@
<?php
/**
* Module Templates management.
*
* @category Module templates management.
* @package Pandora FMS
* @subpackage Opensource
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2020 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.
global $config;
require_once $config['homedir'].'/include/class/ModuleTemplates.class.php';
// This page.
$ajaxPage = 'godmode/modules/manage_module_templates';
// Control call flow.
try {
// User access and validation is being processed on class constructor.
$obj = new ModuleTemplates($ajaxPage);
} catch (Exception $e) {
if (is_ajax()) {
echo json_encode(['error' => '[ModuleTemplates]'.$e->getMessage() ]);
exit;
} else {
echo '[ModuleTemplates]'.$e->getMessage();
}
// Stop this execution, but continue 'globally'.
return;
}
// AJAX controller.
if (is_ajax()) {
$method = get_parameter('method');
if (method_exists($obj, $method) === true) {
$obj->{$method}();
} else {
$obj->error('Method not found. ['.$method.']');
}
// Stop any execution.
exit;
} else {
// Run.
$obj->run();
}

View File

@ -66,7 +66,7 @@ if (defined('METACONSOLE')) {
} }
ui_print_page_header( ui_print_page_header(
__('Module management').' &raquo; '.__('Network component management'), __('Module management').' &raquo; '.__('Remote component management'),
'', '',
false, false,
$help_header, $help_header,

View File

@ -45,8 +45,15 @@ ui_print_page_header(
true, true,
'modulemodal' 'modulemodal'
); );
/*
// At this moment, this message is not necessary
ui_print_info_message(
__(
'This section is maintained only for legacy use. Please, keep in mind use %s for manage template blocks.',
'<a href="'.ui_get_full_url('index.php?logged=1&sec=gmodules&sec2=godmode/modules/manage_block_templates').'">Module Blocks</a>'
)
);
*/
require_once 'include/functions_network_profiles.php'; require_once 'include/functions_network_profiles.php';
$delete_profile = (bool) get_parameter('delete_profile'); $delete_profile = (bool) get_parameter('delete_profile');

View File

@ -0,0 +1,68 @@
<?php
/**
* Private Enterprise Number managemtn.
*
* @category PEN management.
* @package Pandora FMS
* @subpackage Opensource
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2019 Artica Soluciones Tecnologicas
* Please see http://pandorafms.org for full contribution list
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation for version 2.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ============================================================================
*/
// Begin.
global $config;
require_once $config['homedir'].'/include/class/ConfigPEN.class.php';
// This page.
$ajaxPage = 'godmode/modules/private_enterprise_numbers';
// Control call flow.
try {
// User access and validation is being processed on class constructor.
$obj = new ConfigPEN($ajaxPage);
} catch (Exception $e) {
if (is_ajax()) {
echo json_encode(['error' => '[ConfigPEN]'.$e->getMessage() ]);
exit;
} else {
echo '[ConfigPEN]'.$e->getMessage();
}
// Stop this execution, but continue 'globally'.
return;
}
// AJAX controller.
if (is_ajax()) {
$method = get_parameter('method');
if (method_exists($obj, $method) === true) {
$obj->{$method}();
} else {
$obj->error('Method not found. ['.$method.']');
}
// Stop any execution.
exit;
} else {
// Run.
$obj->run();
}

View File

@ -1,5 +1,7 @@
<?php <?php
enterprise_include_once('include/functions_license.php');
global $config; global $config;
check_login(); check_login();
@ -48,6 +50,9 @@ function get_wiz_class($str)
case 'ctask': case 'ctask':
return 'ConsoleTasks'; return 'ConsoleTasks';
case 'deploymentCenter':
return 'DeploymentCenter';
default: default:
// Main, show header. // Main, show header.
ui_print_page_header( ui_print_page_header(
@ -124,7 +129,21 @@ $classname_selected = get_wiz_class($wiz_in_use);
// Else: class not found pseudo exception. // Else: class not found pseudo exception.
if ($classname_selected !== null) { if ($classname_selected !== null) {
$wiz = new $classname_selected($page); $wiz = new $classname_selected((int) $page);
// AJAX controller.
if (is_ajax()) {
$method = get_parameter('method');
if (method_exists($wiz, $method) === true) {
$wiz->{$method}();
} else {
$wiz->error('Method not found. ['.$method.']');
}
// Stop any execution.
exit;
} else {
$result = $wiz->run(); $result = $wiz->run();
if (is_array($result) === true) { if (is_array($result) === true) {
// Redirect control and messages to DiscoveryTasklist. // Redirect control and messages to DiscoveryTasklist.
@ -133,6 +152,7 @@ if ($classname_selected !== null) {
$result = $wiz->run($result['msg'], $result['result']); $result = $wiz->run($result['msg'], $result['result']);
} }
} }
}
if ($classname_selected === null) { if ($classname_selected === null) {
// Load classes and print selector. // Load classes and print selector.

View File

@ -26,7 +26,9 @@
* ============================================================================ * ============================================================================
*/ */
require_once __DIR__.'/Wizard.main.php'; global $config;
require_once $config['homedir'].'/include/class/HTML.class.php';
require_once $config['homedir'].'/include/functions_users.php'; require_once $config['homedir'].'/include/functions_users.php';
require_once $config['homedir'].'/include/functions_reports.php'; require_once $config['homedir'].'/include/functions_reports.php';
require_once $config['homedir'].'/include/functions_cron.php'; require_once $config['homedir'].'/include/functions_cron.php';
@ -34,11 +36,13 @@ enterprise_include_once('include/functions_tasklist.php');
enterprise_include_once('include/functions_cron.php'); enterprise_include_once('include/functions_cron.php');
ui_require_css_file('task_list'); ui_require_css_file('task_list');
ui_require_css_file('simTree');
ui_require_javascript_file('simTree');
/** /**
* Defined as wizard to guide user to explore running tasks. * Defined as wizard to guide user to explore running tasks.
*/ */
class DiscoveryTaskList extends Wizard class DiscoveryTaskList extends HTML
{ {
@ -119,8 +123,9 @@ class DiscoveryTaskList extends Wizard
} }
$force_run = (bool) get_parameter('force_run'); $force_run = (bool) get_parameter('force_run');
if ($force_run === true) { $force = (bool) get_parameter('force');
return $this->forceConsoleTask(); if ($force_run === true || $force === true) {
return $this->forceTask();
} }
$delete_console_task = (bool) get_parameter('delete_console_task'); $delete_console_task = (bool) get_parameter('delete_console_task');
@ -163,6 +168,16 @@ class DiscoveryTaskList extends Wizard
'attributes' => 'class="sub cancel"', 'attributes' => 'class="sub cancel"',
'return' => true, 'return' => true,
], ],
],[
'class' => 'action-buttons rule-builder-actions',
'arguments' => [
'name' => 'refresh',
'label' => __('Refresh'),
'type' => 'button',
'attributes' => 'class="sub upd"',
'return' => true,
'script' => 'location.reload();',
],
], ],
], ],
]; ];
@ -237,7 +252,7 @@ class DiscoveryTaskList extends Wizard
* *
* @return void * @return void
*/ */
public function forceConsoleTask() public function forceTask()
{ {
global $config; global $config;
@ -252,12 +267,46 @@ class DiscoveryTaskList extends Wizard
$id_console_task = (int) get_parameter('id_console_task'); $id_console_task = (int) get_parameter('id_console_task');
if ($id_console_task !== null) { if ($id_console_task != null) {
// --------------------------------
// FORCE A CONSOLE TASK
// --------------------------------
enterprise_hook('cron_task_run', [$id_console_task, true]); enterprise_hook('cron_task_run', [$id_console_task, true]);
// Trick to avoid double execution. // Trick to avoid double execution.
header('Location: '.$this->url); header('Location: '.$this->url);
} else {
// --------------------------------
// FORCE A RECON TASK
// --------------------------------
if (check_acl($config['id_user'], 0, 'AW')) {
if (isset($_GET['force'])) {
$id = (int) get_parameter_get('force', 0);
// Schedule execution.
$review_mode = db_get_value(
'review_mode',
'trecon_task',
'id_rt',
$id
);
if ($review_mode != DISCOVERY_STANDARD) {
// Force re-scan for supervised tasks.
$review_mode = DISCOVERY_REVIEW;
} }
db_process_sql_update(
'trecon_task',
[
'utimestamp' => 0,
'status' => 1,
'review_mode' => $review_mode,
],
['id_rt' => $id]
);
header('Location: '.$this->url);
}
}
}
} }
@ -330,28 +379,7 @@ class DiscoveryTaskList extends Wizard
include_once $config['homedir'].'/include/functions_servers.php'; include_once $config['homedir'].'/include/functions_servers.php';
include_once $config['homedir'].'/include/functions_network_profiles.php'; include_once $config['homedir'].'/include/functions_network_profiles.php';
$modules_server = 0;
$total_modules = 0;
$total_modules_data = 0;
// --------------------------------
// FORCE A RECON TASK
// --------------------------------
if (check_acl($config['id_user'], 0, 'AW')) {
if (isset($_GET['force'])) {
$id = (int) get_parameter_get('force', 0);
servers_force_recon_task($id);
header(
'Location: '.ui_get_full_url(
'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist'
)
);
}
}
$recon_tasks = db_get_all_rows_sql('SELECT * FROM trecon_task'); $recon_tasks = db_get_all_rows_sql('SELECT * FROM trecon_task');
$user_groups = implode(',', array_keys(users_get_groups()));
// Show network tasks for Recon Server. // Show network tasks for Recon Server.
if ($recon_tasks === false) { if ($recon_tasks === false) {
$recon_tasks = []; $recon_tasks = [];
@ -368,18 +396,22 @@ class DiscoveryTaskList extends Wizard
$table->data = []; $table->data = [];
$table->align = []; $table->align = [];
$table->headstyle = []; $table->headstyle = [];
$table->style = [];
$table->style[4] = 'word-break: break-word;';
for ($i = 0; $i < 9; $i++) { for ($i = 0; $i < 9; $i++) {
$table->headstyle[$i] = 'text-align: left;'; $table->headstyle[$i] = 'text-align: left;';
} }
// Name.
$table->headstyle[4] .= 'min-width: 100px; width: 600px;';
// Status. // Status.
$table->headstyle[5] .= 'min-width: 100px; width: 100px;'; $table->headstyle[5] .= 'min-width: 50px; width: 100px;';
// Task type. // Task type.
$table->headstyle[6] .= 'min-width: 200px; width: 150px;'; $table->headstyle[6] .= 'min-width: 150px; width: 150px;';
// Progress. // Progress.
$table->headstyle[7] .= 'min-width: 150px; width: 150px;'; $table->headstyle[7] .= 'min-width: 50px; width: 150px;';
// Updated at. // Updated at.
$table->headstyle[8] .= 'min-width: 150px; width: 150px;'; $table->headstyle[8] .= 'min-width: 50px; width: 150px;';
// Operations. // Operations.
$table->headstyle[9] .= 'min-width: 150px; width: 150px;'; $table->headstyle[9] .= 'min-width: 150px; width: 150px;';
@ -454,11 +486,20 @@ class DiscoveryTaskList extends Wizard
if ($task['disabled'] == 0 && $server_name !== '') { if ($task['disabled'] == 0 && $server_name !== '') {
if (check_acl($config['id_user'], 0, 'AW')) { if (check_acl($config['id_user'], 0, 'AW')) {
$data[0] = '<a href="'.ui_get_full_url( $data[0] = '<span class="link" onclick="force_task(\'';
$data[0] .= ui_get_full_url(
'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist&server_id='.$id_server.'&force='.$task['id_rt'] 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist&server_id='.$id_server.'&force='.$task['id_rt']
).'">'; );
$data[0] .= '\'';
if ($task['type'] == DISCOVERY_HOSTDEVICES) {
$title = __('Are you sure?');
$message = 'This action will rescan the target networks.';
$data[0] .= ', {title: \''.$title.'\', message: \''.$message.'\'}';
}
$data[0] .= ');" >';
$data[0] .= html_print_image('images/target.png', true, ['title' => __('Force')]); $data[0] .= html_print_image('images/target.png', true, ['title' => __('Force')]);
$data[0] .= '</a>'; $data[0] .= '</span>';
} }
} else if ($task['disabled'] == 2) { } else if ($task['disabled'] == 2) {
$data[0] = ui_print_help_tip( $data[0] = ui_print_help_tip(
@ -472,12 +513,12 @@ class DiscoveryTaskList extends Wizard
// Name task. // Name task.
$data[1] = ''; $data[1] = '';
if ($task['disabled'] != 2) { if ($task['disabled'] != 2) {
$data[1] .= '<a onclick="progress_task_list('.$task['id_rt'].',\''.$task['name'].'\')">'; $data[1] .= '<span class="link" onclick="progress_task_list('.$task['id_rt'].',\''.$task['name'].'\')">';
} }
$data[1] .= '<b>'.$task['name'].'</b>'; $data[1] .= '<b>'.$task['name'].'</b>';
if ($task['disabled'] != 2) { if ($task['disabled'] != 2) {
$data[1] .= '</a>'; $data[1] .= '</span>';
} }
$data[2] = $server_name; $data[2] = $server_name;
@ -496,11 +537,39 @@ class DiscoveryTaskList extends Wizard
$data[4] = '-'; $data[4] = '-';
} }
if ($task['status'] <= 0) { $can_be_reviewed = false;
if ($task['review_mode'] == DISCOVERY_STANDARD) {
if ($task['status'] <= 0
&& empty($task['summary']) === false
) {
$data[5] = __('Done'); $data[5] = __('Done');
} else if ($task['utimestamp'] == 0
&& empty($task['summary'])
) {
$data[5] = __('Not started');
} else { } else {
$data[5] = __('Pending'); $data[5] = __('Pending');
} }
} else {
if ($task['status'] <= 0
&& empty($task['summary']) === false
) {
$can_be_reviewed = true;
$data[5] = '<span class="link review" onclick="show_review('.$task['id_rt'].',\''.$task['name'].'\')">';
$data[5] .= __('Review');
$data[5] .= '</span>';
} else if ($task['utimestamp'] == 0
&& empty($task['summary'])
) {
$data[5] = __('Not started');
} else {
if ($task['review_mode'] == DISCOVERY_RESULTS) {
$data[5] = __('Processing');
} else {
$data[5] = __('Searching');
}
}
}
switch ($task['type']) { switch ($task['type']) {
case DISCOVERY_CLOUD_AZURE_COMPUTE: case DISCOVERY_CLOUD_AZURE_COMPUTE:
@ -573,14 +642,7 @@ class DiscoveryTaskList extends Wizard
true, true,
['title' => __('Discovery NetScan')] ['title' => __('Discovery NetScan')]
).'&nbsp;&nbsp;'; ).'&nbsp;&nbsp;';
$str = network_profiles_get_name(
$task['id_network_profile']
);
if (!empty($str)) {
$data[6] .= $str;
} else {
$data[6] .= __('Discovery.NetScan'); $data[6] .= __('Discovery.NetScan');
}
} else { } else {
// APP or external script recon task. // APP or external script recon task.
$data[6] = html_print_image( $data[6] = html_print_image(
@ -595,7 +657,28 @@ class DiscoveryTaskList extends Wizard
if ($task['status'] <= 0 || $task['status'] > 100) { if ($task['status'] <= 0 || $task['status'] > 100) {
$data[7] = '-'; $data[7] = '-';
} else { } else {
$data[7] = ui_progress($task['status'], '100%', 1.5); $data[7] = ui_progress(
$task['status'],
'100%',
1.9,
// Color.
'#82b92e',
// Return.
true,
// Text.
'',
// Ajax.
[
'page' => 'godmode/servers/discovery',
'interval' => 10,
'simple' => 1,
'data' => [
'wiz' => 'tasklist',
'id' => $task['id_rt'],
'method' => 'taskProgress',
],
]
);
} }
if ($task['utimestamp'] > 0) { if ($task['utimestamp'] > 0) {
@ -609,10 +692,22 @@ class DiscoveryTaskList extends Wizard
if (!$no_operations) { if (!$no_operations) {
if ($task['disabled'] != 2) { if ($task['disabled'] != 2) {
$data[9] = '<a href="#" onclick="progress_task_list('.$task['id_rt'].',\''.$task['name'].'\')">'; $data[9] = '';
if ($can_be_reviewed) {
$data[9] .= '<a href="#" onclick="show_review('.$task['id_rt'].',\''.$task['name'].'\')">';
$data[9] .= html_print_image(
'images/expand.png',
true,
['title' => __('Review results')]
);
$data[9] .= '</a>';
}
$data[9] .= '<a href="#" onclick="progress_task_list('.$task['id_rt'].',\''.$task['name'].'\')">';
$data[9] .= html_print_image( $data[9] .= html_print_image(
'images/eye.png', 'images/eye.png',
true true,
['title' => __('View summary')]
); );
$data[9] .= '</a>'; $data[9] .= '</a>';
} }
@ -623,10 +718,11 @@ class DiscoveryTaskList extends Wizard
&& $task['type'] != DISCOVERY_CLOUD_AWS_RDS && $task['type'] != DISCOVERY_CLOUD_AWS_RDS
) { ) {
if (check_acl($config['id_user'], 0, 'MR')) { if (check_acl($config['id_user'], 0, 'MR')) {
$data[9] .= '<a onclick="show_map('.$task['id_rt'].',\''.$task['name'].'\')">'; $data[9] .= '<a href="#" onclick="show_map('.$task['id_rt'].',\''.$task['name'].'\')">';
$data[9] .= html_print_image( $data[9] .= html_print_image(
'images/dynamic_network_icon.png', 'images/dynamic_network_icon.png',
true true,
['title' => __('View map')]
); );
$data[9] .= '</a>'; $data[9] .= '</a>';
} }
@ -646,13 +742,15 @@ class DiscoveryTaskList extends Wizard
) )
).'">'.html_print_image( ).'">'.html_print_image(
'images/config.png', 'images/config.png',
true true,
['title' => __('Edit task')]
).'</a>'; ).'</a>';
$data[9] .= '<a href="'.ui_get_full_url( $data[9] .= '<a href="'.ui_get_full_url(
'index.php?sec=godmode/extensions&sec2=enterprise/extensions/ipam&action=delete&id='.$tipam_task_id 'index.php?sec=godmode/extensions&sec2=enterprise/extensions/ipam&action=delete&id='.$tipam_task_id
).'" onClick="if (!confirm(\' '.__('Are you sure?').'\')) return false;">'.html_print_image( ).'" onClick="if (!confirm(\' '.__('Are you sure?').'\')) return false;">'.html_print_image(
'images/cross.png', 'images/cross.png',
true true,
['title' => __('Delete task')]
).'</a>'; ).'</a>';
} else { } else {
// Check if is a H&D, Cloud or Application or IPAM. // Check if is a H&D, Cloud or Application or IPAM.
@ -664,13 +762,15 @@ class DiscoveryTaskList extends Wizard
) )
).'">'.html_print_image( ).'">'.html_print_image(
'images/config.png', 'images/config.png',
true true,
['title' => __('Edit task')]
).'</a>'; ).'</a>';
$data[9] .= '<a href="'.ui_get_full_url( $data[9] .= '<a href="'.ui_get_full_url(
'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist&delete=1&task='.$task['id_rt'] 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=tasklist&delete=1&task='.$task['id_rt']
).'" onClick="if (!confirm(\' '.__('Are you sure?').'\')) return false;">'.html_print_image( ).'" onClick="if (!confirm(\' '.__('Are you sure?').'\')) return false;">'.html_print_image(
'images/cross.png', 'images/cross.png',
true true,
['title' => __('Delete task')]
).'</a>'; ).'</a>';
} }
} else { } else {
@ -700,9 +800,15 @@ class DiscoveryTaskList extends Wizard
// Div neccesary for modal map task. // Div neccesary for modal map task.
echo '<div id="map_task" style="display:none"></div>'; echo '<div id="map_task" style="display:none"></div>';
echo '<div id="task_review" style="display:none"></div>';
echo '<div id="msg" style="display:none"></div>';
echo '<input type="hidden" id="ajax-url" value="'.ui_get_full_url('ajax.php').'"/>';
echo '<input type="hidden" id="success-str" value="'.__('Success').'"/>';
echo '<input type="hidden" id="failed-str" value="'.__('Failed').'"/>';
unset($table); unset($table);
ui_require_javascript_file('pandora_ui');
ui_require_javascript_file('pandora_taskList'); ui_require_javascript_file('pandora_taskList');
return $return; return $return;
@ -787,4 +893,633 @@ class DiscoveryTaskList extends Wizard
} }
/**
* Returns percent of completion of target task.
*
* @return void
*/
public function taskProgress()
{
if (!is_ajax()) {
echo json_encode(['error' => true]);
return;
}
$id_task = get_parameter('id', 0);
if ($id_task <= 0) {
echo json_encode(['error' => true]);
return;
}
$status = db_get_value('status', 'trecon_task', 'id_rt', $id_task);
if ($status < 0) {
$status = 100;
}
echo json_encode($status);
}
/**
* Generates charts for progress popup.
*
* @param array $task Task.
*
* @return string Charts in HTML.
*/
private function progressTaskGraph($task)
{
$result .= '<div style="display: flex;">';
$result .= '<div class="subtitle">';
$result .= '<span>'._('Overall Progress').'</span>';
$result .= '<div style="margin-top: 25px;">';
$result .= progress_circular_bar(
$task['id_rt'],
($task['status'] < 0) ? 100 : $task['status'],
200,
200,
'#7eb641',
'%',
'',
'#3A3A3A',
0
);
$result .= '</div>';
if ($task['status'] > 0) {
switch ($task['stats']['step']) {
case STEP_SCANNING:
$str = __('Scanning network');
break;
case STEP_CAPABILITIES:
$str = __('Checking');
break;
case STEP_AFT:
$str = __('Finding AFT connectivity');
break;
case STEP_TRACEROUTE:
$str = __('Finding traceroute connectivity');
break;
case STEP_GATEWAY:
$str = __('Finding gateway connectivity');
break;
case STEP_STATISTICS:
$str = __('Searching for devices...');
break;
case STEP_APP_SCAN:
$str = __('Analyzing application...');
break;
case STEP_CUSTOM_QUERIES:
$str = __('Executing custom queries...');
break;
case STEP_MONITORING:
$str = __('Testing modules...');
break;
case STEP_PROCESSING:
$str = __('Processing results...');
break;
default:
$str = __('Processing...');
break;
}
$result .= '</div>';
$result .= '<div class="subtitle">';
$result .= '<span>'.$str.' ';
if (empty($str) === false) {
$result .= $task['stats']['c_network_name'];
}
$result .= '</span>';
$result .= '<div style="margin-top: 25px;">';
$result .= progress_circular_bar(
$task['id_rt'].'_detail',
$task['stats']['c_network_percent'],
200,
200,
'#7eb641',
'%',
'',
'#3A3A3A',
0
);
$result .= '</div></div>';
}
if ($task['review_mode'] == DISCOVERY_REVIEW) {
if ($task['status'] <= 0
&& empty($task['summary']) === false
) {
$result .= '<span class="link review" onclick="show_review('.$task['id_rt'].',\''.$task['name'].'\')">';
$result .= '&raquo;'.__('Review');
$result .= '</span>';
}
}
$result .= '</div></div>';
return $result;
}
/**
* Generates a summary table for given task.
*
* @param array $task Task.
*
* @return html code with summary.
*/
private function progressTaskSummary($task)
{
global $config;
include_once $config['homedir'].'/include/graphs/functions_d3.php';
if (is_array($task) === false) {
return '';
}
$output = '';
if (is_array($task['stats']) === false) {
$task['stats'] = json_decode($task['summary'], true);
}
if (is_array($task['stats'])) {
$i = 0;
$table = new StdClasS();
$table->class = 'databox data';
$table->width = '75%';
$table->styleTable = 'margin: 2em auto 0;border: 1px solid #ddd;background: white;';
$table->rowid = [];
$table->data = [];
if ($task['review_mode'] == DISCOVERY_RESULTS) {
$agents_review = db_get_all_rows_filter(
'tdiscovery_tmp_agents',
['id_rt' => $task['id_rt']]
);
$agents = 0;
$total = 0;
if (is_array($agents_review)) {
foreach ($agents_review as $agent) {
$data = json_decode(base64_decode($agent['data']), true);
if (is_array($data) === false) {
continue;
}
if (is_array($data['agent']) === false) {
continue;
}
// Ensure agent_id really exists.
$agent_id = agents_get_agent_id(
$data['agent']['nombre'],
true
);
if ($agent_id > 0) {
$agents++;
}
$total++;
}
}
// Content.
$table->data[$i][0] = '<b>'.__('Host&devices total').'</b>';
$table->data[$i][1] = '<span id="discovered">';
$table->data[$i][1] .= $total;
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Agents monitored').'</b>';
$table->data[$i][1] = '<span id="alive">';
$table->data[$i][1] .= $agents;
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Agents pending').'</b>';
$table->data[$i][1] = '<span id="alive">';
$table->data[$i][1] .= ($total - $agents);
$table->data[$i++][1] .= '</span>';
} else {
// Content.
$table->data[$i][0] = '<b>'.__('Hosts discovered').'</b>';
$table->data[$i][1] = '<span id="discovered">';
$table->data[$i][1] .= $task['stats']['summary']['discovered'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Alive').'</b>';
$table->data[$i][1] = '<span id="alive">';
$table->data[$i][1] .= $task['stats']['summary']['alive'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Not alive').'</b>';
$table->data[$i][1] = '<span id="not_alive">';
$table->data[$i][1] .= $task['stats']['summary']['not_alive'];
$table->data[$i++][1] .= '</span>';
if ($task['type'] == DISCOVERY_HOSTDEVICES) {
$table->data[$i][0] = '<b>'.__('Responding SNMP').'</b>';
$table->data[$i][1] = '<span id="SNMP">';
$table->data[$i][1] .= $task['stats']['summary']['SNMP'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Responding WMI').'</b>';
$table->data[$i][1] = '<span id="WMI">';
$table->data[$i][1] .= $task['stats']['summary']['WMI'];
$table->data[$i++][1] .= '</span>';
}
}
$output = '<div class="subtitle"><span>'.__('Summary').'</span></div>';
$output .= html_print_table($table, true).'</div>';
}
return $output;
}
/**
* Content of modal 'task progress', ajax only.
*
* @return void
*/
public function progressTaskDiscovery()
{
if (!is_ajax()) {
return;
}
$id_task = get_parameter('id', 0);
if ($id_task <= 0) {
echo json_encode(['error' => true]);
return;
}
$task = db_get_row('trecon_task', 'id_rt', $id_task);
$task['stats'] = json_decode($task['summary'], true);
$summary = $this->progressTaskSummary($task);
$output = '';
// Header information.
if ((int) $task['status'] <= 0 && empty($summary)) {
$output .= ui_print_info_message(
__('This task has never executed'),
'',
true
);
} else if ($task['status'] == 1
|| ($task['utimestamp'] == 0 && $task['interval_sweep'])
) {
$output .= ui_print_info_message(
__('Task queued, please wait.'),
'',
true
).'</div>';
} else {
$output .= $this->progressTaskGraph($task);
}
$output .= $summary;
echo json_encode(['html' => $output]);
}
/**
* Get a map of target task.
*
* @return void
*/
public function taskShowmap()
{
global $config;
include_once $config['homedir'].'/include/class/NetworkMap.class.php';
$id_task = get_parameter('id', 0);
$map = new NetworkMap(
[
'id_task' => $id_task,
'pure' => 1,
'widget' => true,
'map_options' => [
'map_filter' => [
'x_offs' => 120,
'node_sep' => 10,
],
],
]
);
$map->printMap();
}
/**
* Shows a modal to review results found by discovery task.
*
* @return void
*/
public function showTaskReview()
{
$id_task = get_parameter('id', 0);
if ($id_task <= 0) {
ui_print_error_message(__('Invalid task'));
return;
}
$task_data = db_get_all_rows_filter(
'tdiscovery_tmp_agents',
['id_rt' => $id_task]
);
$task = db_get_row('trecon_task', 'id_rt', $id_task);
$simple_data = [];
if (is_array($task_data)) {
foreach ($task_data as $agent) {
$data = json_decode(base64_decode($agent['data']), true);
if (is_array($data) === false) {
continue;
}
if (is_array($data['agent']) === false) {
continue;
}
$id = $data['agent']['nombre'];
// Partial.
$tmp = [
'id' => $id,
'name' => $id,
'checked' => $data['agent']['checked'],
];
// Ensure agent_id really exists.
$agent_id = agents_get_agent_id($data['agent']['nombre'], true);
if ($agent_id > 0) {
$tmp['disabled'] = 1;
$tmp['agent_id'] = $agent_id;
$tmp['checked'] = 1;
}
// Store.
$simple_data[] = $tmp;
if (is_array($data['modules'])) {
$simple_data = array_merge(
$simple_data,
array_reduce(
$data['modules'],
function ($carry, $item) use ($id, $agent_id) {
if (empty($item['name'])) {
$item['name'] = $item['nombre'];
}
if ($item['name'] == 'Host Alive') {
return $carry;
}
if (empty($item['name'])) {
$item['name'] = $item['nombre'];
}
$tmp = [
'name' => $item['name'],
'id' => $id.'-'.$item['name'],
'pid' => $id,
'checked' => $item['checked'],
];
$agentmodule_id = modules_get_agentmodule_id(
io_safe_input($item['name']),
$agent_id
);
if ($agentmodule_id > 0) {
$tmp['disabled'] = 1;
$tmp['checked'] = 1;
$tmp['module_id'] = $agentmodule_id;
}
$carry[] = $tmp;
return $carry;
},
[]
)
);
}
}
}
echo '<div>';
echo $this->progressTaskSummary($task);
echo '</div>';
if (count($simple_data) > 0) {
echo '<div class="subtitle">';
echo '<span>';
echo __('Please select devices to be monitored');
echo '</span><div class="manage">';
echo '<button onclick="$(\'.sim-tree li:not(.disabled) a\').each(function(){simTree_tree.doCheck($(this), false); simTree_tree.clickNode($(this));});">';
echo __('select all');
echo '</button>';
echo '<button onclick="$(\'.sim-tree li:not(.disabled) a\').each(function(){simTree_tree.doCheck($(this), true); simTree_tree.clickNode($(this));});">';
echo __('deselect all');
echo '</button>';
echo '<button onclick="$(\'.sim-tree-spread.sim-icon-r\').click();">';
echo __('expand all');
echo '</button>';
echo '<button onclick="$(\'.sim-tree-spread.sim-icon-d\').click();">';
echo __('collapse all');
echo '</button>';
echo '</div>';
echo '</div>';
echo '<form id="review">';
echo '<div id="tree"></div>';
echo parent::printTree(
'tree',
$simple_data
);
echo '</form>';
} else {
echo '<div class="subtitle">';
echo '<span>';
echo __('No devices found in temporary resources, please re-launch.');
echo '</span>';
echo '</div>';
}
}
/**
* Processes a review over temporary results found by discovery task.
*
* @return void
*/
public function parseTaskReview()
{
$id_task = get_parameter('id', 0);
if ($id_task <= 0) {
echo $this->error(__('Invalid task'));
return;
}
$ids = [];
$n_agents = 0;
$selection = io_safe_output(get_parameter('tree-data-tree', ''));
if (empty($selection) === false) {
$selection = json_decode($selection, true);
$ids = array_reduce(
$selection,
function ($carry, $item) use (&$n_agents) {
// String is agent-module.
$fields = explode('-', $item['id']);
$agent_name = $fields[0];
$module_name = $fields[1];
if ($module_name === null) {
// Do not count if already created.
if (db_get_value(
'id_agente',
'tagente',
'nombre',
io_safe_input($agent_name)
) === false
) {
$n_agents++;
}
}
$carry[] = $item['id'];
return $carry;
}
);
}
$task_data = db_get_all_rows_filter(
'tdiscovery_tmp_agents',
['id_rt' => $id_task]
);
// License precheck.
$license = enterprise_hook('license_get_info');
if (is_array($license) === true
&& $n_agents > ($license['limit'] - $license['count'])
) {
$limit = ($license['limit'] - $license['count']);
echo json_encode(
[
'error' => __(
'Your selection exceeds the agents available on your license. Limit %d',
$limit
),
]
);
return;
}
$summary = [];
if (is_array($ids)) {
foreach ($task_data as $row) {
$data = json_decode(base64_decode($row['data']), true);
if (is_array($data)) {
// Analize each agent.
$agent_name = $data['agent']['nombre'];
if (in_array($agent_name, $ids)) {
if ($data['agent']['checked'] != 1) {
$summary[] = '<li class="added">'.$agent_name.'</li>';
}
$data['agent']['checked'] = 1;
} else {
if ($data['agent']['checked'] == 1) {
$summary[] = '<li class="removed">'.__('Removed').' '.$agent_name.'</li>';
}
$data['agent']['checked'] = 0;
}
// Modules.
if (is_array($data['modules'])) {
$n_modules = count($data['modules']);
foreach ($data['modules'] as $module_name => $module) {
if (in_array($agent_name.'-'.$module_name, $ids)) {
if ($data['modules'][$module_name]['checked'] != 1) {
$summary[] = '<li class="added">'.$agent_name.' - '.$module_name.'</li>';
}
$data['modules'][$module_name]['checked'] = 1;
} else {
if ($data['modules'][$module_name]['checked'] == 1) {
if ($module_name != 'Host Alive') {
$summary[] = '<li class="removed">'.__('Removed').' '.$agent_name.' - '.$module_name.'</li>';
}
}
$data['modules'][$module_name]['checked'] = 0;
}
}
}
// Update data.
db_process_sql_update(
'tdiscovery_tmp_agents',
[
'data' => base64_encode(json_encode($data)),
'review_date' => date('Y-m-d H:i:s'),
],
[
'id_rt' => $id_task,
'label' => $agent_name,
]
);
}
}
}
// Schedule execution.
db_process_sql_update(
'trecon_task',
[
'utimestamp' => 0,
'status' => 1,
'review_mode' => DISCOVERY_RESULTS,
],
['id_rt' => $id_task]
);
if (empty($summary)) {
$out .= __('No changes. Re-Scheduled');
} else {
$out .= __('Scheduled for creation');
$out .= '<ul>';
$out .= join('', $summary);
$out .= '</ul>';
}
echo json_encode(
['result' => $out]
);
}
} }

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* Extension to schedule tasks on Pandora FMS Console * Defines wizard to configure discovery tasks (Host&devices)
* *
* @category Wizard * @category Wizard
* @package Pandora FMS * @package Pandora FMS
@ -58,7 +58,6 @@ class HostDevices extends Wizard
public $pageLabelsNetScan = [ public $pageLabelsNetScan = [
'NetScan definition', 'NetScan definition',
'NetScan features', 'NetScan features',
]; ];
/** /**
@ -139,6 +138,8 @@ class HostDevices extends Wizard
// Load styles. // Load styles.
parent::run(); parent::run();
ui_require_css_file('hostdevices');
$mode = get_parameter('mode', null); $mode = get_parameter('mode', null);
if ($mode === null) { if ($mode === null) {
@ -269,6 +270,8 @@ class HostDevices extends Wizard
*/ */
public function parseNetScan() public function parseNetScan()
{ {
global $config;
if ($this->page == 0) { if ($this->page == 0) {
// Check if we're updating a task. // Check if we're updating a task.
$task_id = get_parameter('task', null); $task_id = get_parameter('task', null);
@ -297,9 +300,63 @@ class HostDevices extends Wizard
$comment = get_parameter('comment', ''); $comment = get_parameter('comment', '');
$server_id = get_parameter('id_recon_server', ''); $server_id = get_parameter('id_recon_server', '');
$network = get_parameter('network', ''); $network = get_parameter('network', '');
$network_csv_enabled = (bool) get_parameter_switch(
'network_csv_enabled',
false
);
$id_group = get_parameter('id_group', ''); $id_group = get_parameter('id_group', '');
$interval = get_parameter('interval', 0); $interval = get_parameter('interval', 0);
if ($network_csv_enabled) {
if (empty($_FILES['network_csv']['type']) === false) {
if ($_FILES['network_csv']['type'] != 'text/csv'
&& $_FILES['network_csv']['type'] != 'text/plain'
&& $_FILES['network_csv']['type'] != 'application/octet-stream'
&& $_FILES['network_csv']['type'] != 'application/vnd.ms-excel'
&& $_FILES['network_csv']['type'] != 'text/x-csv'
&& $_FILES['network_csv']['type'] != 'application/csv'
&& $_FILES['network_csv']['type'] != 'application/x-csv'
&& $_FILES['network_csv']['type'] != 'text/csv'
&& $_FILES['network_csv']['type'] != 'text/comma-separated-values'
&& $_FILES['network_csv']['type'] != 'text/x-comma-separated-values'
&& $_FILES['network_csv']['type'] != 'text/tab-separated-values'
) {
$this->msg = __(
'Invalid mimetype for csv file: %s',
$_FILES['network_csv']['type']
);
return false;
}
$network = preg_split(
"/\n|,|;/",
trim(
file_get_contents(
$_FILES['network_csv']['tmp_name']
)
)
);
unlink($_FILES['network_csv']['tmp_name']);
if (empty($network) || is_array($network) === false) {
$this->msg = __(
'Invalid content readed from csv file: %s',
$_FILES['network_csv']['name']
);
return false;
}
// Sanitize.
$network = array_unique($network);
$network = array_filter(
$network,
function ($item) {
return (!empty($item));
}
);
$network = join(',', $network);
}
}
if (isset($task_id) === true) { if (isset($task_id) === true) {
// We're updating this task. // We're updating this task.
$task = db_get_row( $task = db_get_row(
@ -333,18 +390,15 @@ class HostDevices extends Wizard
if ($task_id !== null if ($task_id !== null
&& $taskname == null && $taskname == null
&& $server_id == null && $server_id == null
&& $id_group == null && empty($id_group) === true
&& $server == null && empty($network) === true
&& $datacenter == '' && empty($network_csv) === true
&& $user == '' && $interval === 0
&& $pass == ''
&& $encrypt == null
&& $interval == 0
) { ) {
// Default values, no data received. // Default values, no data received.
// User is accesing directly to this page. // User is accesing directly to this page.
if (check_acl( if (check_acl(
$config['id_usuario'], $config['id_user'],
$this->task['id_group'], $this->task['id_group'],
$this->access $this->access
) != true ) != true
@ -386,6 +440,7 @@ class HostDevices extends Wizard
$this->task['id_recon_server'] = $server_id; $this->task['id_recon_server'] = $server_id;
$this->task['id_group'] = $id_group; $this->task['id_group'] = $id_group;
$this->task['interval_sweep'] = $interval; $this->task['interval_sweep'] = $interval;
$this->task['subnet_csv'] = $network_csv_enabled;
if (isset($this->task['id_rt']) === false) { if (isset($this->task['id_rt']) === false) {
// Create. // Create.
@ -423,7 +478,10 @@ class HostDevices extends Wizard
return false; return false;
} }
$id_network_profile = get_parameter('id_network_profile', null); $id_network_profile = get_parameter('id_network_profile', []);
$review_results = get_parameter_switch('review_results');
$review_limited = (bool) get_parameter('review_limited', 0);
$auto_monitor = get_parameter_switch('auto_monitor');
$autoconf_enabled = get_parameter_switch( $autoconf_enabled = get_parameter_switch(
'autoconfiguration_enabled' 'autoconfiguration_enabled'
); );
@ -443,7 +501,7 @@ class HostDevices extends Wizard
$snmp_privacy_pass = get_parameter('snmp_privacy_pass', null); $snmp_privacy_pass = get_parameter('snmp_privacy_pass', null);
$snmp_auth_method = get_parameter('snmp_auth_method', null); $snmp_auth_method = get_parameter('snmp_auth_method', null);
$snmp_security_level = get_parameter('snmp_security_level', null); $snmp_security_level = get_parameter('snmp_security_level', null);
$auth_strings = get_parameter('auth_strings', null); $auth_strings = get_parameter('auth_strings', []);
if ($snmp_version == 3) { if ($snmp_version == 3) {
$this->task['snmp_community'] = $snmp_context; $this->task['snmp_community'] = $snmp_context;
@ -452,7 +510,28 @@ class HostDevices extends Wizard
} }
$this->task['autoconfiguration_enabled'] = $autoconf_enabled; $this->task['autoconfiguration_enabled'] = $autoconf_enabled;
$this->task['id_network_profile'] = $id_network_profile; $this->task['id_network_profile'] = '';
if (is_array($id_network_profile) === true) {
$this->task['id_network_profile'] = join(
',',
$id_network_profile
);
}
if ($review_limited === true) {
// License limited, force review.
$this->task['review_mode'] = DISCOVERY_REVIEW;
} else {
if ($review_results) {
if ($this->task['review_mode'] != DISCOVERY_RESULTS) {
$this->task['review_mode'] = DISCOVERY_REVIEW;
}
} else {
$this->task['review_mode'] = DISCOVERY_STANDARD;
}
}
$this->task['auto_monitor'] = $auto_monitor;
$this->task['snmp_enabled'] = $snmp_enabled; $this->task['snmp_enabled'] = $snmp_enabled;
$this->task['os_detect'] = $os_detect; $this->task['os_detect'] = $os_detect;
$this->task['parent_detection'] = $parent_detection; $this->task['parent_detection'] = $parent_detection;
@ -467,7 +546,13 @@ class HostDevices extends Wizard
$this->task['snmp_privacy_pass'] = $snmp_privacy_pass; $this->task['snmp_privacy_pass'] = $snmp_privacy_pass;
$this->task['snmp_auth_method'] = $snmp_auth_method; $this->task['snmp_auth_method'] = $snmp_auth_method;
$this->task['snmp_security_level'] = $snmp_security_level; $this->task['snmp_security_level'] = $snmp_security_level;
$this->task['auth_strings'] = $auth_strings; $this->task['auth_strings'] = '';
if (is_array($auth_strings) === true) {
$this->task['auth_strings'] = join(
',',
$auth_strings
);
}
if ($this->task['disabled'] == 2) { if ($this->task['disabled'] == 2) {
// Wizard finished. // Wizard finished.
@ -562,7 +647,7 @@ class HostDevices extends Wizard
// Check ACL. If user is not able to manage target task, // Check ACL. If user is not able to manage target task,
// redirect him to main page. // redirect him to main page.
if (check_acl( if (check_acl(
$config['id_usuario'], $config['id_user'],
$this->task['id_group'], $this->task['id_group'],
$this->access $this->access
) != true ) != true
@ -598,10 +683,21 @@ class HostDevices extends Wizard
} }
if ($this->page < $this->maxPagesNetScan) { if ($this->page < $this->maxPagesNetScan) {
$title = __('NetScan');
if ($this->page == 1) {
$title = __(
'"%s" features',
io_safe_output(
$this->task['name']
)
);
}
// Avoid to print header out of wizard. // Avoid to print header out of wizard.
$this->prepareBreadcrum($breadcrum); $this->prepareBreadcrum($breadcrum);
ui_print_page_header( ui_print_page_header(
__('NetScan'), $title,
'', '',
false, false,
'', '',
@ -678,7 +774,7 @@ class HostDevices extends Wizard
$form['rows'][0]['columns'][0] = [ $form['rows'][0]['columns'][0] = [
'width' => '30%', 'width' => '30%',
'style' => 'padding: 9px;', 'style' => 'padding: 9px;min-width: 250px;',
'inputs' => [ 'inputs' => [
'0' => [ '0' => [
'arguments' => [ 'arguments' => [
@ -705,7 +801,10 @@ class HostDevices extends Wizard
'name' => 'interval_manual_defined', 'name' => 'interval_manual_defined',
'return' => true, 'return' => true,
], ],
'extra' => '<span id="interval_manual_container">'.html_print_extended_select_for_time( 'extra' => '<div id="interval_manual_container"><div class="time_selection_container">'.ui_print_help_tip(
__('The minimum recomended interval for Recon Task is 5 minutes'),
true
).html_print_extended_select_for_time(
'interval', 'interval',
$this->task['interval_sweep'], $this->task['interval_sweep'],
'', '',
@ -715,10 +814,7 @@ class HostDevices extends Wizard
true, true,
false, false,
false false
).ui_print_help_tip( ).'</div></div>',
__('The minimum recomended interval for Recon Task is 5 minutes'),
true
).'</span>',
], ],
], ],
@ -728,6 +824,7 @@ class HostDevices extends Wizard
'width' => '40%', 'width' => '40%',
'padding-right' => '12%', 'padding-right' => '12%',
'padding-left' => '5%', 'padding-left' => '5%',
'style' => 'min-width: 350px',
'inputs' => [ 'inputs' => [
'0' => [ '0' => [
'label' => '<b>'.__('Task name').':</b>', 'label' => '<b>'.__('Task name').':</b>',
@ -760,6 +857,54 @@ class HostDevices extends Wizard
], ],
], ],
'2' => [ '2' => [
'label' => '<b>'.__('Use CSV file definition').':</b>'.ui_print_help_tip(
__('Define targets using csv o network definition.'),
true
),
'class' => 'no-margin',
'arguments' => [
'name' => 'network_csv_enabled',
'value' => $this->task['subnet_csv'],
'type' => 'switch',
'inline' => true,
'class' => 'discovery_full_width_input',
'onclick' => 'toggleNetwork(this);',
],
],
'3' => [
'hidden' => (($this->task['subnet_csv'] == '1') ? 0 : 1),
'block_id' => 'csv_subnet',
'block_content' => [
[
'label' => '<b>'.__('Networks (csv)').':</b>'.ui_print_help_tip(
__('You can upload a CSV file. Each line must contain a network in IP/MASK format. For instance: 192.168.1.1/32'),
true
),
'arguments' => [
'name' => 'network_csv',
'type' => 'file',
'columns' => 25,
'rows' => 10,
'class' => 'discovery_full_width_input',
],
],
[
'label' => '<b>'.__('Networks (current)').':</b>'.ui_print_help_tip(
__('Plese upload a new file to overwrite this content.'),
true
),
'arguments' => [
'attributes' => 'readonly',
'type' => 'textarea',
'size' => 25,
'value' => $this->task['subnet'],
],
],
],
],
'4' => [
'hidden' => (($this->task['subnet_csv'] == '1') ? 1 : 0),
'id' => 'std_subnet',
'label' => '<b>'.__('Network').':</b>'.ui_print_help_tip( 'label' => '<b>'.__('Network').':</b>'.ui_print_help_tip(
__('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'), __('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'),
true true
@ -794,6 +939,7 @@ class HostDevices extends Wizard
$form['rows'][0]['columns'][2] = [ $form['rows'][0]['columns'][2] = [
'width' => '30%', 'width' => '30%',
'style' => 'min-width: 250px',
'inputs' => ['0' => $group_select], 'inputs' => ['0' => $group_select],
]; ];
@ -824,6 +970,7 @@ class HostDevices extends Wizard
$form['form'] = [ $form['form'] = [
'method' => 'POST', 'method' => 'POST',
'enctype' => 'multipart/form-data',
'action' => $this->url.'&mode=netscan&page='.($this->page + 1).$task_url, 'action' => $this->url.'&mode=netscan&page='.($this->page + 1).$task_url,
]; ];
@ -848,7 +995,19 @@ class HostDevices extends Wizard
$("#hidden-interval").val('.$interval.'); $("#hidden-interval").val('.$interval.');
$("#interval_units").val('.$unit.'); $("#interval_units").val('.$unit.');
} }
}).change();'; }).change();
function toggleNetwork(e) {
if (e.checked) {
$(\'#csv_subnet\').removeClass("hidden");
$(\'#std_subnet\').addClass("hidden");
} else {
$(\'#csv_subnet\').addClass("hidden");
$(\'#std_subnet\').removeClass("hidden");
}
};
';
$this->printFormAsGrid($form); $this->printFormAsGrid($form);
$this->printGoBackButton($this->url.'&page='.($this->page - 1)); $this->printGoBackButton($this->url.'&page='.($this->page - 1));
@ -878,21 +1037,101 @@ class HostDevices extends Wizard
]; ];
$form['inputs'][] = [ $form['inputs'][] = [
'extra' => '<p><h3>Please, configure task <b>'.io_safe_output($this->task['name']).'</b></h3></p>', 'label' => __('Auto discover known hardware').ui_print_help_tip(
__(
'Targets will be monitorized based on its <i>Private Enterprise Number</i>. Requires SNMP.'
),
true
),
'arguments' => [
'name' => 'auto_monitor',
'type' => 'switch',
'return' => true,
'value' => (isset($this->task['auto_monitor'])) ? $this->task['auto_monitor'] : 1,
],
]; ];
$form['inputs'][] = [ $form['inputs'][] = [
'label' => __('Module template'), 'label' => __('Module templates').ui_print_help_tip(
__(
'Module <i>Host Alive</i> will be added to discovered agents by default.'
),
true
),
'arguments' => [ 'arguments' => [
'name' => 'id_network_profile', 'name' => 'id_network_profile[]',
'type' => 'select_from_sql', 'type' => 'select_from_sql',
'sql' => 'SELECT id_np, name 'sql' => 'SELECT tn.id_np, tn.name
FROM tnetwork_profile FROM tnetwork_profile tn
ORDER BY name', LEFT JOIN `tnetwork_profile_pen` tp
ON tp.id_np = tn.id_np
WHERE tp.id_np IS NULL
ORDER BY tn.name',
'return' => true, 'return' => true,
'selected' => $this->task['id_network_profile'], 'selected' => explode(
',',
$this->task['id_network_profile']
),
'nothing_value' => 0, 'nothing_value' => 0,
'nothing' => __('None'), 'nothing' => __('None'),
'multiple' => true,
'class' => 'select_multiple',
],
];
// License precheck.
$license = enterprise_hook('license_get_info');
$n_agents = 0;
foreach (explode(',', $this->task['subnet']) as $net) {
$mask = explode('/', $net, 2)[1];
if (empty($mask)) {
$n_agents++;
} else {
$n_agents += pow(2, (32 - $mask));
}
}
$limited = false;
if (is_array($license) === true
&& $n_agents > ($license['limit'] - $license['count'])
) {
$limit = ($license['limit'] - $license['count']);
$limited = true;
}
if ($limited === true) {
ui_print_warning_message(
__(
'Configured networks could generate %d agents, your license only allows %d, \'review results\' is mandatory.',
$n_agents,
$limit
)
);
}
$form['inputs'][] = [
'label' => __('Review results').ui_print_help_tip(
__(
'Targets must be validated by user before create agents.'
),
true
),
'arguments' => [
'name' => 'review_results',
'type' => 'switch',
'return' => true,
'value' => ($this->task['review_mode'] == DISCOVERY_STANDARD) ? (($limited) ? 1 : 0) : 1,
'disabled' => $limited,
],
];
// Review limited.
$form['inputs'][] = [
'arguments' => [
'name' => 'review_limited',
'type' => 'hidden',
'return' => true,
'value' => (($limited === true) ? 1 : 0),
], ],
]; ];
@ -930,7 +1169,7 @@ class HostDevices extends Wizard
// Submit button. // Submit button.
$form['inputs'][] = [ $form['inputs'][] = [
'arguments' => [ 'arguments' => [
'name' => 'submit', 'name' => 'submit-finish',
'label' => __('Finish'), 'label' => __('Finish'),
'type' => 'submit', 'type' => 'submit',
'attributes' => 'class="sub next"', 'attributes' => 'class="sub next"',

View File

@ -41,7 +41,7 @@ class Wizard
/** /**
* Breadcrum * Breadcrum
* *
* @var array. * @var array
*/ */
public $breadcrum; public $breadcrum;
@ -233,6 +233,27 @@ class Wizard
} }
/**
* Return formatted html for error handler.
*
* @param string $message Error mesage.
*
* @return string
*/
public function error($message)
{
if (is_ajax()) {
echo json_encode(
[
'error' => ui_print_error_message($message, '', true),
]
);
} else {
return ui_print_error_message($message, '', true);
}
}
/** /**
* To be overwritten. * To be overwritten.
* *
@ -566,66 +587,40 @@ class Wizard
if (is_array($input['block_content']) === true) { if (is_array($input['block_content']) === true) {
// Print independent block of inputs. // Print independent block of inputs.
$output .= '<li id="'.$input['block_id'].'" class="'.$class.'">'; $output .= '<div id="'.$input['block_id'].'" class="wizard '.$class.'">';
$output .= '<ul class="wizard '.$input['block_class'].'">'; $output .= '<ul class="wizard '.$input['block_class'].'">';
foreach ($input['block_content'] as $input) { foreach ($input['block_content'] as $input) {
$output .= $this->printBlockAsGrid($input, $return); $output .= $this->printBlockAsGrid($input, $return);
} }
$output .= '</ul></li>'; $output .= '</ul></div>';
} else { } else {
if ($input['arguments']['type'] != 'hidden' if ($input['arguments']['type'] != 'hidden'
&& $input['arguments']['type'] != 'hidden_extended' && $input['arguments']['type'] != 'hidden_extended'
) { ) {
$id = '';
if ($input['id']) {
$id = $input['id'];
}
if ($input['arguments']['inline'] != 'true') { if ($input['arguments']['inline'] != 'true') {
$output .= '<div class="edit_discovery_input">'; $output .= '<div id="'.$id.'" class="std_input '.$class.'">';
} else { } else {
$output .= '<div style="display: flex; margin-bottom: 25px; flex-wrap: wrap;">'; $output .= '<div id="'.$id.'" class="inline_input '.$class.'">';
if (!isset($input['extra'])) {
$output .= '<div style="width: 50%;">';
}
if (isset($input['extra'])) {
$output .= '<div style="display: flex; margin-right:10px;">';
}
}
if ($input['arguments']['inline'] == 'true' && isset($input['extra'])) {
$output .= '<div style="margin-right:10px;">';
} }
$output .= '<div class="label_select">'; $output .= '<div class="label_select">';
$output .= $input['label']; $output .= $input['label'];
$output .= '</div>'; $output .= '</div>';
if ($input['arguments']['inline'] == 'true' && isset($input['extra'])) {
$output .= '</div>';
}
if ($input['arguments']['inline'] == 'true' && !isset($input['extra'])) {
$output .= '</div>';
}
if ($input['arguments']['type'] == 'text' || $input['arguments']['type'] == 'text_extended') { if ($input['arguments']['type'] == 'text' || $input['arguments']['type'] == 'text_extended') {
$output .= '<div class="discovery_text_input">'; $output .= '<div class="discovery_text_input">';
$output .= $this->printInput($input['arguments']); $output .= $this->printInput($input['arguments']);
$output .= '</div>'; $output .= '</div>';
} else if ($input['arguments']['inline'] == 'true') { } else if ($input['arguments']['inline'] == 'true') {
if (isset($input['extra'])) { $output .= '<div class="discovery_inline_input">';
$output .= '<div style="">';
$output .= '<div style="float: left;">';
} else {
$output .= '<div style="width:50%;">';
$output .= '<div style="float: right;">';
}
$output .= $this->printInput($input['arguments']); $output .= $this->printInput($input['arguments']);
$output .= '</div>'; $output .= '</div>';
$output .= '</div>';
if (isset($input['extra'])) {
$output .= '</div>';
}
} else { } else {
$output .= $this->printInput($input['arguments']); $output .= $this->printInput($input['arguments']);
} }
@ -800,7 +795,7 @@ class Wizard
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
$cb_args = $data['cb_args']; $cb_args = $data['cb_args'];
$output_head = '<form class="discovery" onsubmit="'.$form['onsubmit'].'" enctype="'.$form['enctype'].'" action="'.$form['action'].'" method="'.$form['method']; $output_head = '<form class="discovery wizard" onsubmit="'.$form['onsubmit'].'" enctype="'.$form['enctype'].'" action="'.$form['action'].'" method="'.$form['method'];
$output_head .= '" '.$form['extra'].'>'; $output_head .= '" '.$form['extra'].'>';
if ($return === false) { if ($return === false) {

View File

@ -917,9 +917,11 @@ if ($get_response) {
if ($perform_event_response) { if ($perform_event_response) {
global $config; global $config;
$command = get_parameter('target', '');
$response_id = get_parameter('response_id'); $response_id = get_parameter('response_id');
$event_id = (int) get_parameter('event_id');
$server_id = (int) get_parameter('server_id', 0);
$command = events_get_response_target($event_id, $response_id, $server_id);
$event_response = db_get_row('tevent_response', 'id', $response_id); $event_response = db_get_row('tevent_response', 'id', $response_id);
@ -1017,6 +1019,7 @@ if ($dialogue_event_response) {
$show_execute_again_btn = get_parameter('show_execute_again_btn'); $show_execute_again_btn = get_parameter('show_execute_again_btn');
$out_iterator = get_parameter('out_iterator'); $out_iterator = get_parameter('out_iterator');
$event_response = db_get_row('tevent_response', 'id', $response_id); $event_response = db_get_row('tevent_response', 'id', $response_id);
$server_id = get_parameter('server_id');
$event = db_get_row('tevento', 'id_evento', $event_id); $event = db_get_row('tevento', 'id_evento', $event_id);
@ -1067,7 +1070,8 @@ if ($dialogue_event_response) {
echo "<br><div id='response_out' style='text-align:left'></div>"; echo "<br><div id='response_out' style='text-align:left'></div>";
echo "<br><div id='re_exec_command' style='display:none;'>"; echo "<br><div id='re_exec_command' style='display:none;'>";
html_print_button(__('Execute again'), 'btn_str', false, 'perform_response(\''.$command.'\', '.$response_id.');', "class='sub next'"); html_print_button(__('Execute again'), 'btn_str', false, "perform_response({'target':'".$command."','event_id':".$event_id.",'server_id':".$server_id.'}, '.$response_id.');', "class='sub next'");
echo '</div>'; echo '</div>';
} }
break; break;

View File

@ -24,154 +24,7 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* ============================================================================ * ============================================================================
*
*
* MOVED TO DiscoveryTaskList.class.
*/ */
require_once $config['homedir'].'/include/graphs/functions_d3.php';
$progress_task_discovery = (bool) get_parameter('progress_task_discovery', 0);
$showmap = (bool) get_parameter('showmap', 0);
if ($progress_task_discovery) {
$id_task = get_parameter('id', 0);
if ($id_task <= 0) {
echo json_encode(['error' => true]);
return;
}
$task = db_get_row('trecon_task', 'id_rt', $id_task);
$global_progress = $task['status'];
$summary = json_decode($task['summary'], true);
$result = '<div id = progress_task_'.$id_task.'>';
if ($task['utimestamp']) {
$result .= '<div style="display: flex;">';
$result .= '<div style="width: 100%; text-align: center; margin-top: 40px;">';
$result .= '<span style="font-size: 1.9em; font-family: "lato-bolder", "Open Sans", sans-serif !important;">'._('Overall Progress').'</span>';
$result .= '<div style="margin-top: 25px;">';
$result .= progress_circular_bar(
$id_task,
($global_progress < 0) ? 100 : $global_progress,
200,
200,
'#7eb641',
'%',
'',
'#3A3A3A',
0
);
$result .= '</div>';
if ($global_progress > 0) {
switch ($summary['step']) {
case STEP_SCANNING:
$str = __('Scanning network');
break;
case STEP_AFT:
$str = __('Finding AFT connectivity');
break;
case STEP_TRACEROUTE:
$str = __('Finding traceroute connectivity');
break;
case STEP_GATEWAY:
$str = __('Finding gateway connectivity');
break;
default:
$str = __('Searching for devices...');
break;
}
$result .= '</div>';
$result .= '<div style="width: 100%; text-align: center; margin-top: 40px;">';
$result .= '<span style="font-size: 1.9em; font-family: "lato-bolder", "Open Sans", sans-serif !important;">'.$str.' ';
$result .= $summary['c_network_name'];
$result .= '</span>';
$result .= '<div style="margin-top: 25px;">';
$result .= progress_circular_bar(
$id_task.'_detail',
$summary['c_network_percent'],
200,
200,
'#7eb641',
'%',
'',
'#3A3A3A',
0
);
$result .= '</div></div>';
}
$result .= '</div></div>';
$i = 0;
$table = new StdClasS();
$table->class = 'databox data';
$table->width = '75%';
$table->styleTable = 'margin: 2em auto 0;border: 1px solid #ddd;background: white;';
$table->rowid = [];
$table->data = [];
// Content.
$table->data[$i][0] = '<b>'.__('Hosts discovered').'</b>';
$table->data[$i][1] = '<span id="discovered">';
$table->data[$i][1] .= $summary['summary']['discovered'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Alive').'</b>';
$table->data[$i][1] = '<span id="alive">';
$table->data[$i][1] .= $summary['summary']['alive'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Not alive').'</b>';
$table->data[$i][1] = '<span id="not_alive">';
$table->data[$i][1] .= $summary['summary']['not_alive'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Responding SNMP').'</b>';
$table->data[$i][1] = '<span id="SNMP">';
$table->data[$i][1] .= $summary['summary']['SNMP'];
$table->data[$i++][1] .= '</span>';
$table->data[$i][0] = '<b>'.__('Responding WMI').'</b>';
$table->data[$i][1] = '<span id="WMI">';
$table->data[$i][1] .= $summary['summary']['WMI'];
$table->data[$i++][1] .= '</span>';
$result .= '<div style="margin-top: 40px; text-align: center;"><span style="font-size: 1.9em; font-family: "lato-bolder", "Open Sans", sans-serif !important;">'.__('Summary').'</span></div>';
$result .= html_print_table($table, true).'</div>';
} else {
$global_progress = -1;
$result .= ui_print_error_message(
__('No data to show'),
'',
true
).'</div>';
}
$result_array['status'] = $global_progress;
$result_array['html'] = $result;
echo json_encode($result_array);
return;
}
if ($showmap) {
include_once $config['homedir'].'/include/class/NetworkMap.class.php';
$id_task = get_parameter('id', 0);
$map = new NetworkMap(
[
'id_task' => $id_task,
'pure' => 1,
'widget' => true,
]
);
$map->printMap();
}

View File

@ -0,0 +1,782 @@
<?php
/**
* Agent Wizard for SNMP and WMI
*
* @category Class
* @package Pandora FMS
* @subpackage Agent Configuration
* @version 1.0.0
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2020 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.
* ============================================================================
*/
// Get global data.
global $config;
// Necessary class for extends.
require_once $config['homedir'].'/include/class/HTML.class.php';
/**
* AgentWizard class
*/
class AgentWizard extends HTML
{
/**
* Var that contain very cool stuff
*
* @var string
*/
private $ajaxController;
/**
* Contains the URL of this
*
* @var string
*/
private $baseUrl;
/**
* Id of this current agent
*
* @var integer
*/
private $idAgent;
/**
* Wizard Section for Explore
*
* @var string
*/
private $wizardSection;
/**
* Label to show what action are performing
*
* @var string
*/
private $actionLabel;
/**
* Type of action to do
*
* @param string
*/
private $actionType;
/**
* Constructor
*
* @param string $ajax_controller Pues hace cosas to wapas.
*/
public function __construct(string $ajax_controller)
{
global $config;
// Check access.
check_login();
if (! check_acl($config['id_user'], 0, 'AR')) {
db_pandora_audit(
'ACL Violation',
'Trying to access event viewer'
);
if (is_ajax()) {
echo json_encode(['error' => 'noaccess']);
}
include 'general/noaccess.php';
exit;
}
// Set baseUrl for use it in several locations in this class.
$this->baseUrl = ui_get_full_url('index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=agent_wizard');
// Capture all parameters before start.
$this->ajaxController = $ajax_controller;
$this->wizardSection = get_parameter('wizard_section', '');
$this->idAgent = get_parameter('id_agente', '');
return $this;
}
/**
* Run main page.
*
* @return void
*/
public function run()
{
// CSS.
ui_require_css_file('wizard');
ui_require_css_file('discovery');
// Javascript.
// ui_require_javascript_file('jquery.caret.min');
$this->loadMainForm();
$this->performWizard();
// Load integrated JS
$this->loadJS();
}
/**
* Common Main Wizard form
*
* @return void
*/
private function loadMainForm()
{
// Define name of explorer button
switch ($this->wizardSection) {
case 'snmp_explorer':
case 'snmp_interfaces_explorer':
// Define labels.
$this->actionType = 'snmp';
$this->actionLabel = __('SNMP Walk');
// Fill with servers to perform SNMP walk.
$fieldsServers = [];
$fieldsServers[0] = __('Local console');
if (enterprise_installed()) {
enterprise_include_once('include/functions_satellite.php');
// Get the servers.
$rows = get_proxy_servers();
// Check if satellite server has remote configuration enabled.
$satellite_remote = config_agents_has_remote_configuration($this->idAgent);
// Generate a list with allowed servers.
foreach ($rows as $row) {
if ($row['server_type'] == 13) {
$id_satellite = $row['id_server'];
$serverType = ' (Satellite)';
} else {
$serverType = ' (Standard)';
}
$fieldsServers[$row['id_server']] = $row['name'].$serverType;
}
}
// Fill with SNMP versions allowed.
$fieldsVersions = [
'1' => '1',
'2' => '2',
'2c' => '2c',
'3' => '3',
];
break;
case 'wmi_explorer':
$this->actionType = 'wmi';
$this->actionLabel = __('WMI Explorer');
break;
default:
$this->actionType = 'none';
$this->actionLabel = __('Nothing');
exit;
break;
}
// Main form.
$form = [
'action' => '',
// 'action' => $this->baseUrl,
'id' => 'main_wizard_form',
'method' => 'POST',
];
// Inputs.
$inputs = [];
$inputs[] = [
'id' => 'hdn-type-action',
'arguments' => [
'name' => 'type-action',
'type' => 'hidden',
'value' => $this->actionType,
'return' => true,
],
];
$inputs[] = [
'label' => __('Target IP'),
'id' => 'txt-target-ip',
'arguments' => [
'name' => 'target-ip',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('Port'),
'id' => 'txt-target-port',
'arguments' => [
'name' => 'target-port',
'input_class' => 'flex-row',
'type' => 'text',
'size' => '20',
'class' => '',
'return' => true,
],
];
if ($this->actionType === 'snmp') {
$inputs[] = [
'label' => __('Use agent IP'),
'id' => 'txt-use-agent-ip',
'arguments' => [
'name' => 'use-agent-ip',
'input_class' => 'flex-row',
'type' => 'checkbox',
'class' => '',
'return' => true,
],
];
}
if ($this->actionType === 'wmi') {
$inputs[] = [
'label' => __('Namespace'),
'id' => 'txt-namespace',
'arguments' => [
'name' => 'namespace',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('Username'),
'id' => 'txt-username',
'arguments' => [
'name' => 'username',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('Password'),
'id' => 'txt-password',
'arguments' => [
'name' => 'password',
'input_class' => 'flex-row',
'type' => 'text',
'class' => '',
'return' => true,
],
];
}
$inputs[] = [
'label' => __('Server to execute command'),
'id' => 'txt-target-port',
'arguments' => [
'name' => 'target-port',
'input_class' => 'flex-row',
'type' => 'select',
'fields' => $fieldsServers,
'class' => '',
'return' => true,
],
];
if ($this->actionType === 'snmp') {
$inputs[] = [
'label' => __('SNMP community'),
'id' => 'txt-snmp-community',
'arguments' => [
'name' => 'snmp-community',
'input_class' => 'flex-row',
'type' => 'text',
'size' => '20',
'class' => '',
'return' => true,
],
];
$inputs[] = [
'label' => __('SNMP version'),
'id' => 'txt-snmnp-version',
'arguments' => [
'name' => 'snmnp-version',
'input_class' => 'flex-row',
'type' => 'select',
'fields' => $fieldsVersions,
'class' => '',
'return' => true,
],
];
}
$inputs[] = [
'arguments' => [
'label' => $this->actionLabel,
'name' => 'action',
'type' => 'submit',
'attributes' => 'class="sub next" onclick="performAction();return false;"',
'return' => true,
],
];
// Prints main form.
html_print_div(
[
'class' => 'white_box',
'content' => $this->printForm(
[
'form' => $form,
'inputs' => $inputs,
],
true
),
]
);
}
/**
* Undocumented function
*
* @return void
*/
public function performWizard()
{
// echo json_encode(['error' => obhd($_REQUEST)]);
// exit;
$sql = sprintf(
'SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS `group`, ncg.name AS `group_name`
FROM tnetwork_profile_component AS npc, tnetwork_component AS nc
INNER JOIN tnetwork_component_group AS ncg ON ncg.id_sg = nc.id_group
WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d',
10
);
$moduleBlocks = db_get_all_rows_sql($sql);
$blockTables = [];
// Build the information of the blocks.
foreach ($moduleBlocks as $block) {
if (key_exists($block['group'], $blockTables) === false) {
$blockTables[$block['group']] = [
'name' => $block['group_name'],
'data' => [],
];
}
$blockTables[$block['group']]['data'][] = [
'component_id' => $block['component_id'],
'name' => $block['name'],
'type' => $block['type'],
'description' => $block['description'],
];
}
// Lets generate the block tables.
$output = '';
foreach ($blockTables as $id_group => $blockTable) {
// Data with all components.
$blockData = $blockTable['data'];
// Creation of list of all components.
$blockComponentList = '';
foreach ($blockData as $component) {
$blockComponentList .= $component['component_id'].',';
}
$blockComponentList = chop($blockComponentList, ',');
// Title of Block.
$blockTitle = $blockTable['name'];
$blockTitle .= html_print_div(
[
'class' => 'white_table_header_checkbox',
'content' => html_print_checkbox_switch_extended(
'sel_block_'.$id_group,
1,
0,
false,
'switchBlockControl(event)',
'',
true
),
],
true
);
$table = new StdClasS();
$table->class = 'databox data';
$table->width = '75%';
$table->styleTable = 'margin: 2em auto 0;border: 1px solid #ddd;background: white;';
$table->rowid = [];
$table->data = [];
$table->cellpadding = 0;
$table->cellspacing = 0;
$table->width = '100%';
$table->class = 'info_table';
$table->head = [];
$table->head[0] = html_print_div(['style' => 'font-weight:700;', 'content' => __('Module Name')], true);
$table->head[1] = html_print_div(['style' => 'font-weight:700;text-align:center;', 'content' => __('Type')], true);
$table->head[2] = html_print_div(['style' => 'font-weight:700;', 'content' => __('Module info')], true);
$table->head[3] = html_print_div(['style' => 'font-weight:700;text-align:center;', 'content' => __('Warning')], true);
$table->head[4] = html_print_div(['style' => 'font-weight:700;text-align:center;', 'content' => __('Critical')], true);
$table->head[5] = html_print_div(['style' => 'font-weight:700;margin-right:1.2em;', 'content' => __('Active')], true);
$table->size = [];
$table->size[0] = '15%';
$table->size[1] = '3%';
$table->size[3] = '210px';
$table->size[4] = '210px';
$table->size[5] = '3%';
$table->align = [];
$table->align[5] = 'right';
$table->data = [];
foreach ($blockData as $module) {
// Module Name column.
$data[0] = $module['name'];
// Module Type column.
$data[1] = ui_print_moduletype_icon($module['type'], true);
// Module info column.
$data[2] = mb_strimwidth(io_safe_output($module['description']), 0, 150, '...');
// Warning column.
$data[3] = html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Min: '.html_print_input_text(
'warning_min_'.$module['component_id'],
'0',
'',
3,
4,
true
).' ',
],
true
);
$data[3] .= html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Max: '.html_print_input_text(
'warning_max_'.$module['component_id'],
'0',
'',
3,
4,
true
),
],
true
);
$data[3] .= html_print_div(
[
'class' => 'wizard-column-levels',
'style' => 'margin-top: 0.3em;',
'content' => 'Inv: '.html_print_checkbox(
'warning_inv_'.$module['component_id'],
0,
false,
true,
false
),
],
true
);
// Critical column.
$data[4] = html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Min: '.html_print_input_text(
'critical_min_'.$module['component_id'],
'0',
'',
3,
4,
true
).' ',
],
true
);
$data[4] .= html_print_div(
[
'class' => 'wizard-column-levels',
'content' => 'Max: '.html_print_input_text(
'critical_max_'.$module['component_id'],
'0',
'',
3,
4,
true
),
],
true
);
$data[4] .= html_print_div(
[
'class' => 'wizard-column-levels',
'style' => 'margin-top: 0.3em;',
'content' => 'Inv: '.html_print_checkbox(
'critical_inv_'.$module['component_id'],
0,
false,
true,
false
),
],
true
);
// Activation column.
$data[5] = html_print_checkbox_switch_extended('sel_module_'.$id_group.'_'.$module['component_id'], 1, 0, false, 'switchBlockControl(event)', '', true);
array_push($table->data, $data);
}
$content = html_print_table($table, true);
$output .= ui_toggle($content, $blockTitle, '', '', false, true);
}
html_print_div(
[
'class' => 'white_box',
'style' => 'margin-top: 20px;',
'content' => $output,
]
);
// Form. Not used at this moment.
$form = [
'action' => $this->baseUrl,
'id' => 'modal_form_action_response',
'method' => 'POST',
'class' => 'modal',
'extra' => '',
];
// Inputs.
$inputs = [];
$inputs[] = [
'id' => 'inp-id_np',
'arguments' => [
'name' => 'id_np',
'type' => 'hidden',
'value' => '69',
'return' => true,
],
];
$this->printForm(
[
'form' => $form,
'inputs' => $inputs,
true
]
);
}
/**
* Perform SNMP
*
* @return void
*/
private function performSNMP()
{
echo 'HOLA';
}
/**
* Perform WMI
*
* @return void
*/
private function performWMI()
{
}
/**
* Generate the JS needed for use inside
*
* @return void
*/
private function loadJS()
{
$str = '';
ob_start();
?>
<script type="text/javascript">
// The functions goes here!
/**
* WIP: Loads modal from AJAX to perform the required action.
*/
function performAction() {
var btn_ok_text = '<?php echo __('OK'); ?>';
var btn_cancel_text = '<?php echo __('Cancel'); ?>';
var title = '<?php echo __('Perform %s', $this->actionLabel); ?>';
var action = '<?php echo $this->actionType; ?>';
console.log(title);
console.log(action);
load_modal({
target: $('#modal'),
form: 'modal_form_action_response',
url: '<?php echo ui_get_full_url('ajax.php', false, false, false); ?>',
ajax_callback: showMsg,
modal: {
title: title,
ok: btn_ok_text,
cancel: btn_cancel_text,
},
/* extradata: [
{
name: 'action',
value: action,
}
], */
onshow: {
page: '<?php echo $this->ajaxController; ?>',
method: 'performWizard'
}/* ,
onsubmit: {
page: '<?//php echo $this->ajaxController; ?>',
method: 'processData'
} */
});
console.log("he terminado");
}
/**
* WIP: Process ajax responses and shows a dialog with results.
*/
function showMsg(data) {
var title = "<?php echo __('Success'); ?>";
var text = "";
var failed = 0;
try {
data = JSON.parse(data);
text = data["result"];
} catch (err) {
title = "<?php echo __('Failed'); ?>";
text = err.message;
failed = 1;
}
if (!failed && data["error"] != undefined) {
title = "<?php echo __('Failed'); ?>";
text = data["error"];
failed = 1;
}
if (data["report"] != undefined) {
data["report"].forEach(function(item) {
text += "<br>" + item;
});
}
$("#msg").empty();
$("#msg").html(text);
$("#msg").dialog({
width: 450,
position: {
my: "center",
at: "center",
of: window,
collision: "fit"
},
title: title,
buttons: [
{
class:
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
text: "OK",
click: function(e) {
}
}
]
});
}
/**
* Controls checkboxes for modules
*/
function switchBlockControl(e) {
var switchId = e.target.id.split("_");
var type = switchId[1];
var blockNumber = switchId[2];
var selectedBlock = $("#checkbox-sel_block_" + blockNumber);
var totalCount = 0;
var markedCount = 0;
if (type == 'block') {
if (selectedBlock.prop("checked")) {
$("[id*=checkbox-sel_module_" + blockNumber + "]").each(function(){
$(this).prop("checked", true);
});
} else {
$("[id*=checkbox-sel_module_" + blockNumber + "]").each(function(){
$(this).prop("checked", false);
});
}
} else if (type == 'module') {
$("[id*=checkbox-sel_module_" + blockNumber + "]").each(function() {
if ($(this).prop("checked")) {
markedCount++;
}
totalCount++;
});
if (totalCount == markedCount) {
selectedBlock.prop("checked", true);
selectedBlock
.parent()
.removeClass("alpha50");
} else if (markedCount == 0) {
selectedBlock.prop("checked", false);
selectedBlock
.parent()
.removeClass("alpha50");
} else {
selectedBlock.prop("checked", true);
selectedBlock
.parent()
.addClass("alpha50");
}
}
}
</script>
<?php
$str = ob_get_clean();
echo $str;
return $str;
}
}

View File

@ -0,0 +1,799 @@
<?php
/**
* PEN Configuration feature.
*
* @category Class
* @package Pandora FMS
* @subpackage Wizard Setup
* @version 0.0.1
* @license See below
*
* ______ ___ _______ _______ ________
* | __ \.-----.--.--.--| |.-----.----.-----. | ___| | | __|
* | __/| _ | | _ || _ | _| _ | | ___| |__ |
* |___| |___._|__|__|_____||_____|__| |___._| |___| |__|_|__|_______|
*
* ============================================================================
* Copyright (c) 2005-2020 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.
* ============================================================================
*/
global $config;
require_once $config['homedir'].'/include/class/HTML.class.php';
/**
* Config PEN Class
*/
class ConfigPEN extends HTML
{
/**
* Url of controller.
*
* @var string
*/
public $ajaxController;
/**
* URL Base
*
* @var string
*/
private $baseUrl;
/**
* Contructor.
*
* @param string $ajax_page Target ajax page.
*/
public function __construct($ajax_page)
{
global $config;
// Check access.
check_login();
if (! check_acl($config['id_user'], 0, 'PM')) {
db_pandora_audit(
'ACL Violation',
'Trying to access PEN Definition feature'
);
include 'general/noaccess.php';
exit;
}
$this->ajaxController = $ajax_page;
$this->offset = '';
$this->baseUrl = ui_get_full_url(
'index.php?sec=configuration_wizard_setup&sec2=godmode/modules/private_enterprise_numbers'
);
}
/**
* Returns an array with all the credentials matching filter and ACL.
*
* @param array $fields Fields array or 'count' keyword to retrieve count.
* @param array $filter Filters to be applied.
* @param integer $offset Offset (pagination).
* @param integer $limit Limit (pagination).
* @param string $order Sort order.
* @param string $sort_field Sort field.
*
* @return array With all results or false if error.
* @throws Exception On error.
*/
public static function getAll(
$fields,
$filter=null,
$offset=null,
$limit=null,
$order=null,
$sort_field=null
) {
$sql_filters = [];
$order_by = '';
$pagination = '';
$count = false;
if (!is_array($fields) && $fields == 'count') {
$fields = ['*'];
$count = true;
} else if (!is_array($fields)) {
error_log('[configPEN.getAll] Fields must be an array or "count".');
throw new Exception('[configPEN.getAll] Fields must be an array or "count".');
}
if (is_array($filter)) {
if (!empty($filter['free_search'])) {
$sql_filters[] = vsprintf(
' AND (lower(`manufacturer`) like lower("%%%s%%")
OR pen = "%s") ',
array_fill(0, 2, $filter['free_search'])
);
}
if (!empty($filter['pen'])) {
$sql_filters[] = sprintf(
' AND `pen` = %d',
$filter['pen']
);
}
}
if (isset($order)) {
$dir = 'asc';
if ($order == 'desc') {
$dir = 'desc';
};
if (in_array(
$sort_field,
[
'pen',
'manufacturer',
'description',
]
)
) {
$order_by = sprintf(
'ORDER BY `%s` %s',
$sort_field,
$dir
);
}
}
if (isset($limit) && $limit > 0
&& isset($offset) && $offset >= 0
) {
$pagination = sprintf(
' LIMIT %d OFFSET %d ',
$limit,
$offset
);
}
$sql = sprintf(
'SELECT %s
FROM `tpen`
WHERE 1=1
%s
%s
%s',
join(',', $fields),
join(' ', $sql_filters),
$order_by,
$pagination
);
if ($count) {
$sql = sprintf('SELECT count(*) as n FROM ( %s ) tt', $sql);
return db_get_value_sql($sql);
}
return db_get_all_rows_sql($sql);
}
/**
* AJAX: Return JSON content for datatable.
*
* @return void
*/
function draw()
{
global $config;
// Datatables offset, limit and order.
$filter = get_parameter('filter', []);
$start = get_parameter('start', 0);
$length = get_parameter('length', $config['block_size']);
$order = get_datatable_order(true);
try {
ob_start();
$fields = ['*'];
// Retrieve data.
$data = $this->getAll(
// Fields.
$fields,
// Filter.
$filter,
// Offset.
$start,
// Limit.
$length,
// Order.
$order['direction'],
// Sort field.
$order['field']
);
// Retrieve counter.
$count = $this->getAll(
'count',
$filter
);
if ($data) {
$data = array_reduce(
$data,
function ($carry, $item) {
// Transforms array of arrays $data into an array
// of objects, making a post-process of certain fields.
$tmp = (object) $item;
$tmp->description = io_safe_output($tmp->description);
$tmp->manufacturer = io_safe_output($tmp->manufacturer);
$tmp->options = '';
$tmp->options = '<a href="javascript:" onclick="showForm(\'';
$tmp->options .= $tmp->pen;
$tmp->options .= '\')" >';
$tmp->options .= html_print_image(
'images/eye.png',
true,
['title' => __('Show')]
);
$tmp->options .= '</a>';
$tmp->options .= '<a href="javascript:" onclick="deletePEN(\'';
$tmp->options .= $tmp->pen;
$tmp->options .= '\')" >';
$tmp->options .= html_print_image(
'images/cross.png',
true,
['title' => __('Delete')]
);
$tmp->options .= '</a>';
$carry[] = $tmp;
return $carry;
}
);
}
// Datatables format: RecordsTotal && recordsfiltered.
echo json_encode(
[
'data' => $data,
'recordsTotal' => $count,
'recordsFiltered' => $count,
]
);
// Capture output.
$response = ob_get_clean();
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
exit;
}
// If not valid, show error with issue.
json_decode($response);
if (json_last_error() == JSON_ERROR_NONE) {
// If valid dump.
echo $response;
} else {
echo json_encode(
['error' => $response]
);
}
exit;
}
/**
* Run main page.
*
* @return void
*/
public function run()
{
// Require specific CSS and JS.
ui_require_css_file('wizard');
ui_require_css_file('discovery');
ui_require_css_file('pen');
// Header section.
// Breadcrums.
$this->setBreadcrum([]);
$this->prepareBreadcrum(
[
[
'link' => '',
'label' => __('Configuration'),
'selected' => false,
],
[
'link' => '',
'label' => __('Templates'),
'selected' => false,
],
[
'link' => $this->baseUrl,
'label' => __('Private Enterprise Numbers'),
'selected' => true,
],
],
true
);
ui_print_page_header(
__('Private Enterprise Numbers'),
'',
false,
'',
true,
'',
false,
'',
GENERIC_SIZE_TEXT,
'',
$this->printHeader(true)
);
// Definition for AJAX.
html_print_input_hidden(
'ajax_file',
ui_get_full_url('ajax.php', false, false, false)
);
// Ajax page (hidden).
html_print_input_hidden(
'ajax_page',
$this->ajaxController
);
// Allow message area.
html_print_div(['id' => 'message_show_area']);
// Prints the main table.
html_print_div(
[
'id' => 'main_table_area',
'content' => $this->createMainTable(),
]
);
}
/**
* Load modal information for PEN management.
*
* Ajax. Direct HTML.
*
* @return void
*/
public function loadModal()
{
$values = [];
$id = (int) get_parameter('pen', 0);
if ($id > 0) {
$values = $this->getAll(
// Fields.
['*'],
// Filter.
['pen' => $id]
);
if (is_array($values)) {
$values = $values[0];
}
}
$form = [
'action' => '#',
'id' => 'modal_form',
'onsubmit' => 'return false;',
'class' => '',
];
$inputs = [];
$arguments = [
'name' => 'pen',
'type' => 'number',
'value' => $values['pen'],
'required' => true,
'return' => true,
'size' => 50,
];
if ((bool) $values['pen']) {
$arguments['disabled'] = true;
}
$inputs[] = [
'label' => __('PEN'),
'class' => 'flex-row',
'id' => 'div-pen',
'arguments' => $arguments,
];
$inputs[] = [
'label' => __('Manufacturer'),
'class' => 'flex-row',
'arguments' => [
'name' => 'manufacturer',
'id' => 'manufacturer',
'type' => 'text',
'required' => true,
'value' => io_safe_output($values['manufacturer']),
'return' => true,
],
];
$inputs[] = [
'label' => __('Description'),
'class' => 'flex-row',
'arguments' => [
'name' => 'description',
'id' => 'description',
'type' => 'textarea',
'value' => io_safe_output($values['description']),
'return' => true,
'rows' => 50,
'columns' => 30,
],
];
echo '<div id="div-form">';
echo parent::printForm(
[
'form' => $form,
'inputs' => $inputs,
],
true
);
echo '</div>';
}
/**
* Delete a manufacturer register from db.
*
* @return void
*/
public function delete()
{
$pen = get_parameter('pen', 0);
if (empty($pen)) {
echo json_encode(['error' => __('PEN is required')]);
} else {
if (db_process_sql_delete('tpen', ['pen' => $pen]) !== false) {
echo json_encode(['result' => __('Successfully deleted')]);
} else {
global $config;
echo json_encode(['error' => $config['dbconnection']->error]);
}
}
}
/**
* Add or update a manufacturer to private enterprise numbers.
*
* @return void
*/
public function add()
{
$pen = get_parameter('pen', 0);
$manufacturer = get_parameter('manufacturer', '');
$description = get_parameter('description', '');
$is_new = (bool) get_parameter('is_new', false);
if (empty($pen)) {
$error = __('PEN is required.');
}
if (empty($manufacturer)) {
$error = __('Manufacturer is required');
}
if (!empty($error)) {
echo json_encode(
['error' => $error]
);
}
// Add if not exists.
$current = $this->getAll(['pen'], ['pen' => $pen]);
if ($current === false) {
// New.
if ($is_new === false) {
echo json_encode(
[
'error' => __('This PEN definition does not exist'),
]
);
exit;
}
$rs = db_process_sql_insert(
'tpen',
[
'pen' => $pen,
'manufacturer' => $manufacturer,
'description' => $description,
]
);
$str = __('created');
} else {
// Update.
if ($is_new === true) {
echo json_encode(
[
'error' => __('This PEN definition already exists'),
]
);
exit;
}
$rs = db_process_sql_update(
'tpen',
[
'manufacturer' => $manufacturer,
'description' => $description,
],
['pen' => $pen]
);
$str = __('updated');
}
if ($rs === false) {
global $config;
echo json_encode(['error' => $config['dbconnection']->error]);
} else {
echo json_encode(['result' => __('Succesfully %s', $str)]);
}
}
/**
* Create the main table with the PENs info
*
* @return string Return entire the table
*/
public function createMainTable()
{
global $config;
$output = '';
// Datatables list.
try {
$columns = [
'pen',
'manufacturer',
'description',
'options',
];
$column_names = [
__('PEN'),
__('Manufacturer'),
__('Description'),
[
'text' => __('Options'),
'class' => 'action_buttons',
],
];
$this->tableId = 'keystore';
// Load datatables user interface.
$output .= ui_print_datatable(
[
'id' => $this->tableId,
'return' => true,
'class' => 'info_table',
'style' => 'width: 100%',
'columns' => $columns,
'column_names' => $column_names,
'ajax_url' => $this->ajaxController,
'ajax_data' => ['method' => 'draw'],
'no_sortable_columns' => [-1],
'order' => [
'field' => 'pen',
'direction' => 'asc',
],
'search_button_class' => 'sub filter float-right',
'form' => [
'inputs' => [
[
'label' => __('Free search'),
'type' => 'text',
'class' => 'mw250px',
'id' => 'free_search',
'name' => 'free_search',
],
],
],
]
);
} catch (Exception $e) {
echo $e->getMessage();
}
// Auxiliar div.
$output .= '<div id="modal" style="display: none"></div>';
$output .= '<div id="msg" style="display: none"></div>';
$output .= '<div id="aux" style="display: none"></div>';
// Create button.
$output .= parent::printInput(
[
'type' => 'submit',
'name' => 'create',
'label' => __('Register manufacturer'),
'attributes' => 'class="sub next"',
'return' => true,
]
);
ob_start();
?>
<script type="text/javascript">
function cleanupDOM() {
$("#div-form").empty();
}
function deletePEN(id) {
confirmDialog({
title: "<?php echo __('Are you sure?'); ?>",
message: "<?php echo __('Are you sure you want to delete this PEN?'); ?>",
ok: "<?php echo __('OK'); ?>",
cancel: "<?php echo __('Cancel'); ?>",
onAccept: function() {
$.ajax({
method: "post",
url: "<?php echo ui_get_full_url('ajax.php', false, false, false); ?>",
data: {
page: "<?php echo $this->ajaxController; ?>",
method: "delete",
pen: id
},
datatype: "json",
success: function(data) {
showMsg(data);
},
error: function(e) {
showMsg(e);
}
});
}
});
}
function showForm(id) {
var btn_ok_text = "<?php echo __('OK'); ?>";
var btn_cancel_text = "<?php echo __('Cancel'); ?>";
var title = "<?php echo __('Register new manufacturer'); ?>";
var is_new = 1;
if (id) {
btn_ok_text = "<?php echo __('Update'); ?>";
title = "<?php echo __('Update'); ?> " + id;
is_new = 0;
}
load_modal({
target: $("#modal"),
form: "modal_form",
url: "<?php echo ui_get_full_url('ajax.php', false, false, false); ?>",
ajax_callback: showMsg,
cleanup: cleanupDOM,
modal: {
title: title,
ok: btn_ok_text,
cancel: btn_cancel_text
},
extradata: [
{
name: "pen",
value: id
},
{
name: 'is_new',
value: is_new
}
],
onshow: {
page: "<?php echo $this->ajaxController; ?>",
method: "loadModal"
},
onsubmit: {
page: "<?php echo $this->ajaxController; ?>",
method: "add"
}
});
}
/**
* Process ajax responses and shows a dialog with results.
*/
function showMsg(data) {
var title = "<?php echo __('Success'); ?>";
var text = "";
var failed = 0;
try {
data = JSON.parse(data);
text = data["result"];
} catch (err) {
title = "<?php echo __('Failed'); ?>";
text = err.message;
failed = 1;
}
if (!failed && data["error"] != undefined) {
title = "<?php echo __('Failed'); ?>";
text = data["error"];
failed = 1;
}
if (data["report"] != undefined) {
data["report"].forEach(function(item) {
text += "<br>" + item;
});
}
$("#msg").empty();
$("#msg").html(text);
$("#msg").dialog({
width: 450,
position: {
my: "center",
at: "center",
of: window,
collision: "fit"
},
title: title,
buttons: [
{
class:
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
text: "OK",
click: function(e) {
if (!failed) {
$(".ui-dialog-content").dialog("close");
$(".info").hide();
cleanupDOM();
dt_keystore.draw(false);
} else {
$(this).dialog("close");
}
}
}
]
});
}
$(document).ready(function() {
$("#submit-create").click(function() {
showForm();
});
});
</script>
<?php
$output .= ob_get_clean();
return $output;
}
}

View File

@ -443,6 +443,8 @@ class CredentialStore extends Wizard
*/ */
public function draw() public function draw()
{ {
global $config;
// Datatables offset, limit and order. // Datatables offset, limit and order.
$filter = get_parameter('filter', []); $filter = get_parameter('filter', []);
$start = get_parameter('start', 0); $start = get_parameter('start', 0);

View File

@ -38,7 +38,7 @@ class HTML
/** /**
* Breadcrum * Breadcrum
* *
* @var array. * @var array
*/ */
public $breadcrum; public $breadcrum;
@ -119,7 +119,7 @@ class HTML
/** /**
* Add an element to breadcrum array. * Add an element to breadcrum array.
* *
* @param string $breads Elements to add to breadcrum. * @param array $breads Elements to add to breadcrum.
* *
* @return void * @return void
*/ */
@ -335,6 +335,27 @@ class HTML
} }
/**
* Return formatted html for error handler.
*
* @param string $message Error mesage.
*
* @return string
*/
public function error($message)
{
if (is_ajax()) {
echo json_encode(
[
'error' => ui_print_error_message($message, '', true),
]
);
} else {
return ui_print_error_message($message, '', true);
}
}
/** /**
* Print input using functions html lib. * Print input using functions html lib.
* *
@ -725,6 +746,7 @@ class HTML
) { ) {
$form = $data['form']; $form = $data['form'];
$inputs = $data['inputs']; $inputs = $data['inputs'];
$rawInputs = $data['rawInputs'];
$js = $data['js']; $js = $data['js'];
$rawjs = $data['js_block']; $rawjs = $data['js_block'];
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
@ -767,6 +789,11 @@ class HTML
$output .= '</ul>'; $output .= '</ul>';
// There is possible add raw inputs for this form.
if (empty($rawInputs) === false) {
$output .= $rawInputs;
}
if ($print_white_box === true) { if ($print_white_box === true) {
$output .= '</div>'; $output .= '</div>';
} }
@ -800,7 +827,7 @@ class HTML
$form = $data['form']; $form = $data['form'];
$rows = $data['rows']; $rows = $data['rows'];
$rawInputs = $data['rawInputs'];
$js = $data['js']; $js = $data['js'];
$rawjs = $data['js_block']; $rawjs = $data['js_block'];
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
@ -875,6 +902,11 @@ class HTML
} }
} }
// There is possible add raw inputs for this form.
if (empty($rawInputs) === false) {
$output .= $rawInputs;
}
$output .= '</div>'; $output .= '</div>';
$output .= '<ul class="wizard">'.$output_submit.'</ul>'; $output .= '<ul class="wizard">'.$output_submit.'</ul>';
@ -905,6 +937,7 @@ class HTML
{ {
$form = $data['form']; $form = $data['form'];
$inputs = $data['inputs']; $inputs = $data['inputs'];
$rawInputs = $data['rawInputs'];
$js = $data['js']; $js = $data['js'];
$rawjs = $data['js_block']; $rawjs = $data['js_block'];
$cb_function = $data['cb_function']; $cb_function = $data['cb_function'];
@ -940,7 +973,13 @@ class HTML
} }
$output .= '</ul>'; $output .= '</ul>';
// There is possible add raw inputs for this form.
if (empty($rawInputs) === false) {
$output .= $rawInputs;
}
$output .= '</div>'; $output .= '</div>';
$output .= '<ul class="wizard">'.$output_submit.'</ul>'; $output .= '<ul class="wizard">'.$output_submit.'</ul>';
$output .= '</form>'; $output .= '</form>';
$output .= '<script>'.$js.'</script>'; $output .= '<script>'.$js.'</script>';
@ -1000,4 +1039,72 @@ class HTML
} }
/**
* Returns a n-dimensional array (data) into a html tree structure.
*
* Advanced documentation:
* https://www.jqueryscript.net/other/Checkable-Hierarchical-Tree.html
*
* @param string $target Target DOM id.
* @param array $data N-dimensional array.
* @param string $onclick Onclick function.
* @param string $onchange Onchange function.
*
* @return string
*/
public static function printTree(
$target,
$data,
$onclick='',
$onchange=''
) {
ui_require_css_file('simTree');
ui_require_javascript_file('simTree');
/*
* SAMPLE SELECT ALL.
*
* echo '<div class="subtitle">';
* echo '<span>';
* echo __('Please select devices to be monitored');
* echo '</span><div class="manage">';
* echo '<button onclick="$(\'.sim-tree li a\').each(function(){simTree_tree.doCheck($(this), false); simTree_tree.clickNode($(this));});">';
* echo __('select all');
* echo '</button>';
* echo '<button onclick="$(\'.sim-tree li a\').each(function(){simTree_tree.doCheck($(this), true); simTree_tree.clickNode($(this));});">';
* echo __('deselect all');
* echo '</button>';
* echo '</div>';
* echo '</div>';
*
* END SAMPLE SELECT ALL.
*/
$output = '
<script type="text/javascript">
var simTree_'.$target.';
$(document).ready(function() {
simTree_'.$target.' = simTree({
el: $('.$target.'),
data: '.json_encode($data).',
onClick: function (item) {'.$onclick.';},
onChange: function (item) {
'.$onchange.';
$("#tree-data-'.$target.'").val(JSON.stringify(this.sels));
},
check: true,
linkParent: true
});
$("#'.$target.'").append(
\'<input type="hidden" id="tree-data-'.$target.'" name="tree-data-'.$target.'">\'
);
$("#tree-data-'.$target.'").val(JSON.stringify(simTree_'.$target.'.sels));
});
</script>';
return $output;
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -20,7 +20,7 @@
/** /**
* Pandora build version and version * Pandora build version and version
*/ */
$build_version = 'PC200413'; $build_version = 'PC200420';
$pandora_version = 'v7.0NG.744'; $pandora_version = 'v7.0NG.744';
// Do not overwrite default timezone set if defined. // Do not overwrite default timezone set if defined.

View File

@ -524,9 +524,15 @@ define('ARROW_TYPE', 1);
// Discovery task steps. // Discovery task steps.
define('STEP_SCANNING', 1); define('STEP_SCANNING', 1);
define('STEP_CAPABILITIES', 7);
define('STEP_AFT', 2); define('STEP_AFT', 2);
define('STEP_TRACEROUTE', 3); define('STEP_TRACEROUTE', 3);
define('STEP_GATEWAY', 4); define('STEP_GATEWAY', 4);
define('STEP_MONITORING', 5);
define('STEP_PROCESSING', 6);
define('STEP_STATISTICS', 1);
define('STEP_APP_SCAN', 2);
define('STEP_CUSTOM_QUERIES', 3);
// Networkmap node types. // Networkmap node types.
define('NODE_AGENT', 0); define('NODE_AGENT', 0);
@ -594,6 +600,11 @@ define('DISCOVERY_DEPLOY_AGENTS', 9);
define('DISCOVERY_APP_SAP', 10); define('DISCOVERY_APP_SAP', 10);
// Force task build tmp results.
define('DISCOVERY_REVIEW', 0);
define('DISCOVERY_STANDARD', 1);
define('DISCOVERY_RESULTS', 2);
// Discovery types matching definition. // Discovery types matching definition.
define('DISCOVERY_SCRIPT_HOSTDEVICES_CUSTOM', 0); define('DISCOVERY_SCRIPT_HOSTDEVICES_CUSTOM', 0);
// Standard applications. // Standard applications.

File diff suppressed because it is too large Load Diff

View File

@ -2439,7 +2439,13 @@ function graphic_agentaccess(
if ($return === true) { if ($return === true) {
return vbar_graph($data_array, $options, 1); return vbar_graph($data_array, $options, 1);
} else { } else {
echo vbar_graph($data_array, $options, 1); $options['generals']['pdf']['width'] = 350;
$options['generals']['pdf']['height'] = 125;
$imgbase64 = '<img src="data:image/jpg;base64,';
$imgbase64 .= vbar_graph($data_array, $options, 2);
$imgbase64 .= '" />';
return $imgbase64;
} }
} }

View File

@ -722,6 +722,7 @@ function html_print_select(
* @param string $style The string of style. * @param string $style The string of style.
* @param mixed $size Max elements showed in select or default (size=10) * @param mixed $size Max elements showed in select or default (size=10)
* @param integer $truncante_size Truncate size of the element, by default is set to GENERIC_SIZE_TEXT constant * @param integer $truncante_size Truncate size of the element, by default is set to GENERIC_SIZE_TEXT constant
* @param integer $class Class to apply.
* *
* @return string HTML code if return parameter is true. * @return string HTML code if return parameter is true.
*/ */
@ -738,7 +739,8 @@ function html_print_select_from_sql(
$disabled=false, $disabled=false,
$style=false, $style=false,
$size=false, $size=false,
$trucate_size=GENERIC_SIZE_TEXT $trucate_size=GENERIC_SIZE_TEXT,
$class=''
) { ) {
global $config; global $config;
@ -770,7 +772,7 @@ function html_print_select_from_sql(
$return, $return,
$multiple, $multiple,
$sort, $sort,
'', $class,
$disabled, $disabled,
$style, $style,
'', '',
@ -1087,7 +1089,7 @@ function html_print_extended_select_for_time(
ob_start(); ob_start();
// Use the no_meta parameter because this image is only in the base console // Use the no_meta parameter because this image is only in the base console
echo '<div id="'.$uniq_name.'_default" style="width:100%;display:inline;">'; echo '<div id="'.$uniq_name.'_default" style="width:100%;display:flex;align-items: baseline;">';
html_print_select( html_print_select(
$fields, $fields,
$uniq_name.'_select', $uniq_name.'_select',
@ -1121,7 +1123,7 @@ function html_print_extended_select_for_time(
echo '</div>'; echo '</div>';
echo '<div id="'.$uniq_name.'_manual" style="width:100%;display:inline;">'; echo '<div id="'.$uniq_name.'_manual" style="width:100%;display:flex;">';
html_print_input_text($uniq_name.'_text', $selected, '', $size, 255, false, $readonly, false, '', $class); html_print_input_text($uniq_name.'_text', $selected, '', $size, 255, false, $readonly, false, '', $class);
html_print_input_hidden($name, $selected, false, $uniq_name); html_print_input_hidden($name, $selected, false, $uniq_name);
@ -1159,8 +1161,8 @@ function html_print_extended_select_for_time(
$('#text-".$uniq_name."_text').val(seconds); $('#text-".$uniq_name."_text').val(seconds);
adjustTextUnits('".$uniq_name."'); adjustTextUnits('".$uniq_name."');
calculateSeconds('".$uniq_name."'); calculateSeconds('".$uniq_name."');
$('#".$uniq_name."_manual').show(); $('#".$uniq_name."_manual').css('display', 'flex');
$('#".$uniq_name."_default').hide(); $('#".$uniq_name."_default').css('display', 'none');
} }
</script>"; </script>";
$returnString = ob_get_clean(); $returnString = ob_get_clean();
@ -1334,6 +1336,7 @@ function html_print_input_text_extended(
'onkeyup', 'onkeyup',
'required', 'required',
'autocomplete', 'autocomplete',
'form',
]; ];
$output = '<input '.($password ? 'type="password" autocomplete="'.$autocomplete.'" ' : 'type="text" '); $output = '<input '.($password ? 'type="password" autocomplete="'.$autocomplete.'" ' : 'type="text" ');
@ -1550,7 +1553,9 @@ function html_print_input_text(
$class='', $class='',
$onChange='', $onChange='',
$autocomplete='', $autocomplete='',
$autofocus=false $autofocus=false,
$onKeyDown='',
$formTo=''
) { ) {
if ($maxlength == 0) { if ($maxlength == 0) {
$maxlength = 255; $maxlength = 255;
@ -1575,6 +1580,10 @@ function html_print_input_text(
$attr['onchange'] = $onChange; $attr['onchange'] = $onChange;
} }
if ($onKeyDown != '') {
$attr['onkeydown'] = $onKeyDown;
}
if ($autocomplete !== '') { if ($autocomplete !== '') {
$attr['autocomplete'] = $autocomplete; $attr['autocomplete'] = $autocomplete;
} }
@ -1583,6 +1592,10 @@ function html_print_input_text(
$attr['autofocus'] = $autofocus; $attr['autofocus'] = $autofocus;
} }
if ($formTo != '') {
$attr['form'] = $formTo;
}
return html_print_input_text_extended( return html_print_input_text_extended(
$name, $name,
$value, $value,
@ -2164,6 +2177,10 @@ function html_print_table(&$table, $return=false)
$output = ''; $output = '';
static $table_count = 0; static $table_count = 0;
if (!isset($table)) {
$table = new StdClass();
}
$table_count++; $table_count++;
if (isset($table->align)) { if (isset($table->align)) {
foreach ($table->align as $key => $aa) { foreach ($table->align as $key => $aa) {
@ -3453,7 +3470,10 @@ function html_print_input($data, $wrapper='div', $input_only=false)
((isset($data['function']) === true) ? $data['function'] : ''), ((isset($data['function']) === true) ? $data['function'] : ''),
((isset($data['class']) === true) ? $data['class'] : ''), ((isset($data['class']) === true) ? $data['class'] : ''),
((isset($data['onChange']) === true) ? $data['onChange'] : ''), ((isset($data['onChange']) === true) ? $data['onChange'] : ''),
((isset($data['autocomplete']) === true) ? $data['autocomplete'] : '') ((isset($data['autocomplete']) === true) ? $data['autocomplete'] : ''),
false,
((isset($data['onKeyDown']) === true) ? $data['onKeyDown'] : ''),
((isset($data['form']) === true) ? $data['form'] : '')
); );
break; break;
@ -3500,24 +3520,6 @@ function html_print_input($data, $wrapper='div', $input_only=false)
); );
break; break;
case 'text':
$output .= html_print_input_text(
$data['name'],
$data['value'],
((isset($data['alt']) === true) ? $data['alt'] : ''),
((isset($data['size']) === true) ? $data['size'] : 50),
((isset($data['maxlength']) === true) ? $data['maxlength'] : 255),
((isset($data['return']) === true) ? $data['return'] : false),
((isset($data['disabled']) === true) ? $data['disabled'] : false),
((isset($data['required']) === true) ? $data['required'] : false),
((isset($data['function']) === true) ? $data['function'] : ''),
((isset($data['class']) === true) ? $data['class'] : ''),
((isset($data['onChange']) === true) ? $data['onChange'] : ''),
((isset($data['autocomplete']) === true) ? $data['autocomplete'] : ''),
((isset($data['autofocus']) === true) ? $data['autofocus'] : false)
);
break;
case 'email': case 'email':
$output .= html_print_input_email($data); $output .= html_print_input_email($data);
break; break;
@ -3600,7 +3602,8 @@ function html_print_input($data, $wrapper='div', $input_only=false)
((isset($data['disabled']) === true) ? $data['disabled'] : false), ((isset($data['disabled']) === true) ? $data['disabled'] : false),
((isset($data['style']) === true) ? $data['style'] : false), ((isset($data['style']) === true) ? $data['style'] : false),
((isset($data['size']) === true) ? $data['size'] : false), ((isset($data['size']) === true) ? $data['size'] : false),
((isset($data['trucate_size']) === true) ? $data['trucate_size'] : GENERIC_SIZE_TEXT) ((isset($data['trucate_size']) === true) ? $data['trucate_size'] : GENERIC_SIZE_TEXT),
((isset($data['class']) === true) ? $data['class'] : '')
); );
break; break;

View File

@ -783,7 +783,7 @@ function snmp_browser_print_container($return=false, $width='100%', $height='60%
$table2->cellstyle[0][2] = 'text-align:center;'; $table2->cellstyle[0][2] = 'text-align:center;';
// This extra div that can be handled by jquery's dialog. // This extra div that can be handled by jquery's dialog.
$output = '<div id="snmp_browser_container" style="display:'.$display.'">'; $output = '<div id="snmp_browser_container" style="'.$display.'">';
$output .= '<div style="text-align: left; width: '.$width.'; height: '.$height.';">'; $output .= '<div style="text-align: left; width: '.$width.'; height: '.$height.';">';
$output .= '<div style="width: 100%">'; $output .= '<div style="width: 100%">';
$output .= html_print_table($table, true); $output .= html_print_table($table, true);

View File

@ -123,11 +123,11 @@ function treeview_printModuleTable($id_module, $server_data=false, $no_head=fals
$row['data'] = $module_group; $row['data'] = $module_group;
$table->data['module_group'] = $row; $table->data['module_group'] = $row;
// Description // Description.
$row = []; $row = [];
$row['title'] = __('Description'); $row['title'] = __('Description');
$row['data'] = ui_print_truncate_text( $row['data'] = ui_print_truncate_text(
$module['descripcion'];, $module['descripcion'],
'description', 'description',
true, true,
true, true,
@ -761,21 +761,25 @@ function treeview_printTable($id_agente, $server_data=[], $no_head=false)
} }
} }
// End of table advanced // End of table advanced.
$table_advanced = html_print_table($table, true); $table_advanced = html_print_table($table, true);
$table_advanced .= '<br>'; $table_advanced .= '<br>';
ui_toggle($table_advanced, __('Advanced information')); ui_toggle($table_advanced, __('Advanced information'));
if ($config['agentaccess']) { if ($config['agentaccess']) {
$access_graph = '<div style="width:100%; height:130px;">'; $access_graph = '<div style="width:100%; height:130px; text-align:center;">';
$access_graph .= graphic_agentaccess( $access_graph .= graphic_agentaccess(
$id_agente, $id_agente,
SECONDS_1DAY, SECONDS_1DAY,
true false
); );
$access_graph .= '</div>'; $access_graph .= '</div>';
ui_toggle($access_graph, __('Agent access rate (24h)'));
ui_toggle(
$access_graph,
__('Agent access rate (24h)')
);
} }
$events_graph = '<div style="width: 100%; height: 90px; display: flex; flex-direction: row; justify-content: center;">'; $events_graph = '<div style="width: 100%; height: 90px; display: flex; flex-direction: row; justify-content: center;">';

View File

@ -2848,6 +2848,7 @@ function ui_print_status_sets(
* [ * [
* 'page' => 'operation/agentes/ver_agente', Target page. * 'page' => 'operation/agentes/ver_agente', Target page.
* 'interval' => 100 / $agent["intervalo"], Ask every interval seconds. * 'interval' => 100 / $agent["intervalo"], Ask every interval seconds.
* 'simple' => 0,
* 'data' => [ Data to be sent to target page. * 'data' => [ Data to be sent to target page.
* 'id_agente' => $id_agente, * 'id_agente' => $id_agente,
* 'refresh_contact' => 1, * 'refresh_contact' => 1,
@ -2881,18 +2882,60 @@ function ui_progress(
$text = $progress.'%'; $text = $progress.'%';
} }
$id = uniqid();
ui_require_css_file('progress'); ui_require_css_file('progress');
$output .= '<span class="progress_main" data-label="'.$text; $output .= '<span id="'.$id.'" class="progress_main" data-label="'.$text;
$output .= '" style="width: '.$width.'; height: '.$height.'em; border: 1px solid '.$color.'">'; $output .= '" style="width: '.$width.'; height: '.$height.'em; border: 1px solid '.$color.'">';
$output .= '<span class="progress" style="width: '.$progress.'%; background: '.$color.'"></span>'; $output .= '<span id="'.$id.'_progress" class="progress" style="width: '.$progress.'%; background: '.$color.'"></span>';
$output .= '</span>'; $output .= '</span>';
if ($ajax !== false && is_array($ajax)) { if ($ajax !== false && is_array($ajax)) {
if ($ajax['simple']) {
$output .= '<script type="text/javascript"> $output .= '<script type="text/javascript">
$(document).ready(function() { $(document).ready(function() {
setInterval(() => { setInterval(() => {
last = $(".progress_main").attr("data-label").split(" ")[0]*1; $.post({
width = $(".progress").width() / $(".progress").parent().width() * 100; url: "'.ui_get_full_url('ajax.php', false, false, false).'",
data: {';
if (is_array($ajax['data'])) {
foreach ($ajax['data'] as $token => $value) {
$output .= '
'.$token.':"'.$value.'",';
}
}
$output .= '
page: "'.$ajax['page'].'"
},
success: function(data) {
try {
val = JSON.parse(data);
$("#'.$id.'").attr("data-label", val + " %");
$("#'.$id.'_progress").width(val+"%");';
if (isset($ajax['oncomplete'])) {
$output .= '
if (val == 100) {
'.$ajax['oncomplete'].'($("#'.$id.'"));
}
';
}
$output .= '
} catch (e) {
console.error(e);
}
}
});
}, '.($ajax['interval'] > 0 ? $ajax['interval'] * 1000 : 30000 ).');
});
</script>';
} else {
$output .= '<script type="text/javascript">
$(document).ready(function() {
setInterval(() => {
last = $("#'.$id.'").attr("data-label").split(" ")[0]*1;
width = $("#'.$id.'_progress").width() / $("#'.$id.'_progress").parent().width() * 100;
width_interval = '.$ajax['interval'].'; width_interval = '.$ajax['interval'].';
if (last % 10 == 0) { if (last % 10 == 0) {
$.post({ $.post({
@ -2911,27 +2954,28 @@ function ui_progress(
success: function(data) { success: function(data) {
try { try {
val = JSON.parse(data); val = JSON.parse(data);
$(".progress_main").attr("data-label", val["last_contact"]+" s"); $("#'.$id.'").attr("data-label", val["last_contact"]+" s");
$(".progress").width(val["progress"]+"%"); $("#'.$id.'_progress").width(val["progress"]+"%");
} catch (e) { } catch (e) {
console.error(e); console.error(e);
$(".progress_text").attr("data-label", (last -1) + " s"); $(".progress_text").attr("data-label", (last -1) + " s");
if (width < 100) { if (width < 100) {
$(".progress").width((width+width_interval) + "%"); $("#'.$id.'_progress").width((width+width_interval) + "%");
} }
} }
} }
}); });
} else { } else {
$(".progress_main").attr("data-label", (last -1) + " s"); $("#'.$id.'").attr("data-label", (last -1) + " s");
if (width < 100) { if (width < 100) {
$(".progress").width((width+width_interval) + "%"); $("#'.$id.'_progress").width((width+width_interval) + "%");
} }
} }
}, 1000); }, 1000);
}); });
</script>'; </script>';
} }
}
if (!$return) { if (!$return) {
echo $output; echo $output;
@ -3469,10 +3513,13 @@ function ui_print_datatable(array $parameters)
ui_require_javascript_file('buttons.html5.min'); ui_require_javascript_file('buttons.html5.min');
ui_require_javascript_file('buttons.print.min'); ui_require_javascript_file('buttons.print.min');
$output = $include.$output; if (isset($parameters['return']) && $parameters['return'] == true) {
// Compat.
$parameters['print'] = false;
}
// Print datatable if needed. // Print datatable if needed.
if (isset($parameters['print']) === false || $parameters['print'] === false) { if (isset($parameters['print']) === false || $parameters['print'] === true) {
echo $output; echo $output;
} }
@ -3673,8 +3720,8 @@ function ui_toggle(
// Generate unique Id. // Generate unique Id.
$uniqid = uniqid(''); $uniqid = uniqid('');
$image_a = html_print_image($img_a, true, false, true); $image_a = html_print_image($img_a, true, [ 'style' => 'object-fit: contain;' ], true);
$image_b = html_print_image($img_b, true, false, true); $image_b = html_print_image($img_b, true, [ 'style' => 'object-fit: contain;' ], true);
// Options. // Options.
if ($hidden_default) { if ($hidden_default) {
$style = 'display:none'; $style = 'display:none';
@ -3698,6 +3745,7 @@ function ui_toggle(
$original, $original,
true, true,
[ [
'style' => 'object-fit: contain;',
'title' => $title, 'title' => $title,
'id' => 'image_'.$uniqid, 'id' => 'image_'.$uniqid,
] ]

View File

@ -1604,15 +1604,14 @@
}), }),
d.GridStackUI d.GridStackUI
); );
}) }),
/** /**
* gridstack.js 0.3.0 * gridstack.js 0.3.0
* http://troolee.github.io/gridstack.js/ * http://troolee.github.io/gridstack.js/
* (c) 2014-2016 Pavel Reznikov, Dylan Weiss * (c) 2014-2016 Pavel Reznikov, Dylan Weiss
* gridstack.js may be freely distributed under the MIT license. * gridstack.js may be freely distributed under the MIT license.
* @preserve * @preserve
*/, */ (function(a) {
(function(a) {
if ("function" == typeof define && define.amd) if ("function" == typeof define && define.amd)
define([ define([
"jquery", "jquery",

View File

@ -0,0 +1,2 @@
// http://code.accursoft.com/caret - 1.3.3
!function(e){e.fn.caret=function(e){var t=this[0],n="true"===t.contentEditable;if(0==arguments.length){if(window.getSelection){if(n){t.focus();var o=window.getSelection().getRangeAt(0),r=o.cloneRange();return r.selectNodeContents(t),r.setEnd(o.endContainer,o.endOffset),r.toString().length}return t.selectionStart}if(document.selection){if(t.focus(),n){var o=document.selection.createRange(),r=document.body.createTextRange();return r.moveToElementText(t),r.setEndPoint("EndToEnd",o),r.text.length}var e=0,c=t.createTextRange(),r=document.selection.createRange().duplicate(),a=r.getBookmark();for(c.moveToBookmark(a);0!==c.moveStart("character",-1);)e++;return e}return t.selectionStart?t.selectionStart:0}if(-1==e&&(e=this[n?"text":"val"]().length),window.getSelection)n?(t.focus(),window.getSelection().collapse(t.firstChild,e)):t.setSelectionRange(e,e);else if(document.body.createTextRange)if(n){var c=document.body.createTextRange();c.moveToElementText(t),c.moveStart("character",e),c.collapse(!0),c.select()}else{var c=t.createTextRange();c.move("character",e),c.select()}return n||t.focus(),e}}(jQuery);

View File

@ -0,0 +1,370 @@
/*
jQuery tagEditor v1.0.21
Copyright (c) 2014 Simon Steinberger / Pixabay
GitHub: https://github.com/Pixabay/jQuery-tagEditor
License: http://www.opensource.org/licenses/mit-license.php
*/
(function($){
// auto grow input (stackoverflow.com/questions/931207)
$.fn.tagEditorInput=function(){var t=" ",e=$(this),n=parseInt(e.css("fontSize")),i=$("<span/>").css({position:"absolute",top:-9999,left:-9999,width:"auto",fontSize:e.css("fontSize"),fontFamily:e.css("fontFamily"),fontWeight:e.css("fontWeight"),letterSpacing:e.css("letterSpacing"),whiteSpace:"nowrap"}),s=function(){if(t!==(t=e.val())){i.text(t);var s=i.width()+n;20>s&&(s=20),s!=e.width()&&e.width(s)}};return i.insertAfter(e),e.bind("keyup keydown focus",s)};
// plugin with val as parameter for public methods
$.fn.tagEditor = function(options, val, blur){
// helper
function escape(tag) {
return tag.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
// build options dictionary with default values
var blur_result, o = $.extend({}, $.fn.tagEditor.defaults, options), selector = this;
// store regex and default delimiter in options for later use
o.dregex = new RegExp('['+o.delimiter.replace('-', '\-')+']', 'g');
// public methods
if (typeof options == 'string') {
// depending on selector, response may contain tag lists of multiple editor instances
var response = [];
selector.each(function(){
// the editor is the next sibling to the hidden, original field
var el = $(this), o = el.data('options'), ed = el.next('.tag-editor');
if (options == 'getTags')
response.push({field: el[0], editor: ed, tags: ed.data('tags')});
else if (options == 'addTag') {
if (o.maxTags && ed.data('tags').length >= o.maxTags) return false;
// insert new tag
$('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>').appendTo(ed).find('.tag-editor-tag')
.html('<input type="text" maxlength="'+o.maxLength+'">').addClass('active').find('input').val(val).blur();
if (!blur) ed.click();
else $('.placeholder', ed).remove();
} else if (options == 'removeTag') {
// trigger delete on matching tag, then click editor to create a new tag
$('.tag-editor-tag', ed).filter(function(){return $(this).text()==val;}).closest('li').find('.tag-editor-delete').click();
if (!blur) ed.click();
} else if (options == 'destroy') {
el.removeClass('tag-editor-hidden-src').removeData('options').off('focus.tag-editor').next('.tag-editor').remove();
}
});
return options == 'getTags' ? response : this;
}
// delete selected tags on backspace, delete, ctrl+x
if (window.getSelection) $(document).off('keydown.tag-editor').on('keydown.tag-editor', function(e){
if (e.which == 8 || e.which == 46 || e.ctrlKey && e.which == 88) {
try {
var sel = getSelection(), el = document.activeElement.tagName != 'INPUT' ? $(sel.getRangeAt(0).startContainer.parentNode).closest('.tag-editor') : 0;
} catch(e){ el = 0; }
if (sel.rangeCount > 0 && el && el.length) {
var tags = [], splits = sel.toString().split(el.prev().data('options').dregex);
for (i=0; i<splits.length; i++){ var tag = $.trim(splits[i]); if (tag) tags.push(tag); }
$('.tag-editor-tag', el).each(function(){
if (~$.inArray($(this).text(), tags)) $(this).closest('li').find('.tag-editor-delete').click();
});
return false;
}
}
});
return selector.each(function(){
var el = $(this), tag_list = []; // cache current tags
// create editor (ed) instance
var ed = $('<ul '+(o.clickDelete ? 'oncontextmenu="return false;" ' : '')+'class="tag-editor"></ul>').insertAfter(el);
el.addClass('tag-editor-hidden-src') // hide original field
.data('options', o) // set data on hidden field
.on('focus.tag-editor', function(){ ed.click(); }); // simulate tabindex
// add dummy item for min-height on empty editor
ed.append('<li style="width:1px">&nbsp;</li>');
// markup for new tag
var new_tag = '<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>';
// helper: update global data
function set_placeholder(){
if (o.placeholder && !tag_list.length && !$('.deleted, .placeholder, input', ed).length)
ed.append('<li class="placeholder"><div>'+o.placeholder+'</div></li>');
}
// helper: update global data
function update_globals(init){
var old_tags = tag_list.toString();
tag_list = $('.tag-editor-tag:not(.deleted)', ed).map(function(i, e) {
var val = $.trim($(this).hasClass('active') ? $(this).find('input').val() : $(e).text());
if (val) return val;
}).get();
ed.data('tags', tag_list);
el.val(tag_list.join(o.delimiter[0]));
// change callback except for plugin init
if (!init) if (old_tags != tag_list.toString()) o.onChange(el, ed, tag_list);
set_placeholder();
}
ed.click(function(e, closest_tag){
var d, dist = 99999, loc;
// do not create tag when user selects tags by text selection
if (window.getSelection && getSelection() != '') return;
if (o.maxTags && ed.data('tags').length >= o.maxTags) { ed.find('input').blur(); return false; }
blur_result = true
$('input:focus', ed).blur();
if (!blur_result) return false;
blur_result = true
// always remove placeholder on click
$('.placeholder', ed).remove();
if (closest_tag && closest_tag.length)
loc = 'before';
else {
// calculate tag closest to click position
$('.tag-editor-tag', ed).each(function(){
var tag = $(this), to = tag.offset(), tag_x = to.left, tag_y = to.top;
if (e.pageY >= tag_y && e.pageY <= tag_y+tag.height()) {
if (e.pageX < tag_x) loc = 'before', d = tag_x - e.pageX;
else loc = 'after', d = e.pageX - tag_x - tag.width();
if (d < dist) dist = d, closest_tag = tag;
}
});
}
if (loc == 'before') {
$(new_tag).insertBefore(closest_tag.closest('li')).find('.tag-editor-tag').click();
} else if (loc == 'after')
$(new_tag).insertAfter(closest_tag.closest('li')).find('.tag-editor-tag').click();
else // empty editor
$(new_tag).appendTo(ed).find('.tag-editor-tag').click();
return false;
});
ed.on('click', '.tag-editor-delete', function(e){
// delete icon is hidden when input is visible; place cursor near invisible delete icon on click
if ($(this).prev().hasClass('active')) { $(this).closest('li').find('input').caret(-1); return false; }
var li = $(this).closest('li'), tag = li.find('.tag-editor-tag');
if (o.beforeTagDelete(el, ed, tag_list, tag.text()) === false) return false;
tag.addClass('deleted').animate({width: 0}, o.animateDelete, function(){ li.remove(); set_placeholder(); });
update_globals();
return false;
});
// delete on right mouse click or ctrl+click
if (o.clickDelete)
ed.on('mousedown', '.tag-editor-tag', function(e){
if (e.ctrlKey || e.which > 1) {
var li = $(this).closest('li'), tag = li.find('.tag-editor-tag');
if (o.beforeTagDelete(el, ed, tag_list, tag.text()) === false) return false;
tag.addClass('deleted').animate({width: 0}, o.animateDelete, function(){ li.remove(); set_placeholder(); });
update_globals();
return false;
}
});
ed.on('click', '.tag-editor-tag', function(e){
// delete on right click or ctrl+click -> exit
if (o.clickDelete && (e.ctrlKey || e.which > 1)) return false;
if (!$(this).hasClass('active')) {
var tag = $(this).text();
// guess cursor position in text input
var left_percent = Math.abs(($(this).offset().left - e.pageX)/$(this).width()), caret_pos = parseInt(tag.length*left_percent),
input = $(this).html('<input type="text" maxlength="'+o.maxLength+'" value="'+escape(tag)+'">').addClass('active').find('input');
input.data('old_tag', tag).tagEditorInput().focus().caret(caret_pos);
if (o.autocomplete) {
var aco = $.extend({}, o.autocomplete);
// extend user provided autocomplete select method
var ac_select = 'select' in aco ? o.autocomplete.select : '';
aco.select = function(e, ui){ if (ac_select) ac_select(e, ui); setTimeout(function(){
ed.trigger('click', [$('.active', ed).find('input').closest('li').next('li').find('.tag-editor-tag')]);
}, 20); };
input.autocomplete(aco);
}
}
return false;
});
// helper: split into multiple tags, e.g. after paste
function split_cleanup(input){
var li = input.closest('li'), sub_tags = input.val().replace(/ +/, ' ').split(o.dregex),
old_tag = input.data('old_tag'), old_tags = tag_list.slice(0), exceeded = false, cb_val; // copy tag_list
for (var i=0; i<sub_tags.length; i++) {
tag = $.trim(sub_tags[i]).slice(0, o.maxLength);
if (o.forceLowercase) tag = tag.toLowerCase();
cb_val = o.beforeTagSave(el, ed, old_tags, old_tag, tag);
tag = cb_val || tag;
if (cb_val === false || !tag) continue;
// remove duplicates
if (o.removeDuplicates && ~$.inArray(tag, old_tags))
$('.tag-editor-tag', ed).each(function(){ if ($(this).text() == tag) $(this).closest('li').remove(); });
old_tags.push(tag);
li.before('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+escape(tag)+'</div><div class="tag-editor-delete"><i></i></div></li>');
if (o.maxTags && old_tags.length >= o.maxTags) { exceeded = true; break; }
}
input.attr('maxlength', o.maxLength).removeData('old_tag').val('')
if (exceeded) input.blur(); else input.focus();
update_globals();
}
ed.on('blur', 'input', function(e){
e.stopPropagation();
var input = $(this), old_tag = input.data('old_tag'), tag = $.trim(input.val().replace(/ +/, ' ').replace(o.dregex, o.delimiter[0]));
if (!tag) {
if (old_tag && o.beforeTagDelete(el, ed, tag_list, old_tag) === false) {
input.val(old_tag).focus();
blur_result = false;
update_globals();
return;
}
try { input.closest('li').remove(); } catch(e){}
if (old_tag) update_globals();
}
else if (tag.indexOf(o.delimiter[0])>=0) { split_cleanup(input); return; }
else if (tag != old_tag) {
if (o.forceLowercase) tag = tag.toLowerCase();
cb_val = o.beforeTagSave(el, ed, tag_list, old_tag, tag);
tag = cb_val || tag;
if (cb_val === false) {
if (old_tag) {
input.val(old_tag).focus();
blur_result = false;
update_globals();
return;
}
try { input.closest('li').remove(); } catch(e){}
if (old_tag) update_globals();
}
// remove duplicates
else if (o.removeDuplicates)
$('.tag-editor-tag:not(.active)', ed).each(function(){ if ($(this).text() == tag) $(this).closest('li').remove(); });
}
input.parent().html(escape(tag)).removeClass('active');
if (tag != old_tag) update_globals();
set_placeholder();
});
var pasted_content;
ed.on('paste', 'input', function(e){
$(this).removeAttr('maxlength');
pasted_content = $(this);
setTimeout(function(){ split_cleanup(pasted_content); }, 30);
});
// keypress delimiter
var inp;
ed.on('keypress', 'input', function(e){
if (o.delimiter.indexOf(String.fromCharCode(e.which))>=0) {
inp = $(this);
setTimeout(function(){ split_cleanup(inp); }, 20);
}
});
ed.on('keydown', 'input', function(e){
var $t = $(this);
// left/up key + backspace key on empty field
if ((e.which == 37 || !o.autocomplete && e.which == 38) && !$t.caret() || e.which == 8 && !$t.val()) {
var prev_tag = $t.closest('li').prev('li').find('.tag-editor-tag');
if (prev_tag.length) prev_tag.click().find('input').caret(-1);
else if ($t.val() && !(o.maxTags && ed.data('tags').length >= o.maxTags)) $(new_tag).insertBefore($t.closest('li')).find('.tag-editor-tag').click();
return false;
}
// right/down key
else if ((e.which == 39 || !o.autocomplete && e.which == 40) && ($t.caret() == $t.val().length)) {
var next_tag = $t.closest('li').next('li').find('.tag-editor-tag');
if (next_tag.length) next_tag.click().find('input').caret(0);
else if ($t.val()) ed.click();
return false;
}
// tab key
else if (e.which == 9) {
// shift+tab
if (e.shiftKey) {
var prev_tag = $t.closest('li').prev('li').find('.tag-editor-tag');
if (prev_tag.length) prev_tag.click().find('input').caret(0);
else if ($t.val() && !(o.maxTags && ed.data('tags').length >= o.maxTags)) $(new_tag).insertBefore($t.closest('li')).find('.tag-editor-tag').click();
// allow tabbing to previous element
else {
el.attr('disabled', 'disabled');
setTimeout(function(){ el.removeAttr('disabled'); }, 30);
return;
}
return false;
// tab
} else {
var next_tag = $t.closest('li').next('li').find('.tag-editor-tag');
if (next_tag.length) next_tag.click().find('input').caret(0);
else if ($t.val()) ed.click();
else return; // allow tabbing to next element
return false;
}
}
// del key
else if (e.which == 46 && (!$.trim($t.val()) || ($t.caret() == $t.val().length))) {
var next_tag = $t.closest('li').next('li').find('.tag-editor-tag');
if (next_tag.length) next_tag.click().find('input').caret(0);
else if ($t.val()) ed.click();
return false;
}
// enter key
else if (e.which == 13) {
ed.trigger('click', [$t.closest('li').next('li').find('.tag-editor-tag')]);
// trigger blur if maxTags limit is reached
if (o.maxTags && ed.data('tags').length >= o.maxTags) ed.find('input').blur();
return false;
}
// pos1
else if (e.which == 36 && !$t.caret()) ed.find('.tag-editor-tag').first().click();
// end
else if (e.which == 35 && $t.caret() == $t.val().length) ed.find('.tag-editor-tag').last().click();
// esc
else if (e.which == 27) {
$t.val($t.data('old_tag') ? $t.data('old_tag') : '').blur();
return false;
}
});
// create initial tags
var tags = o.initialTags.length ? o.initialTags : el.val().split(o.dregex);
for (var i=0; i<tags.length; i++) {
if (o.maxTags && i >= o.maxTags) break;
var tag = $.trim(tags[i].replace(/ +/, ' '));
if (tag) {
if (o.forceLowercase) tag = tag.toLowerCase();
tag_list.push(tag);
ed.append('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+escape(tag)+'</div><div class="tag-editor-delete"><i></i></div></li>');
}
}
update_globals(true); // true -> no onChange callback
// init sortable
if (o.sortable && $.fn.sortable) ed.sortable({
distance: 5, cancel: '.tag-editor-spacer, input', helper: 'clone',
update: function(){ update_globals(); }
});
});
};
$.fn.tagEditor.defaults = {
initialTags: [],
maxTags: 0,
maxLength: 50,
delimiter: ',;',
placeholder: '',
forceLowercase: true,
removeDuplicates: true,
clickDelete: false,
animateDelete: 175,
sortable: true, // jQuery UI sortable
autocomplete: null, // options dict for jQuery UI autocomplete
// callbacks
onChange: function(){},
beforeTagSave: function(){},
beforeTagDelete: function(){}
};
}(jQuery));

File diff suppressed because one or more lines are too long

View File

@ -837,8 +837,8 @@ function post_process_select_events(name) {
*/ */
function period_select_init(name, allow_zero) { function period_select_init(name, allow_zero) {
// Manual mode is hidden by default // Manual mode is hidden by default
$("#" + name + "_manual").hide(); $("#" + name + "_manual").css("display", "none");
$("#" + name + "_default").show(); $("#" + name + "_default").css("display", "flex");
// If the text input is empty, we put on it 5 minutes by default // If the text input is empty, we put on it 5 minutes by default
if ($("#text-" + name + "_text").val() == "") { if ($("#text-" + name + "_text").val() == "") {
@ -852,8 +852,8 @@ function period_select_init(name, allow_zero) {
} }
} else if ($("#text-" + name + "_text").val() == 0 && allow_zero != true) { } else if ($("#text-" + name + "_text").val() == 0 && allow_zero != true) {
$("#" + name + "_units option:last").prop("selected", false); $("#" + name + "_units option:last").prop("selected", false);
$("#" + name + "_manual").show(); $("#" + name + "_manual").css("display", "flex");
$("#" + name + "_default").hide(); $("#" + name + "_default").css("display", "none");
} }
} }
@ -941,13 +941,13 @@ function selectFirst(name) {
*/ */
function toggleBoth(name) { function toggleBoth(name) {
if ($("#" + name + "_default").css("display") == "none") { if ($("#" + name + "_default").css("display") == "none") {
$("#" + name + "_default").css("display", "inline"); $("#" + name + "_default").css("display", "flex");
} else { } else {
$("#" + name + "_default").css("display", "none"); $("#" + name + "_default").css("display", "none");
} }
if ($("#" + name + "_manual").css("display") == "none") { if ($("#" + name + "_manual").css("display") == "none") {
$("#" + name + "_manual").css("display", "inline"); $("#" + name + "_manual").css("display", "flex");
} else { } else {
$("#" + name + "_manual").css("display", "none"); $("#" + name + "_manual").css("display", "none");
} }

View File

@ -118,30 +118,26 @@ function execute_response(event_id, server_id) {
} }
response["target"] = get_response_target(event_id, response_id, server_id); response["target"] = get_response_target(event_id, response_id, server_id);
response["event_id"] = event_id;
response["server_id"] = server_id;
switch (response["type"]) { if (response["type"] == "url" && response["new_window"] == 1) {
case "command":
show_response_dialog(event_id, response_id, response);
break;
case "url":
if (response["new_window"] == 1) {
window.open(response["target"], "_blank"); window.open(response["target"], "_blank");
} else { } else {
show_response_dialog(event_id, response_id, response); show_response_dialog(response_id, response);
}
break;
} }
} }
//Show the modal window of an event response //Show the modal window of an event response
function show_response_dialog(event_id, response_id, response) { function show_response_dialog(response_id, response) {
var params = []; var params = [];
params.push("page=include/ajax/events"); params.push("page=include/ajax/events");
params.push("dialogue_event_response=1"); params.push("dialogue_event_response=1");
params.push("massive=0"); params.push("massive=0");
params.push("event_id=" + event_id); params.push("event_id=" + response["event_id"]);
params.push("target=" + response["target"]); params.push("target=" + response["target"]);
params.push("response_id=" + response_id); params.push("response_id=" + response_id);
params.push("server_id=" + response["server_id"]);
jQuery.ajax({ jQuery.ajax({
data: params.join("&"), data: params.join("&"),
@ -159,7 +155,7 @@ function show_response_dialog(event_id, response_id, response) {
draggable: true, draggable: true,
modal: false, modal: false,
open: function() { open: function() {
perform_response(response["target"], response_id); perform_response(response, response_id);
}, },
width: response["modal_width"], width: response["modal_width"],
height: response["modal_height"] height: response["modal_height"]
@ -171,7 +167,6 @@ function show_response_dialog(event_id, response_id, response) {
//Show the modal window of event responses when multiple events are selected //Show the modal window of event responses when multiple events are selected
function show_massive_response_dialog( function show_massive_response_dialog(
event_id,
response_id, response_id,
response, response,
out_iterator, out_iterator,
@ -183,13 +178,14 @@ function show_massive_response_dialog(
params.push("massive=1"); params.push("massive=1");
params.push("end=" + end); params.push("end=" + end);
params.push("out_iterator=" + out_iterator); params.push("out_iterator=" + out_iterator);
params.push("event_id=" + event_id); params.push("event_id=" + response["event_id"]);
params.push("target=" + response["target"]); params.push("target=" + response["target"]);
params.push("response_id=" + response_id); params.push("response_id=" + response_id);
params.push("server_id=" + response["server_id"]);
jQuery.ajax({ jQuery.ajax({
data: params.join("&"), data: params.join("&"),
response_tg: response["target"], response_tg: response,
response_id: response_id, response_id: response_id,
out_iterator: out_iterator, out_iterator: out_iterator,
type: "POST", type: "POST",
@ -384,7 +380,7 @@ function get_response_target(
} }
// Perform a response and put the output into a div // Perform a response and put the output into a div
function perform_response(target, response_id) { function perform_response(response, response_id) {
$("#re_exec_command").hide(); $("#re_exec_command").hide();
$("#response_loading_command").show(); $("#response_loading_command").show();
$("#response_out").html(""); $("#response_out").html("");
@ -392,8 +388,10 @@ function perform_response(target, response_id) {
var params = []; var params = [];
params.push("page=include/ajax/events"); params.push("page=include/ajax/events");
params.push("perform_event_response=1"); params.push("perform_event_response=1");
params.push("target=" + target); params.push("target=" + response["target"]);
params.push("response_id=" + response_id); params.push("response_id=" + response_id);
params.push("event_id=" + response["event_id"]);
params.push("server_id=" + response["server_id"]);
jQuery.ajax({ jQuery.ajax({
data: params.join("&"), data: params.join("&"),
@ -413,7 +411,7 @@ function perform_response(target, response_id) {
} }
// Perform a response and put the output into a div // Perform a response and put the output into a div
function perform_response_massive(target, response_id, out_iterator) { function perform_response_massive(response, response_id, out_iterator) {
$("#re_exec_command").hide(); $("#re_exec_command").hide();
$("#response_loading_command_" + out_iterator).show(); $("#response_loading_command_" + out_iterator).show();
$("#response_out_" + out_iterator).html(""); $("#response_out_" + out_iterator).html("");
@ -421,8 +419,10 @@ function perform_response_massive(target, response_id, out_iterator) {
var params = []; var params = [];
params.push("page=include/ajax/events"); params.push("page=include/ajax/events");
params.push("perform_event_response=1"); params.push("perform_event_response=1");
params.push("target=" + target); params.push("target=" + response["target"]);
params.push("response_id=" + response_id); params.push("response_id=" + response_id);
params.push("event_id=" + response["event_id"]);
params.push("server_id=" + response["server_id"]);
jQuery.ajax({ jQuery.ajax({
data: params.join("&"), data: params.join("&"),
@ -916,17 +916,24 @@ function check_massive_response_event(
$(".chk_val:checked").each(function() { $(".chk_val:checked").each(function() {
var event_id = $(this).val(); var event_id = $(this).val();
var server_id = $("#hidden-server_id_" + event_id).val(); var meta = $("#hidden-meta").val();
var server_id = 0;
if (meta) {
server_id = $("#hidden-server_id_" + event_id).val();
}
response["target"] = get_response_target( response["target"] = get_response_target(
event_id, event_id,
response_id, response_id,
server_id, server_id,
response_command response_command
); );
response["server_id"] = server_id;
response["event_id"] = event_id;
if (total_checked - 1 === counter) end = 1; if (total_checked - 1 === counter) end = 1;
show_massive_response_dialog(event_id, response_id, response, counter, end); show_massive_response_dialog(response_id, response, counter, end);
counter++; counter++;
}); });

View File

@ -22,7 +22,7 @@ function progress_task_list(id, title) {
autoOpen: false, autoOpen: false,
modal: false, modal: false,
resizable: false, resizable: false,
draggable: false, draggable: true,
closeOnEscape: true, closeOnEscape: true,
width: 800, width: 800,
height: 600, height: 600,
@ -35,18 +35,22 @@ function progress_task_list(id, title) {
// Function var. // Function var.
var handleFetchTaskList = function(err, data) { var handleFetchTaskList = function(err, data) {
if (err) { if (err) {
console.error(err);
}
if (data.error) {
// TODO: Show info about the problem. // TODO: Show info about the problem.
$elem.html(data.error);
} else {
$elem.html(data.html);
} }
$elem.html(data.html);
if (!$elem.dialog("isOpen")) $elem.dialog("open"); if (!$elem.dialog("isOpen")) $elem.dialog("open");
};
if (data.status != -1) { if (!$elem.dialog("isOpen"))
timeoutRef = setTimeout(function() { timeoutRef = setInterval(function() {
xhr = fetchTaskList(id, handleFetchTaskList); xhr = fetchTaskList(id, handleFetchTaskList);
}, 3000); }, 3000);
}
};
xhr = fetchTaskList(id, handleFetchTaskList); xhr = fetchTaskList(id, handleFetchTaskList);
} }
@ -60,12 +64,13 @@ function progress_task_list(id, title) {
function fetchTaskList(id, callback) { function fetchTaskList(id, callback) {
return jQuery.ajax({ return jQuery.ajax({
data: { data: {
page: "include/ajax/task_list.ajax", page: "godmode/servers/discovery",
progress_task_discovery: 1, wiz: "tasklist",
method: "progressTaskDiscovery",
id: id id: id
}, },
type: "POST", type: "POST",
url: "ajax.php", url: $("#ajax-url").val(),
dataType: "json", dataType: "json",
success: function(data) { success: function(data) {
callback(null, data); callback(null, data);
@ -95,12 +100,13 @@ function show_map(id, name) {
jQuery.ajax({ jQuery.ajax({
data: { data: {
page: "include/ajax/task_list.ajax", page: "godmode/servers/discovery",
showmap: 1, wiz: "tasklist",
method: "taskShowmap",
id: id id: id
}, },
type: "POST", type: "POST",
url: "ajax.php", url: $("#ajax-url").val(),
dataType: "html", dataType: "html",
success: function(data) { success: function(data) {
$("#map_task") $("#map_task")
@ -109,3 +115,106 @@ function show_map(id, name) {
} }
}); });
} }
function show_review(id, name) {
load_modal({
target: $("#task_review"),
form: "review",
url: $("#ajax-url").val(),
modal: {
title: "Review " + name,
ok: "OK",
cancel: "Cancel"
},
ajax_callback: function(data) {
var title = $("#success-str").val();
var text = "";
var failed = 0;
try {
data = JSON.parse(data);
text = data["result"];
} catch (err) {
title = $("#failed-str").val();
text = err.message;
failed = 1;
}
if (!failed && data["error"] != undefined) {
title = $("#failed-str").val();
text = data["error"];
failed = 1;
}
if (data["report"] != undefined) {
data["report"].forEach(function(item) {
text += "<br>" + item;
});
}
$("#msg").empty();
$("#msg").html(text);
$("#msg").dialog({
width: 450,
position: {
my: "center",
at: "center",
of: window,
collision: "fit"
},
maxHeight: 400,
title: title,
buttons: [
{
class:
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
text: "OK",
click: function(e) {
if (!failed) {
$(".ui-dialog-content").dialog("close");
$("#task_review").empty();
location.reload();
} else {
$(this).dialog("close");
}
}
}
]
});
},
extradata: [
{
name: "id",
value: id
},
{
name: "wiz",
value: "tasklist"
}
],
onshow: {
page: "godmode/servers/discovery",
method: "showTaskReview",
maxHeight: 800
},
onsubmit: {
page: "godmode/servers/discovery",
method: "parseTaskReview"
}
});
}
function force_task_run(url) {
window.location = url;
}
function force_task(url, ask) {
if (ask != undefined) {
confirmDialog({
title: ask.title,
message: ask.message,
onAccept: function() {
force_task_run(url);
}
});
} else {
force_task_run(url);
}
}

View File

@ -319,6 +319,21 @@ function load_modal(settings) {
contentType: false, contentType: false,
data: data, data: data,
success: function(data) { success: function(data) {
if (settings.onshow.parser) {
data = settings.onshow.parser(data);
} else {
data = (function(d) {
try {
d = JSON.parse(d);
} catch (e) {
// Not JSON
return d;
}
if (d.error) return d.error;
if (d.result) return d.result;
})(data);
}
settings.target.html(data); settings.target.html(data);
if (settings.onload != undefined) { if (settings.onload != undefined) {
settings.onload(data); settings.onload(data);
@ -338,6 +353,12 @@ function load_modal(settings) {
? settings.onshow.maxHeight ? settings.onshow.maxHeight
: "auto", : "auto",
overlay: settings.modal.overlay, overlay: settings.modal.overlay,
position: {
my: "top+20%",
at: "top",
of: window,
collision: "fit"
},
buttons: required_buttons, buttons: required_buttons,
closeOnEscape: true, closeOnEscape: true,
open: function() { open: function() {
@ -386,6 +407,7 @@ function confirmDialog(settings) {
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel", "ui-widget ui-state-default ui-corner-all ui-button-text-only sub upd submit-cancel",
click: function() { click: function() {
$(this).dialog("close"); $(this).dialog("close");
$(this).remove();
if (typeof settings.onDeny == "function") settings.onDeny(); if (typeof settings.onDeny == "function") settings.onDeny();
} }
}, },
@ -395,6 +417,7 @@ function confirmDialog(settings) {
"ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next", "ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok submit-next",
click: function() { click: function() {
$(this).dialog("close"); $(this).dialog("close");
$(this).remove();
if (typeof settings.onAccept == "function") settings.onAccept(); if (typeof settings.onAccept == "function") settings.onAccept();
} }
} }

View File

@ -0,0 +1,441 @@
/**
* IMPORTANT. Official plugin does not allow string ids
* This modificated one yes.
*/
!(function(e) {
var t = {};
function i(s) {
if (t[s]) return t[s].exports;
var n = (t[s] = { i: s, l: !1, exports: {} });
return e[s].call(n.exports, n, n.exports, i), (n.l = !0), n.exports;
}
(i.m = e),
(i.c = t),
(i.d = function(e, t, s) {
i.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: s });
}),
(i.r = function(e) {
"undefined" != typeof Symbol &&
Symbol.toStringTag &&
Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }),
Object.defineProperty(e, "__esModule", { value: !0 });
}),
(i.t = function(e, t) {
if ((1 & t && (e = i(e)), 8 & t)) return e;
if (4 & t && "object" == typeof e && e && e.__esModule) return e;
var s = Object.create(null);
if (
(i.r(s),
Object.defineProperty(s, "default", { enumerable: !0, value: e }),
2 & t && "string" != typeof e)
)
for (var n in e)
i.d(
s,
n,
function(t) {
return e[t];
}.bind(null, n)
);
return s;
}),
(i.n = function(e) {
var t =
e && e.__esModule
? function() {
return e.default;
}
: function() {
return e;
};
return i.d(t, "a", t), t;
}),
(i.o = function(e, t) {
return Object.prototype.hasOwnProperty.call(e, t);
}),
(i.p = ""),
i((i.s = 0));
})([
function(e, t, i) {
"use strict";
i.r(t);
i(1);
!(function(e, t) {
if (!e || !e.document) throw new Error("simTree need window");
!(function(e) {
var t,
i = e.document,
s = {
linkParent: !1,
response: {
name: "name",
id: "id",
pid: "pid",
checked: "checked",
open: "open",
disabled: "disabled"
}
},
n = function(e) {
throw new Error(e);
},
a = function(e, t) {
return e.replace(/\{\{(.+?)\}\}/g, function(e, i) {
return t[i] ? t[i] : "";
});
},
r = function e(t) {
if (
("undefined" == typeof $ && n("simTreeneed jquery"),
$.isPlainObject(t))
) {
if ((t.el || n("你没有传el"), !(this instanceof e)))
return new e(t);
(this.options = $.extend(!0, {}, s, t)), this.init();
}
},
d = [],
o = [];
(r.prototype = {
version: "0.0.2",
constructor: r,
on: function(e, t, i) {
var s, n;
return (
(this.handles[e] = this.handles[e] || []),
(s = this.handles[e].isTriggered),
(n = this.handles[e].args),
$.isFunction(t) &&
(!0 === i ? (this.handles[e] = [t]) : this.handles[e].push(t),
s && t.call(this, n)),
this
);
},
off: function(e) {
return (this.handles[e] = []), this;
},
trigger: function(e, t) {
var i, s;
for (
this.handles[e] = this.handles[e] || [],
i = 0,
s = this.handles[e].length,
this.handles[e].isTriggered = !0,
this.handles[e].args = t;
i < s;
i++
)
this.handles[e][i].call(this, t);
},
init: function() {
var e = this.options,
t = e.data;
(this.handles = {}),
(this.$el = $(e.el)),
(this.data = t),
this.event(),
this.render();
},
dataCallback: function() {
var e = arguments;
1 === e.length ? this.render(e[0]) : this.doRender(e[0], e[1]);
},
parse: function(e) {
var t = this.options,
i = t.response,
s = [],
n = {},
a = 0,
r = e.length,
d = i.id,
o = i.pid;
if (t.childNodeAsy) return e;
for (; a < r; a++) {
var h = e[a],
c = h[d];
if (h.children) return e;
c && (n[c] = h);
}
for (a = 0; a < r; a++) {
var h = e[a],
l = h[o],
u = n[l];
l && u ? (u.children || (u.children = [])).push(h) : s.push(h);
}
return s;
},
render: function(e) {
var e = e || this.data;
$.isFunction(e) && e({}, this.dataCallback.bind(this)),
$.isArray(e) && ((e = this.parse(e)), this.doRender(this.$el, e));
},
doRender: function(e, t, s) {
var n,
r,
h,
c,
l,
u = this,
f = this.options,
p = f.response,
m = t.length,
g = 0,
v = p.id,
k = p.name,
s = s || 1,
C =
'<i data-type="{{asy}}" class="sim-tree-spread {{spreadIcon}}"></i><a href="javascript:;"><i class="sim-tree-checkbox"></i>{{text}}</a>',
b = e === this.$el,
y = $(i.createElement("ul")),
w = f.childNodeAsy ? "asy" : "";
for (
f.check ||
(C = C.replace('<i class="sim-tree-checkbox"></i>', ""));
g < m;
g++
)
(n = t[g]),
(r = i.createElement("li")),
(c = !!n.children),
(l = n[p.disabled]),
(r.innerHTML = a(C, {
asy: w,
text: n[k],
spreadIcon: c ? "sim-icon-r" : "hidden"
})),
r.setAttribute("data-level", s),
r.setAttribute("data-id", n[v]),
l && r.setAttribute("class", "disabled"),
(h = $(r)).data("data", n),
y.append(h),
c && this.doRender(h, n.children, s + 1),
n[p.checked] && d.push(n[v]),
n[p.open] && o.push(n[v]);
m && e.append(y),
b
? (y.addClass("sim-tree"),
this.trigger("done", t),
$.each(o, function(e, t) {
u.expandNode(t);
}),
this.setSelected(d))
: f.childNodeAsy &&
(this.hideLoading(e.find(".sim-tree-spread")),
y.addClass("show"));
},
event: function() {
var e = this;
this.$el.off("click").on("click", function(t) {
var i = $(t.target);
return (
i.hasClass("sim-tree-spread") && e.spread.call(e, i),
i.hasClass("sim-tree-checkbox") && (i = i.parent()),
"a" === i[0].tagName.toLowerCase() && e.clickNode.call(e, i),
!1
);
}),
this.$el.on("selectstart", function() {
return !1;
}),
this.options.done && this.on("done", this.options.done),
this.options.onClick && this.on("click", this.options.onClick),
this.options.onChange && this.on("change", this.options.onChange),
this.options.onSearch && this.on("search", this.options.onSearch);
},
spread: function(e) {
e.hasClass("sim-icon-r")
? this.doSpread(e, !0)
: this.doSpread(e, !1);
},
showLoading: function(e) {
e.addClass("sim-loading");
},
hideLoading: function(e) {
e.removeClass("sim-loading");
},
doSpread: function(e, t) {
var i = e.parent(),
s = i.children("ul"),
n = i.data("data");
n.children &&
(t
? (e.removeClass("sim-icon-r").addClass("sim-icon-d"),
"asy" === e.data("type") &&
$.isFunction(this.data) &&
(this.showLoading(e),
this.data(i.data("data"), this.dataCallback.bind(this, i)),
e.data("type", "")),
s.addClass("show"))
: (e.removeClass("sim-icon-d").addClass("sim-icon-r"),
s.removeClass("show")));
},
clickNode: function(e) {
var i,
s,
n,
a = this,
r = e.parent(),
d = this.$el.find("li"),
o = d.length,
h = 0,
c = [],
l = !1;
if (!r.hasClass("disabled")) {
if (this.options.check)
for (
l = !0,
this.doCheck(e.find(".sim-tree-checkbox")),
this.options.linkParent &&
((s = r.children("ul")),
(n = s.find(".sim-tree-checkbox")),
$.each(n, function() {
a.doCheck($(this), r.data("checked"), !0);
}));
h < o;
h++
)
!0 === (i = d.eq(h).data()).checked && c.push(i.data);
else
t && t.css("font-weight", "normal"),
e.css("font-weight", "bold"),
(t = e),
(i = r.data("data")),
(c = [i]),
(l = !this.sels || !(this.sels[0] === i));
(this.sels = c),
this.trigger("click", c),
l && this.trigger("change", c);
}
},
doCheck: function(e, t, i) {
var s = e.closest("li"),
n = s.data();
void 0 === t && (t = !n.checked),
!0 === t
? e.removeClass("sim-tree-semi").addClass("checked")
: !1 === t
? e.removeClass("checked sim-tree-semi")
: "semi" === t &&
e.removeClass("checked").addClass("sim-tree-semi"),
s.data("checked", t),
!0 === this.options.linkParent && !i && this.setParentCheck(s);
},
setParentCheck: function(e) {
var t,
i = e.parent("ul"),
s = i.parent("li"),
n = i.children("li"),
a = s.find(">a .sim-tree-checkbox"),
r = [],
d = n.length;
s.length &&
(e.find(">a .sim-tree-checkbox").hasClass("sim-tree-semi")
? this.doCheck(a, "semi")
: ($.each(n, function() {
!0 === $(this).data("checked") && r.push($(this));
}),
(t = r.length),
d === t && this.doCheck(a, !0),
t || this.doCheck(a, !1),
t >= 1 && t < d && this.doCheck(a, "semi")));
},
search: function(e) {
if (this.$el) {
var t,
i,
s,
e = $.trim(e),
n = this.$el.find("li"),
a = 0,
r = n.length,
d = [],
o = new RegExp(e, "i");
for (
n
.hide()
.children(".sim-tree-spread")
.addClass("hidden");
a < r;
a++
)
(i = n.eq(a)),
(t = i.children("a").text()),
(s = i.data("data")),
e
? -1 !== t.search(o) &&
(1 !== parseInt(i.data("level")) &&
this.expandNode(s[this.options.response.pid]),
i
.parents("li")
.add(i)
.show(),
d.push(i))
: (i.show(),
s.children &&
i.children(".sim-tree-spread").removeClass("hidden"));
this.trigger("search", e);
}
},
expandNode: function(e) {
var t = e.addClass ? e : this.$el.find("[data-id='" + e + "']"),
i = t.data("data"),
s = i[this.options.response.pid],
n = t.children(".sim-tree-spread"),
a = parseInt(t.data("level"));
i.children &&
n.length &&
(n.removeClass("hidden"), this.doSpread(n, !0)),
1 !== a && this.expandNode(s);
},
setSelected: function(e) {
var t = this,
i = e,
s = [],
n = [];
("string" != typeof i && "number" != typeof i) || (i = [i]),
$.isArray(i) &&
(this.options.check || (i = [i[0]]),
$.each(i, function(e, i) {
var a = t.$el.find("[data-id='" + i + "']"),
r = a.children("a"),
d = r.children(".sim-tree-checkbox"),
o = a.data("data");
if (!a.length) return !0;
d.length ? t.doCheck(d, !0) : r.css("font-weight", "bold"),
1 !== parseInt(a.data("level")) &&
t.expandNode(o[t.options.response.pid]),
s.push(o),
n.push(a[0]);
}),
(t.sels = s),
t.trigger("click", s));
},
getSelected: function() {
return this.sels;
},
disableNode: function(e) {
var t = this,
i = e;
("string" != typeof i && "number" != typeof i) || (i = [i]),
$.isArray(i) &&
$.each(i, function(e, i) {
var s = t.$el.find("[data-id='" + i + "']");
s.addClass("disabled");
});
},
destroy: function() {
for (var e in (this.$el.html(""), this)) delete this[e];
},
refresh: function(e) {
this.$el.html(""), this.render(e);
}
}),
(e.simTree = r),
($.fn.simTree = function(e) {
return (e = $.extend(!0, { el: this }, e)), r(e);
});
})(e);
})("undefined" != typeof window ? window : void 0);
},
function(e, t, i) {}
]);

View File

@ -416,7 +416,12 @@ class EventsListWidget extends Widget
$filter['limit'] = $this->values['limit']; $filter['limit'] = $this->values['limit'];
$filter['order'] = '`utimestamp` DESC'; $filter['order'] = '`utimestamp` DESC';
if ((int) $this->values['severity'] !== -1) { if ((int) $this->values['severity'] === 20) {
$filter['criticity'] = [
EVENT_CRIT_WARNING,
EVENT_CRIT_CRITICAL,
];
} else if ((int) $this->values['severity'] !== -1) {
$filter['criticity'] = $this->values['severity']; $filter['criticity'] = $this->values['severity'];
} }

View File

@ -309,12 +309,6 @@ class GraphModuleHistogramWidget extends Widget
$size = parent::getSize(); $size = parent::getSize();
// Desactive scroll bars only this item. // Desactive scroll bars only this item.
$output .= '<style type="text/css">
.grid-stack-item .grid-stack-item-content .content-widget {
overflow-x: hidden;
overflow-y: hidden;
}
</style>';
$id_agent = $this->values['agentId']; $id_agent = $this->values['agentId'];
$id_module = $this->values['moduleId']; $id_module = $this->values['moduleId'];
$period = $this->values['period']; $period = $this->values['period'];

View File

@ -206,9 +206,9 @@ class MapsMadeByUser extends Widget
$fields = \visual_map_get_user_layouts($config['id_user'], true); $fields = \visual_map_get_user_layouts($config['id_user'], true);
// Event Type. // Visual console.
$inputs[] = [ $inputs[] = [
'label' => __('Event type'), 'label' => __('Visual console'),
'arguments' => [ 'arguments' => [
'type' => 'select', 'type' => 'select',
'fields' => $fields, 'fields' => $fields,

View File

@ -439,7 +439,7 @@ class SystemGroupStatusWidget extends Widget
} }
} }
$height = (count($result_groups) * 30); $height = (count($table->data) * 30);
$style = 'min-width:200px; min-height:'.$height.'px;'; $style = 'min-width:200px; min-height:'.$height.'px;';
$output = '<div class="container-center" style="'.$style.'">'; $output = '<div class="container-center" style="'.$style.'">';
if ($flag_groups === true) { if ($flag_groups === true) {

View File

@ -339,10 +339,8 @@ table.widget_maps_status tr td:first-child {
table.widget_maps_status tr td a { table.widget_maps_status tr td a {
font-family: "lato-lighter", "Open Sans", sans-serif; font-family: "lato-lighter", "Open Sans", sans-serif;
letter-spacing: 0.03pt; letter-spacing: 0.03pt;
font-size: 11pt; font-size: 9pt;
text-decoration: none; text-decoration: none;
color: #3f3f3f;
font-weight: bolder;
} }
table.widget_maps_status tr td img { table.widget_maps_status tr td img {

View File

@ -169,6 +169,7 @@ span.breadcrumb_link {
form.discovery * { form.discovery * {
font-size: 10pt; font-size: 10pt;
font-family: "lato", "Open Sans", sans-serif;
} }
form.discovery .label_select b { form.discovery .label_select b {

View File

@ -1,3 +1,14 @@
/* /*
* TODO: This may be at hostdevices.css * TODO: This may be at hostdevices.css
*/ */
select.select_multiple {
min-width: 500px;
width: 50%;
height: 250px;
}
.indented select.select_multiple {
min-width: calc(500px - 1em);
width: calc(50% - 1em);
}

View File

@ -0,0 +1,146 @@
/* surrounding tag container */
.tag-editor {
list-style-type: none;
padding: 0 5px 0 0;
margin: 0;
overflow: hidden;
border: 1px solid #eee;
cursor: text;
font: normal 14px sans-serif;
color: #555;
background: #fff;
line-height: 20px;
}
/* core styles usually need no change */
.tag-editor li {
display: block;
float: left;
overflow: hidden;
margin: 3px 0;
}
.tag-editor div {
float: left;
padding: 0 4px;
}
.tag-editor .placeholder {
padding: 0 8px;
color: #bbb;
}
.tag-editor .tag-editor-spacer {
padding: 0;
width: 8px;
overflow: hidden;
color: transparent;
background: none;
}
.tag-editor input {
vertical-align: inherit;
border: 0;
outline: none;
padding: 0;
margin: 0;
cursor: text;
font-family: inherit;
font-weight: inherit;
font-size: inherit;
font-style: inherit;
box-shadow: none;
background: none;
color: #444;
}
/* hide original input field or textarea visually to allow tab navigation */
.tag-editor-hidden-src {
position: absolute !important;
left: -99999px;
}
/* hide IE10 "clear field" X */
.tag-editor ::-ms-clear {
display: none;
}
/* tag style */
.tag-editor .tag-editor-tag {
padding-left: 5px;
color: #46799b;
background: #e0eaf1;
white-space: nowrap;
overflow: hidden;
cursor: pointer;
border-radius: 2px 0 0 2px;
}
/* delete icon */
.tag-editor .tag-editor-delete {
background: #e0eaf1;
cursor: pointer;
border-radius: 0 2px 2px 0;
padding-left: 3px;
padding-right: 4px;
}
.tag-editor .tag-editor-delete i {
line-height: 18px;
display: inline-block;
}
.tag-editor .tag-editor-delete i:before {
font-size: 16px;
color: #8ba7ba;
content: "×";
font-style: normal;
}
.tag-editor .tag-editor-delete:hover i:before {
color: #d65454;
}
.tag-editor .tag-editor-tag.active + .tag-editor-delete,
.tag-editor .tag-editor-tag.active + .tag-editor-delete i {
visibility: hidden;
cursor: text;
}
.tag-editor .tag-editor-tag.active {
background: none !important;
}
/* jQuery UI autocomplete - code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css */
.ui-autocomplete {
position: absolute;
top: 0;
left: 0;
cursor: default;
font-size: 14px;
}
.ui-front {
z-index: 9999;
}
.ui-menu {
list-style: none;
padding: 1px;
margin: 0;
display: block;
outline: none;
}
.ui-menu .ui-menu-item a {
text-decoration: none;
display: block;
padding: 2px 0.4em;
line-height: 1.4;
min-height: 0; /* support: IE7 */
}
.ui-widget-content {
border: 1px solid #bbb;
background: #fff;
color: #555;
}
.ui-widget-content a {
color: #46799b;
}
.ui-widget-content .ui-state-hover,
.ui-widget-header .ui-state-hover,
.ui-state-focus,
.ui-widget-content .ui-state-focus,
.ui-widget-header .ui-state-focus {
background: #e0eaf1;
}
.ui-helper-hidden-accessible {
display: none;
}

View File

@ -628,6 +628,9 @@ select:-internal-list-box {
.float-right { .float-right {
float: right; float: right;
} }
.invisible {
display: none;
}
div#page { div#page {
background: #fbfbfb; background: #fbfbfb;
@ -4081,103 +4084,11 @@ div#footer_help {
background-size: 120px 80px; background-size: 120px 80px;
} }
/*
* ---------------------------------------------------------------------
* - WUX VIEW -
* ---------------------------------------------------------------------
*/
#mssg_error_div { #mssg_error_div {
color: red; color: red;
font-size: 12px; font-size: 12px;
} }
.wux_global_result_container {
width: 100%;
margin-top: 30px;
margin-bottom: 30px;
}
.wux_global_result_title {
width: 100%;
text-align: center;
color: white;
background-color: #373737;
border: 1px solid #373737;
height: 28px;
}
.wux_global_result_title p {
margin: 8px;
}
.wux_global_result_content {
width: 100%;
border: 1px solid #e2e2e2;
height: 120px;
}
.wux_global_result_content_left {
float: left;
width: 40%;
text-align: center;
}
.wux_global_result_content_left ul {
display: inline-flex;
margin-top: 15px;
}
.wux_global_result_content_left ul li p {
margin-top: 35px;
margin-right: 10px;
margin-left: 10px;
}
.wux_global_result_content_left ul li p b {
font-size: 16px;
}
.wux_global_result_content_right {
float: right;
width: 60%;
}
.wux_global_result_content_right ul {
display: inline-flex;
margin-top: 15px;
margin-left: 100px;
}
.wux_global_result_content_right ul li p {
margin-top: 36px;
margin-right: 10px;
margin-left: 10px;
}
.wux_global_result_content_right ul li p b {
font-size: 16px;
}
.wux_transaction_container {
width: 100%;
margin-bottom: 30px;
}
.wux_result_transaction {
width: 33%;
float: left;
}
.wux_transaction_graphs {
width: 33%;
float: left;
}
.wux_transaction_graphs_pie {
width: 33%;
float: left;
}
.pagination_show_more { .pagination_show_more {
text-align: center; text-align: center;
margin-top: 10px; margin-top: 10px;
@ -5739,6 +5650,11 @@ div#status_pie {
.white_table_graph_header b { .white_table_graph_header b {
font-size: 10pt; font-size: 10pt;
font-weight: 600; font-weight: 600;
width: 100%;
}
.white_table_graph_header div.white_table_header_checkbox {
float: right;
} }
.white_table_graph_header div#bullets_modules { .white_table_graph_header div#bullets_modules {

View File

@ -0,0 +1,38 @@
ul.wizard li > label:not(.p-switch) {
width: auto;
}
form.top-action-buttons ul.wizard {
display: flex;
flex-direction: row;
}
ul.wizard li {
margin-right: 1em;
}
form.modal ul.wizard li {
display: flex;
flex-direction: row;
width: 90%;
margin: 0 auto;
justify-items: center;
}
form.modal ul.wizard li * {
flex: 1;
}
ul.wizard li.flex-indep {
flex: 1;
margin: 0;
}
div#div-form {
padding: 0 2em;
}
div#div-form textarea {
width: 100%;
margin-top: 1em;
}

View File

@ -0,0 +1,124 @@
.sim-tree {
list-style: none;
font-size: 14px;
color: #333;
}
.sim-tree ul,
.sim-tree li {
margin: 0;
padding: 0;
}
.sim-tree li {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
font-size: 0;
}
.sim-tree li ul {
display: none;
margin-left: 15px;
}
.sim-tree ul.show,
.sim-tree li.show {
display: block;
}
.sim-tree ul.none,
.sim-tree li.none {
display: none;
}
.sim-tree li.disabled > a {
color: #aaa;
cursor: not-allowed;
}
.sim-tree li.disabled > a .sim-tree-checkbox {
border-color: #eee;
}
.sim-tree a {
font-size: 14px;
color: #333;
text-decoration: none;
vertical-align: top;
line-height: 26px;
}
.sim-tree .sim-tree-spread {
width: 20px;
padding-left: 5px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.sim-tree .sim-tree-spread.hidden {
visibility: hidden;
}
.sim-tree .sim-tree-spread,
.sim-tree a {
display: inline-block;
height: 26px;
cursor: pointer;
}
.sim-tree .sim-loading {
background: url(data:image/gif;base64,R0lGODlhEAAQAMQQAObm5uLi4unp6dHR0cnJydfX1+jo6O/v7/Dw8NPT0/39/crKyvr6+uDg4MfHx////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAQACwAAAAAEAAQAAAFXeAjPkiTjGgaLI6Tvs9BtPAIMPH8KgK5DDhZSlFYlFrAGIrYMrUcyRGzdapZr6jE02FAyZ6JxrOrEAVnjgaCRS6IkjLjo9F2PaDBwLJAu+NfAix2LQsAMCVVYQgoIQAh+QQFAAAQACwJAAAABwAHAAAFFGDSIE/5OM7SmKhjsK55vjIt32UIACH5BAUAABAALAoAAwAGAAoAAAUaICQqgggpxYKcheM0qOskZm0/eA7luMibvRAAIfkEBQAAEAAsCQAJAAcABwAABRXgcxBOmTwi6TRouiAoIwbtI9d4/oQAIfkEBQAAEAAsAwAKAAoABgAABRsgJI7MKD6POJQnKjpD60IODKFzvQD3nDQISAgAIfkEBQAAEAAsAAAJAAcABwAABRPgI45kSSrFWTgj6rCisLwk0iQhACH5BAUAABAALAAAAwAHAAoAAAUcIPRAJPmco4mm61m+cJk4tGNATX0ryGK/jVspBAAh+QQFAAAQACwAAAAABwAHAAAFFOAjjmRpPgBDIsugio3juGIiz2oIADs=)
center center no-repeat;
}
.sim-tree .sim-loading.sim-icon-d:before,
.sim-tree .sim-loading.sim-icon-r:before {
display: none;
}
.sim-tree .sim-icon-d:before,
.sim-tree .sim-icon-r:before {
content: "";
display: inline-block;
width: 0;
height: 0;
border: 6px solid transparent;
vertical-align: top;
position: relative;
}
.sim-tree .sim-icon-r:before {
border-left-width: 8px;
border-left-color: #333;
top: 7px;
}
.sim-tree .sim-icon-d:before {
margin-left: -4px;
border-top-color: #333;
top: 10px;
}
.sim-tree .sim-tree-checkbox {
display: inline-block;
border: 1px solid #ccc;
height: 16px;
width: 16px;
border-radius: 3px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
text-align: center;
line-height: 16px;
background: #fff;
color: #fff;
vertical-align: middle;
margin-right: 6px;
margin-top: -2px;
}
.sim-tree .sim-tree-checkbox.sim-tree-semi,
.sim-tree .sim-tree-checkbox.checked {
border-color: #2b85e4;
background-color: #2b85e4;
}
.sim-tree .sim-tree-checkbox.sim-tree-semi {
position: relative;
}
.sim-tree .sim-tree-checkbox.sim-tree-semi:after {
content: "";
display: block;
position: absolute;
width: 8px;
height: 2px;
background: #fff;
top: 6px;
left: 3px;
}
.sim-tree .sim-tree-checkbox.checked {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAMAAABhq6zVAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAPFBMVEUAAAD///////////////////////////////////////////////////////////////////////8AAADY904BAAAAE3RSTlMAOiE8877cHQkXr9cZQvUc20NAbrhSVAAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAA7SURBVAjXY2DADhiZEGxmFlYkNhs7KpuDE0mci5sHoYaXj5sHyOaHqOblE4CzGRgE+RBsBgYhfmxuAABcBQF5T7U3IwAAAABJRU5ErkJggg==);
background-repeat: no-repeat;
background-position: center center;
}

View File

@ -36,7 +36,86 @@ ul.progress_task_discovery {
flex-direction: column; flex-direction: column;
} }
div.subtitle {
width: 100%;
margin-top: 40px;
text-align: center;
}
div.subtitle span {
font-size: 1.9em;
font-family: "lato-bolder", "Open Sans", sans-serif;
}
div.subtitle div.manage {
text-align: center;
padding-top: 2em;
padding-bottom: 1em;
}
div.subtitle div.manage button {
font-size: 1.2em;
font-family: "lato", "Open Sans", sans-serif;
display: inline-block;
margin-right: 1em;
cursor: pointer;
text-align: left;
border-radius: 21px;
box-shadow: 0 0 10px -5px #888;
padding: 0.5em 1em;
border: 1px solid #ddd;
user-select: none;
color: #424242;
}
div.subtitle .link.review {
margin: 15px 0 -30px;
display: block;
font-weight: bold;
}
#msg ul li {
margin-left: 3em;
}
li.added {
list-style: url("../../images/header_ready.png");
}
li.removed {
list-style: url("../../images/header_down.png");
}
#msg ul {
list-style: url("../../images/header_ready.png");
}
ul.progress_task_discovery li span { ul.progress_task_discovery li span {
font-size: 9pt; font-size: 9pt;
margin-left: 20px; margin-left: 20px;
} }
.ui-dialog.ui-widget-content {
cursor: initial;
}
span.link {
cursor: pointer;
}
span.link.review {
font-weight: bold;
}
#review {
padding-top: 2em;
padding-left: 6.7em;
}
#review .sim-tree li.disabled > a .sim-tree-checkbox {
border-color: #eee;
background-color: #ddd;
}
#task_review {
width: 100% !important;
}

View File

@ -2,7 +2,11 @@
* Discovery > Wizard css global style * Discovery > Wizard css global style
*/ */
#main > form.discovery.wizard > .white_box {
min-width: 1024px;
}
ul.wizard { ul.wizard {
list-style-type: none;
} }
ul.wizard li { ul.wizard li {
@ -23,6 +27,104 @@ ul.wizard li > textarea {
font-family: monospace; font-family: monospace;
} }
.hidden { .wizard .hidden {
display: none; display: none;
} }
.wizard .indented {
margin-left: 1em;
}
.wizard .std_input {
display: flex;
margin-bottom: 25px;
flex-wrap: wrap;
justify-content: space-between;
}
.std_input.hidden {
display: none;
}
.wizard .std_input > .label_select {
flex: 1 1 100%;
}
.wizard .std_input > * {
flex: 1 1 auto;
align-self: baseline;
}
.wizard .inline_input.no-margin {
margin-bottom: 0px;
}
.wizard .inline_input {
display: flex;
margin-bottom: 25px;
flex-wrap: wrap;
justify-content: space-between;
align-items: baseline;
}
.wizard .inline_input * {
flex: 1 1 auto;
}
.wizard .discovery_inline_input {
display: flex;
align-content: end;
flex: 0;
align-self: flex-start;
}
/* override tag-editor styles */
.wizard .tag-editor.ui-sortable {
width: 450px;
display: inline-block;
}
.wizard .tag-editor .tag-editor-tag {
padding: 5px;
color: #fff;
background: #82b92e;
}
.wizard .tag-editor .tag-editor-delete i {
line-height: inherit;
}
.wizard .tag-editor .tag-editor-delete i:before {
color: #ccc;
}
.wizard .tag-editor .tag-editor-delete:hover i:before {
color: #fff;
}
.wizard .tag-editor .tag-editor-delete {
padding: 5px;
background: #e63c52;
}
.wizard .time_selection_container {
display: flex;
align-items: baseline;
justify-items: center;
align-content: space-between;
margin-top: 1em;
}
.wizard #interval_manual_container #interval_manual > * {
flex: 1 1 auto;
}
.wizard-column-levels {
float: left;
width: 33%;
text-align: center;
}
.action_button_list {
height: 60px;
}
.action_button_list li {
display: inline;
}

View File

@ -1,10 +1 @@
/* /* Enterprise content */
* Wux style
*/
.wux_execution_result_transaction {
width: auto;
height: auto;
float: right;
margin-right: 200px;
}

View File

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

View File

@ -57,10 +57,10 @@ if ($new_networkmap) {
$offset_x = ''; $offset_x = '';
$offset_y = ''; $offset_y = '';
$scale_z = 0.5; $scale_z = 0.5;
$node_sep = 0.1; $node_sep = 10;
$rank_sep = 1.0; $rank_sep = 1.0;
$mindist = 1.0; $mindist = 1.0;
$kval = 0.1; $kval = 5;
} }
$disabled_generation_method_select = false; $disabled_generation_method_select = false;

View File

@ -1119,12 +1119,13 @@ if ($group_rep == 2) {
server_id, server_id,
response_command response_command
); );
response["server_id"] = server_id;
response["event_id"] = event_id;
if (total_checked-1 === counter) if (total_checked-1 === counter)
end=1; end=1;
show_massive_response_dialog( show_massive_response_dialog(
event_id,
response_id, response_id,
response, response,
counter, counter,

View File

@ -328,6 +328,8 @@ if (is_ajax()) {
$data = array_reduce( $data = array_reduce(
$events, $events,
function ($carry, $item) { function ($carry, $item) {
global $config;
$tmp = (object) $item; $tmp = (object) $item;
$tmp->meta = is_metaconsole(); $tmp->meta = is_metaconsole();
if (is_metaconsole()) { if (is_metaconsole()) {
@ -360,7 +362,10 @@ if (is_ajax()) {
true true
); );
$tmp->data = format_numeric($tmp->data, 1); $tmp->data = format_numeric(
$tmp->data,
$config['graph_precision']
);
$tmp->instructions = events_get_instructions($item); $tmp->instructions = events_get_instructions($item);
@ -1760,6 +1765,9 @@ function process_datatables_item(item) {
evn += '('+item.event_rep+') '; evn += '('+item.event_rep+') ';
} }
evn += item.evento+'</a>'; evn += item.evento+'</a>';
if(item.meta === true) {
evn += '<input id="hidden-server_id_'+item.id_evento+'" type="hidden" value="'+item.server_id+'">';
}
item.mini_severity = '<div class="event flex-row h100p nowrap">'; item.mini_severity = '<div class="event flex-row h100p nowrap">';
item.mini_severity += output; item.mini_severity += output;

View File

@ -127,17 +127,7 @@ if ($read_message) {
).' '.$user_name; ).' '.$user_name;
} }
$order = [ $parsed_message = nl2br(htmlspecialchars(trim(io_safe_output($row['message']))));
"\r\n",
"\n",
"\r",
];
$replace = '<br />';
$parsed_message = str_replace(
$order,
$replace,
trim(io_safe_output($row['message']))
);
echo '<div class="container">'; echo '<div class="container">';
echo ' <p>'.$parsed_message.'</p>'; echo ' <p>'.$parsed_message.'</p>';

View File

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

View File

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

View File

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

View File

@ -234,7 +234,7 @@ CREATE TABLE IF NOT EXISTS `tagente_modulo` (
`delete_pending` int(1) unsigned default 0, `delete_pending` int(1) unsigned default 0,
`policy_linked` tinyint(1) unsigned not null default 0, `policy_linked` tinyint(1) unsigned not null default 0,
`policy_adopted` tinyint(1) unsigned not null default 0, `policy_adopted` tinyint(1) unsigned not null default 0,
`custom_string_1` text, `custom_string_1` mediumtext,
`custom_string_2` text, `custom_string_2` text,
`custom_string_3` text, `custom_string_3` text,
`custom_integer_1` int(10) default 0, `custom_integer_1` int(10) default 0,
@ -773,14 +773,14 @@ CREATE TABLE IF NOT EXISTS `trecon_task` (
`name` varchar(100) NOT NULL default '', `name` varchar(100) NOT NULL default '',
`description` varchar(250) NOT NULL default '', `description` varchar(250) NOT NULL default '',
`subnet` text NOT NULL, `subnet` text NOT NULL,
`id_network_profile` int(10) unsigned NOT NULL default '0', `id_network_profile` text,
`create_incident` tinyint(3) unsigned NOT NULL default '0', `review_mode` tinyint(1) unsigned NOT NULL default 1,
`id_group` int(10) unsigned NOT NULL default '1', `id_group` int(10) unsigned NOT NULL default 1,
`utimestamp` bigint(20) unsigned NOT NULL default '0', `utimestamp` bigint(20) unsigned NOT NULL default 0,
`status` tinyint(4) NOT NULL default '0', `status` tinyint(4) NOT NULL default 0,
`interval_sweep` int(10) unsigned NOT NULL default '0', `interval_sweep` int(10) unsigned NOT NULL default 0,
`id_recon_server` int(10) unsigned NOT NULL default '0', `id_recon_server` int(10) unsigned NOT NULL default 0,
`id_os` tinyint(4) NOT NULL default '0', `id_os` tinyint(4) NOT NULL default 0,
`recon_ports` varchar(250) NOT NULL default '', `recon_ports` varchar(250) NOT NULL default '',
`snmp_community` varchar(64) NOT NULL default 'public', `snmp_community` varchar(64) NOT NULL default 'public',
`id_recon_script` int(10), `id_recon_script` int(10),
@ -788,31 +788,59 @@ CREATE TABLE IF NOT EXISTS `trecon_task` (
`field2` varchar(250) NOT NULL default '', `field2` varchar(250) NOT NULL default '',
`field3` varchar(250) NOT NULL default '', `field3` varchar(250) NOT NULL default '',
`field4` varchar(250) NOT NULL default '', `field4` varchar(250) NOT NULL default '',
`os_detect` tinyint(1) unsigned default '0', `os_detect` tinyint(1) unsigned default 0,
`resolve_names` tinyint(1) unsigned default '0', `resolve_names` tinyint(1) unsigned default 0,
`parent_detection` tinyint(1) unsigned default '0', `parent_detection` tinyint(1) unsigned default 0,
`parent_recursion` tinyint(1) unsigned default '0', `parent_recursion` tinyint(1) unsigned default 0,
`disabled` tinyint(1) unsigned NOT NULL DEFAULT '0', `disabled` tinyint(1) unsigned NOT NULL DEFAULT 0,
`macros` TEXT, `macros` TEXT,
`alias_as_name` tinyint(2) NOT NULL default '0', `alias_as_name` tinyint(2) NOT NULL default 0,
`snmp_enabled` tinyint(1) unsigned default '0', `snmp_enabled` tinyint(1) unsigned default 0,
`vlan_enabled` tinyint(1) unsigned default '0', `vlan_enabled` tinyint(1) unsigned default 0,
`snmp_version` varchar(5) NOT NULL default '1', `snmp_version` varchar(5) NOT NULL default 1,
`snmp_auth_user` varchar(255) NOT NULL default '', `snmp_auth_user` varchar(255) NOT NULL default '',
`snmp_auth_pass` varchar(255) NOT NULL default '', `snmp_auth_pass` varchar(255) NOT NULL default '',
`snmp_auth_method` varchar(25) NOT NULL default '', `snmp_auth_method` varchar(25) NOT NULL default '',
`snmp_privacy_method` varchar(25) NOT NULL default '', `snmp_privacy_method` varchar(25) NOT NULL default '',
`snmp_privacy_pass` varchar(255) NOT NULL default '', `snmp_privacy_pass` varchar(255) NOT NULL default '',
`snmp_security_level` varchar(25) NOT NULL default '', `snmp_security_level` varchar(25) NOT NULL default '',
`wmi_enabled` tinyint(1) unsigned DEFAULT '0', `wmi_enabled` tinyint(1) unsigned DEFAULT 0,
`auth_strings` text, `auth_strings` text,
`autoconfiguration_enabled` tinyint(1) unsigned default '0', `auto_monitor` TINYINT(1) UNSIGNED DEFAULT 1,
`autoconfiguration_enabled` tinyint(1) unsigned default 0,
`summary` text, `summary` text,
`type` int NOT NULL default 0, `type` int NOT NULL default 0,
`subnet_csv` TINYINT(1) UNSIGNED DEFAULT 0,
PRIMARY KEY (`id_rt`), PRIMARY KEY (`id_rt`),
KEY `recon_task_daemon` (`id_recon_server`) KEY `recon_task_daemon` (`id_recon_server`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tdiscovery_tmp`
-- ----------------------------------------------------------------------
CREATE TABLE `tdiscovery_tmp_agents` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`label` varchar(600) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`data` MEDIUMTEXT,
`review_date` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_rt` (`id_rt`),
INDEX `label` (`label`),
CONSTRAINT `tdta_trt` FOREIGN KEY (`id_rt`) REFERENCES `trecon_task` (`id_rt`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `tdiscovery_tmp_connections` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_rt` int(10) unsigned NOT NULL,
`dev_1` text,
`dev_2` text,
`if_1` text,
`if_2` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
-- Table `tmodule_relationship` -- Table `tmodule_relationship`
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
@ -926,6 +954,28 @@ CREATE TABLE IF NOT EXISTS `tnetwork_profile_component` (
KEY `id_np` (`id_np`) KEY `id_np` (`id_np`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tpen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tpen` (
`pen` int(10) unsigned NOT NULL,
`manufacturer` TEXT,
`description` TEXT,
PRIMARY KEY (`pen`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- Table `tnetwork_profile_pen`
-- ----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tnetwork_profile_pen` (
`pen` int(10) unsigned NOT NULL,
`id_np` int(10) unsigned NOT NULL,
CONSTRAINT `fk_network_profile_pen_pen` FOREIGN KEY (`pen`)
REFERENCES `tpen` (`pen`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_network_profile_pen_id_np` FOREIGN KEY (`id_np`)
REFERENCES `tnetwork_profile` (`id_np`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
-- Table `tnota` -- Table `tnota`
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------

View File

@ -1594,3 +1594,123 @@ VALUES
(254,6,848,943,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0), (254,6,848,943,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0),
(255,5,846,941,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0) (255,5,846,941,0,0,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','time','Europe/Madrid',0,0)
; ;
--
-- Dumping data for table `tpen`
--
INSERT INTO `tpen`
VALUES
(9,'cisco','Cisco&#x20;System'),
(11,'hp','Hewlett&#x20;Packard'),
(2021,'general_snmp','U.C.&#x20;Davis,&#x20;ECE&#x20;Dept.&#x20;Tom'),
(2636,'juniper','Juniper&#x20;Networks'),
(3375,'f5','F5&#x20;Labs'),
(8072,'general_snmp','Net&#x20;SNMP'),
(12356,'fortinet','Fortinet')
;
--
-- Dumping data for table `tnetwork_profile` and `tnetwork_profile_pen`
--
SET @template_name = 'Network&#x20;Management';
SET @template_description = 'Basic network monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Network Management')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Cisco&#x20;MIBS';
SET @template_description = 'Cisco devices monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Cisco MIBS' OR g.name = 'Catalyst 2900')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 9)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Linux&#x20;System';
SET @template_description = 'Linux system monitoring template (SNMP)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
SET @module_group = 'Linux';
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Linux' OR g.name = 'UCD Mibs (Linux, UCD-SNMP)')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
INSERT INTO tnetwork_profile_pen (pen, id_np) SELECT * FROM (SELECT p.pen pen, np.id_np id_np FROM tnetwork_profile np, tpen p WHERE np.name = @template_name AND (p.pen = 2021 OR p.pen = 2636)) AS tmp WHERE NOT EXISTS (SELECT pp.id_np FROM tnetwork_profile p, tnetwork_profile_pen pp WHERE p.id_np = pp.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;System';
SET @template_description = 'Windows system monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Microsoft&#x20;Windows' OR g.name = 'Windows System')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Hardware';
SET @template_description = 'Windows hardware monitoring templae (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Hardware Layer')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Active&#x20;Directory';
SET @template_description = 'Active directory monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows AD' OR g.name = 'AD&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;IIS';
SET @template_description = 'IIS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows IIS' OR g.name = 'IIS&#x20;services')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Exchange';
SET @template_description = 'Exchange monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Exchange' OR g.name = 'Exchange&#x20;Services' OR g.name = 'Exchange&#x20;TCP&#x20;Ports')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;LDAP';
SET @template_description = 'LDAP monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows LDAP')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MDSTC';
SET @template_description = 'MDSTC monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows MSDTC')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Printers';
SET @template_description = 'Windows printers monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows Printers')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;DNS';
SET @template_description = 'Windows DNS monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Windows&#x20;DNS' OR g.name = 'DNS&#x20;Counters')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;MS&#x20;SQL&#x20;Server';
SET @template_description = 'MS SQL Server monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MS&#x20;SQL&#x20;Server')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Oracle';
SET @template_description = 'Oracle monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Oracle')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'MySQL';
SET @template_description = 'MySQL monitoring template';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'MySQL')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);
SET @template_name = 'Windows&#x20;Antivirus';
SET @template_description = 'Windows antivirus monitoring template (WMI)';
INSERT INTO tnetwork_profile (id_np, name, description) SELECT * FROM (SELECT '' id_np, @template_name name, @template_description description) AS tmp WHERE NOT EXISTS (SELECT id_np FROM tnetwork_profile WHERE name = @template_name);
INSERT INTO tnetwork_profile_component (id_nc, id_np) SELECT * FROM (SELECT c.id_nc id_nc, p.id_np id_np FROM tnetwork_profile p, tnetwork_component c, tnetwork_component_group g WHERE g.id_sg = c.id_group AND p.name = @template_name AND (g.name = 'Norton' OR g.name = 'Panda' OR g.name = 'McAfee' OR g.name = 'Bitdefender' OR g.name = 'BullGuard' OR g.name = 'AVG' OR g.name = 'Kaspersky')) AS tmp WHERE NOT EXISTS (SELECT pc.id_np FROM tnetwork_profile p, tnetwork_profile_component pc WHERE p.id_np = pc.id_np AND p.name = @template_name);

View File

@ -1,5 +1,5 @@
package: pandorafms-server package: pandorafms-server
Version: 7.0NG.744-200413 Version: 7.0NG.744-200420
Architecture: all Architecture: all
Priority: optional Priority: optional
Section: admin Section: admin

View File

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

View File

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

View File

@ -270,6 +270,8 @@ our @EXPORT = qw(
pandora_delete_custom_graph pandora_delete_custom_graph
pandora_edit_custom_graph pandora_edit_custom_graph
notification_set_targets notification_set_targets
notification_get_users
notification_get_groups
); );
# Some global variables # Some global variables
@ -929,10 +931,12 @@ sub pandora_execute_alert ($$$$$$$$$;$$) {
$pa_config, $pa_config,
"$text (" . safe_output($alert->{'name'}) . ") " . (defined ($module) ? 'assigned to ('. safe_output($module->{'nombre'}) . ")" : ""), "$text (" . safe_output($alert->{'name'}) . ") " . (defined ($module) ? 'assigned to ('. safe_output($module->{'nombre'}) . ")" : ""),
(defined ($agent) ? $agent->{'id_grupo'} : 0), (defined ($agent) ? $agent->{'id_grupo'} : 0),
(defined ($agent) ? $agent->{'id_agente'} : 0), # id agent.
0,
$severity, $severity,
(defined ($alert->{'id_template_module'}) ? $alert->{'id_template_module'} : 0), (defined ($alert->{'id_template_module'}) ? $alert->{'id_template_module'} : 0),
(defined ($alert->{'id_agent_module'}) ? $alert->{'id_agent_module'} : 0), # id agent module.
0,
$event, $event,
0, 0,
$dbh, $dbh,
@ -1647,6 +1651,17 @@ sub pandora_process_module ($$$$$$$$$;$) {
(defined ($agent) && $agent ne '' ? "'" . safe_output($agent->{'nombre'}) . "'" : 'ID ' . $module->{'id_agente'}) . ".", (defined ($agent) && $agent ne '' ? "'" . safe_output($agent->{'nombre'}) . "'" : 'ID ' . $module->{'id_agente'}) . ".",
10); 10);
# Ensure default values.
$module->{'min_ff_event'} = 0 unless defined($module->{'min_ff_event'});
$module->{'ff_timeout'} = 0 unless defined($module->{'ff_timeout'});
$module->{'module_interval'} = 0 unless defined($module->{'module_interval'});
if (ref($agent) eq 'HASH') {
if (!defined($agent->{'interval'}) && defined($agent->{'interval'})) {
$agent->{'intervalo'} = $agent->{'interval'};
}
}
# Get agent information # Get agent information
if (! defined ($agent) || $agent eq '') { if (! defined ($agent) || $agent eq '') {
$agent = get_db_single_row ($dbh, 'SELECT * FROM tagente WHERE id_agente = ?', $module->{'id_agente'}); $agent = get_db_single_row ($dbh, 'SELECT * FROM tagente WHERE id_agente = ?', $module->{'id_agente'});
@ -1761,6 +1776,11 @@ sub pandora_process_module ($$$$$$$$$;$) {
$min_ff_event = $module->{'min_ff_event_warning'} if ($new_status == 2); $min_ff_event = $module->{'min_ff_event_warning'} if ($new_status == 2);
} }
# Avoid warning if not initialized.
$min_ff_event = 0 unless defined($min_ff_event);
$module->{'ff_type'} = 0 unless defined($module->{'ff_type'});
$module->{'module_ff_interval'} = 0 unless defined($module->{'module_ff_interval'});
if ($last_known_status == $new_status) { if ($last_known_status == $new_status) {
# Avoid overflows # Avoid overflows
$status_changes = $min_ff_event if ($status_changes > $min_ff_event && $module->{'ff_type'} == 0); $status_changes = $min_ff_event if ($status_changes > $min_ff_event && $module->{'ff_type'} == 0);
@ -3129,6 +3149,8 @@ sub pandora_create_module_from_network_component ($$$$) {
pandora_create_module_tags ($pa_config, $dbh, $module_id, $component_tags); pandora_create_module_tags ($pa_config, $dbh, $module_id, $component_tags);
logger($pa_config, 'Creating module ' . safe_output ($component->{'nombre'}) . " (ID $module_id) for agent $addr from network component.", 10); logger($pa_config, 'Creating module ' . safe_output ($component->{'nombre'}) . " (ID $module_id) for agent $addr from network component.", 10);
return $module_id;
} }
########################################################################## ##########################################################################
@ -3167,8 +3189,12 @@ sub pandora_create_module_from_hash ($$$) {
} }
# Encrypt SNMP v3 passwords. # Encrypt SNMP v3 passwords.
if ($parameters->{'id_tipo_modulo'} >= 15 && $parameters->{'id_tipo_modulo'} <= 18 && if (defined($parameters->{'tcp_send'})
$parameters->{'tcp_send'} eq '3') { && $parameters->{'tcp_send'} eq '3'
&& defined($parameters->{'id_tipo_modulo'})
&& $parameters->{'id_tipo_modulo'} >= 15
&& $parameters->{'id_tipo_modulo'} <= 18
) {
$parameters->{'custom_string_2'} = pandora_input_password($pa_config, $parameters->{'custom_string_2'}); $parameters->{'custom_string_2'} = pandora_input_password($pa_config, $parameters->{'custom_string_2'});
} }
@ -3176,7 +3202,11 @@ sub pandora_create_module_from_hash ($$$) {
'tagente_modulo', $parameters); 'tagente_modulo', $parameters);
my $status = 4; my $status = 4;
if (defined ($parameters->{'id_tipo_modulo'}) && ($parameters->{'id_tipo_modulo'} == 21 || $parameters->{'id_tipo_modulo'} == 22 || $parameters->{'id_tipo_modulo'} == 23)) { if (defined ($parameters->{'id_tipo_modulo'})
&& ($parameters->{'id_tipo_modulo'} == 21
|| $parameters->{'id_tipo_modulo'} == 22
|| $parameters->{'id_tipo_modulo'} == 23)
) {
$status = 0; $status = 0;
} }
@ -3328,7 +3358,7 @@ sub pandora_create_agent ($$$$$$$$$$;$$$$$$$$$$) {
$agent_mode = 1 unless defined($agent_mode); $agent_mode = 1 unless defined($agent_mode);
$alias = $agent_name unless defined($alias); $alias = $agent_name unless defined($alias);
$description = "Created by $server_name" unless ($description ne ''); $description = "Created by $server_name" unless (defined($description) && $description ne '');
my ($columns, $values) = db_insert_get_values ({ 'nombre' => safe_input($agent_name), my ($columns, $values) = db_insert_get_values ({ 'nombre' => safe_input($agent_name),
'direccion' => $address, 'direccion' => $address,
'comentarios' => $description, 'comentarios' => $description,
@ -4178,7 +4208,9 @@ sub on_demand_macro($$$$$$;$) {
my $unit_mod = get_db_value ($dbh, 'SELECT unit FROM tagente_modulo WHERE id_agente_modulo = ?', $id_mod); my $unit_mod = get_db_value ($dbh, 'SELECT unit FROM tagente_modulo WHERE id_agente_modulo = ?', $id_mod);
my $field_value = ""; my $field_value = "";
if ($type_mod eq 3 || $type_mod eq 23|| $type_mod eq 17 || $type_mod eq 10 || $type_mod eq 33 ){ if (defined($type_mod)
&& ($type_mod eq 3 || $type_mod eq 23|| $type_mod eq 17 || $type_mod eq 10 || $type_mod eq 33 )
) {
$field_value = get_db_value($dbh, 'SELECT datos FROM tagente_datos_string where id_agente_modulo = ? order by utimestamp desc limit 1', $id_mod); $field_value = get_db_value($dbh, 'SELECT datos FROM tagente_datos_string where id_agente_modulo = ? order by utimestamp desc limit 1', $id_mod);
} }
else{ else{
@ -4241,7 +4273,9 @@ sub process_data ($$$$$$$) {
# Not a number # Not a number
if (! is_numeric ($data)) { if (! is_numeric ($data)) {
logger($pa_config, "Received invalid data '" . $data_object->{'data'} . "' from agent '" . $agent->{'nombre'} . "' module '" . $module->{'nombre'} . "' agent " . (defined ($agent) ? "'" . $agent->{'nombre'} . "'" : 'ID ' . $module->{'id_agente'}) . ".", 3); my $d = $data_object->{'data'};
$d = '' unless defined ($data_object->{'data'});
logger($pa_config, "Received invalid data '" . $d . "' from agent '" . $agent->{'nombre'} . "' module '" . $module->{'nombre'} . "' agent " . (defined ($agent) ? "'" . $agent->{'nombre'} . "'" : 'ID ' . $module->{'id_agente'}) . ".", 3);
return undef; return undef;
} }
@ -6288,6 +6322,63 @@ sub notification_set_targets {
return 1; return 1;
} }
##########################################################################
=head2 C<< notification_get_users (I<$dbh>, I<$source>) >>
Get targets for given sources
=cut
##########################################################################
sub notification_get_users {
my ($dbh, $source) = @_;
my @results = get_db_rows(
$dbh,
'SELECT id_user
FROM tnotification_source_user nsu
INNER JOIN tnotification_source ns ON nsu.id_source=ns.id
WHERE ns.description = ?
',
safe_input($source)
);
@results = map {
if(ref($_) eq 'HASH') { $_->{'id_user'} }
else {}
} @results;
return @results;
}
##########################################################################
=head2 C<< notification_get_groups (I<$dbh>, I<$source>) >>
Get targets for given sources
=cut
##########################################################################
sub notification_get_groups {
my ($dbh, $source) = @_;
my @results = get_db_rows(
$dbh,
'SELECT id_group
FROM tnotification_source_group nsg
INNER JOIN tnotification_source ns ON nsg.id_source=ns.id
WHERE ns.description = ?
',
safe_input($source)
);
@results = map {
if(ref($_) eq 'HASH') { $_->{'id_group'} }
else {}
} @results;
return @results;
}
# End of function declaration # End of function declaration
# End of defined Code # End of defined Code

View File

@ -20,6 +20,7 @@ package PandoraFMS::DB;
use strict; use strict;
use warnings; use warnings;
use DBI; use DBI;
use Carp qw/croak/;
use lib '/usr/lib/perl5'; use lib '/usr/lib/perl5';
use PandoraFMS::Tools; use PandoraFMS::Tools;
@ -80,6 +81,8 @@ our @EXPORT = qw(
get_module_id get_module_id
get_module_name get_module_name
get_nc_profile_name get_nc_profile_name
get_pen_templates
get_nc_profile_advanced
get_os_id get_os_id
get_os_name get_os_name
get_plugin_id get_plugin_id
@ -656,6 +659,48 @@ sub get_nc_profile_name ($$) {
return get_db_value ($dbh, "SELECT * FROM tnetwork_profile WHERE id_np = ?", $nc_id); return get_db_value ($dbh, "SELECT * FROM tnetwork_profile WHERE id_np = ?", $nc_id);
} }
##########################################################################
## Return all network component's profile ids matching given PEN.
##########################################################################
sub get_pen_templates($$) {
my ($dbh, $pen) = @_;
my @results = get_db_rows(
$dbh,
'SELECT t.`id_np`
FROM `tnetwork_profile` t
INNER JOIN `tnetwork_profile_pen` pp ON pp.`id_np` = t.`id_np`
INNER JOIN `tpen` p ON pp.pen = p.pen
WHERE p.`pen` = ?',
$pen
);
@results = map {
if (ref($_) eq 'HASH') { $_->{'id_np'} }
else {}
} @results;
return @results;
}
##########################################################################
## Return a network component's profile data and pen list, given its ID.
##########################################################################
sub get_nc_profile_advanced($$) {
my ($dbh, $id_nc) = @_;
return get_db_single_row(
$dbh,
'SELECT t.*,GROUP_CONCAT(p.pen) AS "pen"
FROM `tnetwork_profile` t
LEFT JOIN `tnetwork_profile_pen` pp ON t.id_np = pp.id_np
LEFT JOIN `tpen` p ON pp.pen = p.pen
WHERE t.`id_np` = ?
GROUP BY t.`id_np`',
$id_nc
);
}
########################################################################## ##########################################################################
## Return user profile ID given the user id, group id and profile id. ## Return user profile ID given the user id, group id and profile id.
########################################################################## ##########################################################################
@ -894,7 +939,7 @@ sub db_insert ($$$;@) {
$insert_id = $dbh->{'mysql_insertid'}; $insert_id = $dbh->{'mysql_insertid'};
} }
else { else {
die($exception); croak (join(', ', @_));
} }
} }
@ -917,7 +962,7 @@ sub db_update ($$;@) {
$rows = $dbh->do($query, undef, @values); $rows = $dbh->do($query, undef, @values);
} }
else { else {
die($exception); croak (join(', ', @_));
} }
} }
@ -1163,7 +1208,7 @@ sub db_do ($$;@) {
$dbh->do($query, undef, @values); $dbh->do($query, undef, @values);
} }
else { else {
die($exception); croak (join(', ', @_));
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -384,6 +384,7 @@ sub pandora_query_snmp ($$$$) {
my $output; # Command output my $output; # Command output
# If not defined, always snmp v1 (standard) # If not defined, always snmp v1 (standard)
$snmp_version = '1' unless defined($snmp_version);
if ($snmp_version ne '1' && $snmp_version ne '2' if ($snmp_version ne '1' && $snmp_version ne '2'
&& $snmp_version ne '2c' && $snmp_version ne '3') { && $snmp_version ne '2c' && $snmp_version ne '3') {
$snmp_version = '1'; $snmp_version = '1';
@ -470,7 +471,9 @@ sub exec_network_module ($$$$) {
my $retries = $module->{'max_retries'}; my $retries = $module->{'max_retries'};
my $target_os = pandora_get_os($dbh, $module->{'custom_string_2'}); my $target_os = pandora_get_os($dbh, $module->{'custom_string_2'});
if ($module->{'custom_string_2'} eq "inherited" ) { if (defined($module->{'custom_string_2'})
&& $module->{'custom_string_2'} eq "inherited"
) {
$target_os = $agent_row->{'id_os'}; $target_os = $agent_row->{'id_os'};
} elsif (!defined($target_os) || "$target_os" eq '0') { } elsif (!defined($target_os) || "$target_os" eq '0') {
$target_os = $agent_row->{'id_os'}; $target_os = $agent_row->{'id_os'};
@ -589,7 +592,7 @@ sub exec_network_module ($$$$) {
my %data = ("data" => $module_data); my %data = ("data" => $module_data);
pandora_process_module ($pa_config, \%data, '', $module, '', $timestamp, $utimestamp, $server_id, $dbh); pandora_process_module ($pa_config, \%data, '', $module, '', $timestamp, $utimestamp, $server_id, $dbh);
if ($agent_os_version eq ''){ if (!defined($agent_os_version) || $agent_os_version eq ''){
$agent_os_version = $pa_config->{'servername'}.'_Net'; $agent_os_version = $pa_config->{'servername'}.'_Net';
} }

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -23,9 +23,9 @@ our @EXPORT = qw(
subnet_matches subnet_matches
); );
######################################################################################## ################################################################################
# Return an Enterprise Recon object. # Return an Enterprise Recon object.
######################################################################################## ################################################################################
sub enterprise_new($$) { sub enterprise_new($$) {
my ($class, $arguments) = @_; my ($class, $arguments) = @_;
@ -53,18 +53,18 @@ sub enterprise_new($$) {
} }
######################################################################################## ################################################################################
# Return the numeric representation of the given IP address. # Return the numeric representation of the given IP address.
######################################################################################## ################################################################################
sub ip_to_long($) { sub ip_to_long($) {
my $ip_address = shift; my $ip_address = shift;
return unpack('N', inet_aton($ip_address)); return unpack('N', inet_aton($ip_address));
} }
######################################################################################## ################################################################################
# Returns 1 if the two given MAC addresses are the same. # Returns 1 if the two given MAC addresses are the same.
######################################################################################## ################################################################################
sub mac_matches($$) { sub mac_matches($$) {
my ($mac_1, $mac_2) = @_; my ($mac_1, $mac_2) = @_;
@ -75,9 +75,9 @@ sub mac_matches($$) {
return 0; return 0;
} }
######################################################################################## ################################################################################
# Convert a MAC address to decimal dotted notation. # Convert a MAC address to decimal dotted notation.
######################################################################################## ################################################################################
sub mac_to_dec($) { sub mac_to_dec($) {
my $mac = shift; my $mac = shift;
@ -91,9 +91,9 @@ sub mac_to_dec($) {
return $dec_mac; return $dec_mac;
} }
######################################################################################## ################################################################################
# Make sure all MAC addresses are in the same format (00 11 22 33 44 55 66). # Make sure all MAC addresses are in the same format (00 11 22 33 44 55 66).
######################################################################################## ################################################################################
sub parse_mac($) { sub parse_mac($) {
my ($mac) = @_; my ($mac) = @_;
@ -114,9 +114,9 @@ sub parse_mac($) {
return $mac; return $mac;
} }
######################################################################################## ################################################################################
# Returns 1 if the given IP address belongs to the given subnet. # Returns 1 if the given IP address belongs to the given subnet.
######################################################################################## ################################################################################
sub subnet_matches($$;$) { sub subnet_matches($$;$) {
my ($ipaddr, $subnet, $mask) = @_; my ($ipaddr, $subnet, $mask) = @_;
my ($netaddr, $netmask); my ($netaddr, $netmask);

View File

@ -1,8 +1,8 @@
package PandoraFMS::Tools; package PandoraFMS::Tools;
######################################################################## ################################################################################
# Tools Package # Tools Package
# Pandora FMS. the Flexible Monitoring System. http://www.pandorafms.org # Pandora FMS. the Flexible Monitoring System. http://www.pandorafms.org
######################################################################## ################################################################################
# Copyright (c) 2005-2011 Artica Soluciones Tecnologicas S.L # Copyright (c) 2005-2011 Artica Soluciones Tecnologicas S.L
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
@ -15,7 +15,7 @@ package PandoraFMS::Tools;
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
########################################################################## ################################################################################
use warnings; use warnings;
use Time::Local; use Time::Local;
@ -109,8 +109,11 @@ our @EXPORT = qw(
float_equal float_equal
sqlWrap sqlWrap
is_numeric is_numeric
is_enabled
is_metaconsole is_metaconsole
is_offline is_offline
is_empty
is_in_array
to_number to_number
clean_blank clean_blank
credential_store_get_key credential_store_get_key
@ -128,6 +131,7 @@ our @EXPORT = qw(
pandora_ping pandora_ping
pandora_ping_latency pandora_ping_latency
pandora_block_ping pandora_block_ping
ping
resolve_hostname resolve_hostname
ticks_totime ticks_totime
safe_input safe_input
@ -147,6 +151,7 @@ our @EXPORT = qw(
get_enabled_servers get_enabled_servers
dateTimeToTimestamp dateTimeToTimestamp
get_user_agent get_user_agent
ui_get_full_url
); );
# ID of the different servers # ID of the different servers
@ -361,9 +366,9 @@ my @ServerThreads;
# Keep threads running. # Keep threads running.
our $THRRUN :shared = 1; our $THRRUN :shared = 1;
########################################################################## ################################################################################
## Reads a file and returns entire content or undef if error. ## Reads a file and returns entire content or undef if error.
########################################################################## ################################################################################
sub read_file { sub read_file {
my $path = shift; my $path = shift;
@ -383,9 +388,9 @@ sub read_file {
} }
############################################################################### ################################################################################
# Sets user:group owner for the given file # Sets user:group owner for the given file
############################################################################### ################################################################################
sub set_file_permissions($$;$) { sub set_file_permissions($$;$) {
my ($pa_config, $file, $grants) = @_; my ($pa_config, $file, $grants) = @_;
if ($^O !~ /win/i ) { # Only for Linux environments if ($^O !~ /win/i ) { # Only for Linux environments
@ -410,10 +415,10 @@ sub set_file_permissions($$;$) {
} }
######################################################################## ################################################################################
## SUB pandora_trash_ascii ## SUB pandora_trash_ascii
# Generate random ascii strings with variable lenght # Generate random ascii strings with variable lenght
######################################################################## ################################################################################
sub pandora_trash_ascii { sub pandora_trash_ascii {
my $config_depth = $_[0]; my $config_depth = $_[0];
@ -426,9 +431,9 @@ sub pandora_trash_ascii {
return $output return $output
} }
######################################################################## ################################################################################
## Convert the $value encode in html entity to clear char string. ## Convert the $value encode in html entity to clear char string.
######################################################################## ################################################################################
sub safe_input($) { sub safe_input($) {
my $value = shift; my $value = shift;
@ -439,9 +444,9 @@ sub safe_input($) {
return $value; return $value;
} }
######################################################################## ################################################################################
## Convert the html entities to value encode to rebuild char string. ## Convert the html entities to value encode to rebuild char string.
######################################################################## ################################################################################
sub safe_output($) { sub safe_output($) {
my $value = shift; my $value = shift;
@ -452,10 +457,10 @@ sub safe_output($) {
return $value; return $value;
} }
######################################################################## ################################################################################
# Sub daemonize () # Sub daemonize ()
# Put program in background (for daemon mode) # Put program in background (for daemon mode)
######################################################################## ################################################################################
sub pandora_daemonize { sub pandora_daemonize {
my $pa_config = $_[0]; my $pa_config = $_[0];
@ -492,13 +497,13 @@ sub pandora_daemonize {
# Pandora other General functions | # Pandora other General functions |
# -------------------------------------------+ # -------------------------------------------+
######################################################################## ################################################################################
# SUB credential_store_get_key # SUB credential_store_get_key
# Retrieve all information related to target identifier. # Retrieve all information related to target identifier.
# param1 - config hash # param1 - config hash
# param2 - dbh link # param2 - dbh link
# param3 - string identifier # param3 - string identifier
######################################################################## ################################################################################
sub credential_store_get_key($$$) { sub credential_store_get_key($$$) {
my ($pa_config, $dbh, $identifier) = @_; my ($pa_config, $dbh, $identifier) = @_;
@ -520,7 +525,7 @@ sub credential_store_get_key($$$) {
} }
######################################################################## ################################################################################
# SUB pandora_sendmail # SUB pandora_sendmail
# Send a mail, connecting directly to MTA # Send a mail, connecting directly to MTA
# param1 - config hash # param1 - config hash
@ -528,7 +533,7 @@ sub credential_store_get_key($$$) {
# param3 - Email subject # param3 - Email subject
# param4 - Email Message body # param4 - Email Message body
# param4 - Email content type # param4 - Email content type
######################################################################## ################################################################################
sub pandora_sendmail { sub pandora_sendmail {
@ -584,10 +589,10 @@ sub pandora_sendmail {
}; };
} }
########################################################################## ################################################################################
# SUB is_numeric # SUB is_numeric
# Return TRUE if given argument is numeric # Return TRUE if given argument is numeric
########################################################################## ################################################################################
sub is_numeric { sub is_numeric {
my $val = $_[0]; my $val = $_[0];
@ -610,10 +615,73 @@ sub is_numeric {
} }
} }
########################################################################## ################################################################################
# SUB is_enabled
# Return TRUE if given argument is defined, number and greater than 1.
################################################################################
sub is_enabled {
my $value = shift;
if ((defined ($value)) && is_numeric($value) && ($value > 0)){
# return true
return 1;
}
#return false
return 0;
}
################################################################################
# SUB is_empty
# Return TRUE if given argument is an empty string/array/hash or undefined.
################################################################################
sub is_empty {
my $str = shift;
if (! (defined ($str)) ){
return 1;
}
if(looks_like_number($str)){
return 0;
}
if (ref ($str) eq "ARRAY") {
return (($#{$str}<0)?1:0);
}
if (ref ($str) eq "HASH") {
my @tmp = keys %{$str};
return (($#tmp<0)?1:0);
}
if ($str =~ /^\ *[\n\r]{0,2}\ *$/) {
return 1;
}
return 0;
}
################################################################################
# Check if a value is in an array
################################################################################
sub is_in_array {
my ($array, $value) = @_;
if (is_empty($value)) {
return 0;
}
my %params = map { $_ => 1 } @{$array};
if (exists($params{$value})) {
return 1;
}
return 0;
}
################################################################################
# SUB md5check (param_1, param_2) # SUB md5check (param_1, param_2)
# Verify MD5 file .checksum # Verify MD5 file .checksum
########################################################################## ################################################################################
# param_1 : Name of data file # param_1 : Name of data file
# param_2 : Name of md5 file # param_2 : Name of md5 file
@ -647,10 +715,10 @@ sub md5check {
} }
} }
######################################################################## ################################################################################
# SUB logger (pa_config, message, level) # SUB logger (pa_config, message, level)
# Log to file # Log to file
######################################################################## ################################################################################
sub logger ($$;$) { sub logger ($$;$) {
my ($pa_config, $message, $level) = @_; my ($pa_config, $message, $level) = @_;
@ -701,10 +769,10 @@ sub logger ($$;$) {
} }
} }
######################################################################## ################################################################################
# SUB pandora_rotate_log (pa_config) # SUB pandora_rotate_log (pa_config)
# Log to file # Log to file
######################################################################## ################################################################################
sub pandora_rotate_logfile ($) { sub pandora_rotate_logfile ($) {
my ($pa_config) = @_; my ($pa_config) = @_;
@ -720,9 +788,9 @@ sub pandora_rotate_logfile ($) {
} }
} }
######################################################################## ################################################################################
# limpia_cadena (string) - Purge a string for any forbidden characters (esc, etc) # limpia_cadena (string) - Purge a string for any forbidden characters (esc, etc)
######################################################################## ################################################################################
sub limpia_cadena { sub limpia_cadena {
my $micadena; my $micadena;
$micadena = $_[0]; $micadena = $_[0];
@ -736,9 +804,9 @@ sub limpia_cadena {
} }
} }
######################################################################## ################################################################################
# clean_blank (string) - Remove leading and trailing blanks # clean_blank (string) - Remove leading and trailing blanks
######################################################################## ################################################################################
sub clean_blank { sub clean_blank {
my $input = $_[0]; my $input = $_[0];
$input =~ s/^\s+//g; $input =~ s/^\s+//g;
@ -746,10 +814,10 @@ sub clean_blank {
return $input; return $input;
} }
######################################################################################## ################################################################################
# sub sqlWrap(texto) # sub sqlWrap(texto)
# Elimina comillas y caracteres problematicos y los sustituye por equivalentes # Elimina comillas y caracteres problematicos y los sustituye por equivalentes
######################################################################################## ################################################################################
sub sqlWrap { sub sqlWrap {
my $toBeWrapped = shift(@_); my $toBeWrapped = shift(@_);
@ -760,21 +828,21 @@ sub sqlWrap {
} }
} }
########################################################################## ################################################################################
# sub float_equal (num1, num2, decimals) # sub float_equal (num1, num2, decimals)
# This function make possible to compare two float numbers, using only x decimals # This function make possible to compare two float numbers, using only x decimals
# in comparation. # in comparation.
# Taken from Perl Cookbook, O'Reilly. Thanks, guys. # Taken from Perl Cookbook, O'Reilly. Thanks, guys.
########################################################################## ################################################################################
sub float_equal { sub float_equal {
my ($A, $B, $dp) = @_; my ($A, $B, $dp) = @_;
return sprintf("%.${dp}g", $A) eq sprintf("%.${dp}g", $B); return sprintf("%.${dp}g", $A) eq sprintf("%.${dp}g", $B);
} }
########################################################################## ################################################################################
# Tries to load the PandoraEnterprise module. Must be called once before # Tries to load the PandoraEnterprise module. Must be called once before
# enterprise_hook (). # enterprise_hook ().
########################################################################## ################################################################################
sub enterprise_load ($) { sub enterprise_load ($) {
my $pa_config = shift; my $pa_config = shift;
@ -809,9 +877,9 @@ sub enterprise_load ($) {
return 1; return 1;
} }
########################################################################## ################################################################################
# Tries to call a PandoraEnterprise function. Returns undef if unsuccessful. # Tries to call a PandoraEnterprise function. Returns undef if unsuccessful.
########################################################################## ################################################################################
sub enterprise_hook ($$) { sub enterprise_hook ($$) {
my $func = shift; my $func = shift;
my @args = @{shift ()}; my @args = @{shift ()};
@ -840,19 +908,19 @@ sub enterprise_hook ($$) {
return $output; return $output;
} }
######################################################################## ################################################################################
# Prints a message to STDOUT at the given log level. # Prints a message to STDOUT at the given log level.
######################################################################## ################################################################################
sub print_message ($$$) { sub print_message ($$$) {
my ($pa_config, $message, $log_level) = @_; my ($pa_config, $message, $log_level) = @_;
print STDOUT $message . "\n" if ($pa_config->{'verbosity'} >= $log_level); print STDOUT $message . "\n" if ($pa_config->{'verbosity'} >= $log_level);
} }
########################################################################## ################################################################################
# Returns the value of an XML tag from a hash returned by XMLin (one level # Returns the value of an XML tag from a hash returned by XMLin (one level
# depth). # depth).
########################################################################## ################################################################################
sub get_tag_value ($$$;$) { sub get_tag_value ($$$;$) {
my ($hash_ref, $tag, $def_value, $all_array) = @_; my ($hash_ref, $tag, $def_value, $all_array) = @_;
$all_array = 0 unless defined ($all_array); $all_array = 0 unless defined ($all_array);
@ -871,10 +939,10 @@ sub get_tag_value ($$$;$) {
return $def_value; return $def_value;
} }
######################################################################## ################################################################################
# Initialize some variables needed by the MD5 algorithm. # Initialize some variables needed by the MD5 algorithm.
# See http://en.wikipedia.org/wiki/MD5#Pseudocode. # See http://en.wikipedia.org/wiki/MD5#Pseudocode.
######################################################################## ################################################################################
my (@R, @K); my (@R, @K);
sub md5_init () { sub md5_init () {
@ -890,10 +958,10 @@ sub md5_init () {
} }
} }
############################################################################### ################################################################################
# Return the MD5 checksum of the given string. # Return the MD5 checksum of the given string.
# Pseudocode from http://en.wikipedia.org/wiki/MD5#Pseudocode. # Pseudocode from http://en.wikipedia.org/wiki/MD5#Pseudocode.
############################################################################### ################################################################################
sub md5 ($) { sub md5 ($) {
my $str = shift; my $str = shift;
@ -981,18 +1049,18 @@ sub md5 ($) {
return unpack ("H*", pack ("V", $h0)) . unpack ("H*", pack ("V", $h1)) . unpack ("H*", pack ("V", $h2)) . unpack ("H*", pack ("V", $h3)); return unpack ("H*", pack ("V", $h0)) . unpack ("H*", pack ("V", $h1)) . unpack ("H*", pack ("V", $h2)) . unpack ("H*", pack ("V", $h3));
} }
############################################################################### ################################################################################
# MD5 leftrotate function. See http://en.wikipedia.org/wiki/MD5#Pseudocode. # MD5 leftrotate function. See http://en.wikipedia.org/wiki/MD5#Pseudocode.
############################################################################### ################################################################################
sub leftrotate ($$) { sub leftrotate ($$) {
my ($x, $c) = @_; my ($x, $c) = @_;
return (0xFFFFFFFF & ($x << $c)) | ($x >> (32 - $c)); return (0xFFFFFFFF & ($x << $c)) | ($x >> (32 - $c));
} }
########################################################################## ################################################################################
## Convert a date (yyy-mm-ddThh:ii:ss) to Timestamp. ## Convert a date (yyy-mm-ddThh:ii:ss) to Timestamp.
########################################################################## ################################################################################
sub dateTimeToTimestamp { sub dateTimeToTimestamp {
$_[0] =~ /(\d{4})-(\d{2})-(\d{2})([ |T])(\d{2}):(\d{2}):(\d{2})/; $_[0] =~ /(\d{4})-(\d{2})-(\d{2})([ |T])(\d{2}):(\d{2}):(\d{2})/;
my($year, $mon, $day, $GMT, $hour, $min, $sec) = ($1, $2, $3, $4, $5, $6, $7); my($year, $mon, $day, $GMT, $hour, $min, $sec) = ($1, $2, $3, $4, $5, $6, $7);
@ -1002,10 +1070,10 @@ sub dateTimeToTimestamp {
#print "BST\t" . mktime($sec, $min, $hour, $day, $mon - 1, $year - 1900, 0, 0) . "\n"; #print "BST\t" . mktime($sec, $min, $hour, $day, $mon - 1, $year - 1900, 0, 0) . "\n";
} }
############################################################################## ################################################################################
# Below some "internal" functions for automonitoring feature # Below some "internal" functions for automonitoring feature
# TODO: Implement the same for other systems like Solaris or BSD # TODO: Implement the same for other systems like Solaris or BSD
############################################################################## ################################################################################
sub disk_free ($) { sub disk_free ($) {
my $target = $_[0]; my $target = $_[0];
@ -1082,10 +1150,10 @@ sub free_mem {
return $free_mem; return $free_mem;
} }
########################################################################## ################################################################################
## SUB ticks_totime ## SUB ticks_totime
# Transform a snmp timeticks count in a date # Transform a snmp timeticks count in a date
########################################################################## ################################################################################
sub ticks_totime ($){ sub ticks_totime ($){
@ -1109,7 +1177,7 @@ sub ticks_totime ($){
return "$days days, $hours hours, $minutes minutes, $seconds seconds"; return "$days days, $hours hours, $minutes minutes, $seconds seconds";
} }
############################################################################## ################################################################################
=head2 C<< pandora_ping (I<$pa_config>, I<$host>) >> =head2 C<< pandora_ping (I<$pa_config>, I<$host>) >>
Ping the given host. Ping the given host.
@ -1118,7 +1186,7 @@ Returns:
0 otherwise. 0 otherwise.
=cut =cut
############################################################################## ################################################################################
sub pandora_ping ($$$$) { sub pandora_ping ($$$$) {
my ($pa_config, $host, $timeout, $retries) = @_; my ($pa_config, $host, $timeout, $retries) = @_;
@ -1236,13 +1304,13 @@ sub pandora_ping ($$$$) {
return $output; return $output;
} }
######################################################################## ################################################################################
=head2 C<< pandora_ping_latency (I<$pa_config>, I<$host>) >> =head2 C<< pandora_ping_latency (I<$pa_config>, I<$host>) >>
Ping the given host. Returns the average round-trip time. Returns undef if fails. Ping the given host. Returns the average round-trip time. Returns undef if fails.
=cut =cut
######################################################################## ################################################################################
sub pandora_ping_latency ($$$$) { sub pandora_ping_latency ($$$$) {
my ($pa_config, $host, $timeout, $retries) = @_; my ($pa_config, $host, $timeout, $retries) = @_;
@ -1375,32 +1443,120 @@ sub pandora_ping_latency ($$$$) {
return $output; return $output;
} }
######################################################################## ################################################################################
=head2 C<< pandora_block_ping (I<$pa_config>, I<$hosts>) >> =head2 C<< pandora_block_ping (I<$pa_config>, I<$hosts>) >>
Ping all given hosts. Returns an array with all hosts detected as alive. Ping all given hosts. Returns an array with all hosts detected as alive.
=cut =cut
######################################################################## ################################################################################
sub pandora_block_ping($@) { sub pandora_block_ping($@) {
my ($pa_config, @hosts) = @_; my ($pa_config, @hosts) = @_;
my ($cmd, $output);
return () if is_empty(@hosts);
if (-x $pa_config->{'fping'}) {
# fping timeout in milliseconds # fping timeout in milliseconds
my $cmd = $pa_config->{'fping'} . " -a -q -t " . (1000 * $pa_config->{'networktimeout'}) . " " . (join (' ', @hosts)); $cmd = $pa_config->{'fping'} . " -a -q -t " . (1000 * $pa_config->{'networktimeout'}) . " " . (join (' ', @hosts));
@output = `$cmd 2>$DEVNULL`;
my @output = `$cmd 2>$DEVNULL`; } else {
# Ping scan
foreach my $host (@hosts) {
if (ping($pa_config, $host) > 0) {
push @output, $host;
}
}
}
return @output; return @output;
} }
######################################################################## ################################################################################
=head2 C<< ping (I<$pa_config>, I<$hosts>) >>
Ping the given host. Returns 1 if the host is alive, 0 otherwise.
=cut
################################################################################
sub ping ($$) {
my ($pa_config, $host) = @_;
my ($timeout, $retries, $packets) = (
$pa_config->{'networktimeout'},
$pa_config->{'icmp_checks'},
1
);
# Windows
if (($^O eq "MSWin32") || ($^O eq "MSWin32-x64") || ($^O eq "cygwin")){
$timeout *= 1000; # Convert the timeout to milliseconds.
for (my $i = 0; $i < $retries; $i++) {
my $output = `ping -n $packets -w $timeout $host`;
return 1 if ($output =~ /TTL/);
}
return 0;
}
# Solaris
if ($^O eq "solaris"){
my $ping_command = $host =~ /\d+:|:\d+/ ? "ping -A inet6" : "ping";
for (my $i = 0; $i < $retries; $i++) {
# Note: There is no timeout option.
`$ping_command -s -n $host 56 $packets >$DEVNULL 2>&1`;
return 1 if ($? == 0);
}
return 0;
}
# FreeBSD
if ($^O eq "freebsd"){
my $ping_command = $host =~ /\d+:|:\d+/ ? "ping6" : "ping -t $timeout";
for (my $i = 0; $i < $retries; $i++) {
# Note: There is no timeout option for ping6.
`$ping_command -q -n -c $packets $host >$DEVNULL 2>&1`;
return 1 if ($? == 0);
}
return 0;
}
# NetBSD
if ($^O eq "netbsd"){
my $ping_command = $host =~ /\d+:|:\d+/ ? "ping6" : "ping -w $timeout";
for (my $i = 0; $i < $retries; $i++) {
# Note: There is no timeout option for ping6.
`$ping_command -q -n -c $packets $host >$DEVNULL 2>&1`;
if ($? == 0) {
return 1;
}
}
return 0;
}
# Assume Linux by default.
my $ping_command = $host =~ /\d+:|:\d+/ ? "ping6" : "ping";
for (my $i = 0; $i < $retries; $i++) {
`$ping_command -q -W $timeout -n -c $packets $host >$DEVNULL 2>&1`;
return 1 if ($? == 0);
}
return 0;
}
################################################################################
=head2 C<< month_have_days (I<$month>, I<$year>) >> =head2 C<< month_have_days (I<$month>, I<$year>) >>
Pass a $month (as january 0 number and each month with numbers) and the year Pass a $month (as january 0 number and each month with numbers) and the year
as number (for example 1981). And return the days of this month. as number (for example 1981). And return the days of this month.
=cut =cut
######################################################################## ################################################################################
sub month_have_days($$) { sub month_have_days($$) {
my $month= shift(@_); my $month= shift(@_);
my $year= @_ ? shift(@_) : (1900 + (localtime())[5]); my $year= @_ ? shift(@_) : (1900 + (localtime())[5]);
@ -1428,9 +1584,9 @@ sub month_have_days($$) {
return $monthDays[$month]; return $monthDays[$month];
} }
############################################################################### ################################################################################
# Convert a text obj tag to an OID and update the module configuration. # Convert a text obj tag to an OID and update the module configuration.
############################################################################### ################################################################################
sub translate_obj ($$$) { sub translate_obj ($$$) {
my ($pa_config, $dbh, $obj) = @_; my ($pa_config, $dbh, $obj) = @_;
@ -1448,9 +1604,9 @@ sub translate_obj ($$$) {
return $oid; return $oid;
} }
############################################################################### ################################################################################
# Get the number of seconds left to the next execution of the given cron entry. # Get the number of seconds left to the next execution of the given cron entry.
############################################################################### ################################################################################
sub cron_next_execution { sub cron_next_execution {
my ($cron, $interval) = @_; my ($cron, $interval) = @_;
@ -1482,18 +1638,18 @@ sub cron_next_execution {
return $nex_time - $cur_time; return $nex_time - $cur_time;
} }
############################################################################### ################################################################################
# Get the number of seconds left to the next execution of the given cron entry. # Get the number of seconds left to the next execution of the given cron entry.
############################################################################### ################################################################################
sub cron_check_syntax ($) { sub cron_check_syntax ($) {
my ($cron) = @_; my ($cron) = @_;
return 0 if !defined ($cron); return 0 if !defined ($cron);
return ($cron =~ m/^(\d|\*|-)+ (\d|\*|-)+ (\d|\*|-)+ (\d|\*|-)+ (\d|\*|-)+$/); return ($cron =~ m/^(\d|\*|-)+ (\d|\*|-)+ (\d|\*|-)+ (\d|\*|-)+ (\d|\*|-)+$/);
} }
############################################################################### ################################################################################
# Check if a value is inside an interval. # Check if a value is inside an interval.
############################################################################### ################################################################################
sub cron_check_interval { sub cron_check_interval {
my ($elem_cron, $elem_curr_time) = @_; my ($elem_cron, $elem_curr_time) = @_;
@ -1515,9 +1671,9 @@ sub cron_check_interval {
return 1; return 1;
} }
############################################################################### ################################################################################
# Get the next execution date for the given cron entry in seconds since epoch. # Get the next execution date for the given cron entry in seconds since epoch.
############################################################################### ################################################################################
sub cron_next_execution_date { sub cron_next_execution_date {
my ($cron, $cur_time, $interval) = @_; my ($cron, $cur_time, $interval) = @_;
@ -1646,11 +1802,11 @@ sub cron_next_execution_date {
return $nex_time; return $nex_time;
} }
############################################################################### ################################################################################
# Returns if a date is in a cron. Recursive. # Returns if a date is in a cron. Recursive.
# Needs the cron like an array reference and # Needs the cron like an array reference and
# current time in cron format to works properly # current time in cron format to works properly
############################################################################### ################################################################################
sub cron_is_in_cron { sub cron_is_in_cron {
my ($elems_cron, $elems_curr_time) = @_; my ($elems_cron, $elems_curr_time) = @_;
@ -1687,11 +1843,11 @@ sub cron_get_next_time_element {
? $floor_data ? $floor_data
: $elem_down; : $elem_down;
} }
############################################################################### ################################################################################
# Returns the interval of a cron element. If there is not a range, # Returns the interval of a cron element. If there is not a range,
# returns an array with the first element in the first place of array # returns an array with the first element in the first place of array
# and the second place undefined. # and the second place undefined.
############################################################################### ################################################################################
sub cron_get_interval { sub cron_get_interval {
my ($element) = @_; my ($element) = @_;
@ -1702,10 +1858,10 @@ sub cron_get_interval {
return ($1, $2); return ($1, $2);
} }
############################################################################### ################################################################################
# Returns the closest number to the target inside the given range (including # Returns the closest number to the target inside the given range (including
# the target itself). # the target itself).
############################################################################### ################################################################################
sub cron_get_closest_in_range ($$) { sub cron_get_closest_in_range ($$) {
my ($target, $range) = @_; my ($target, $range) = @_;
@ -1727,9 +1883,9 @@ sub cron_get_closest_in_range ($$) {
return $target; return $target;
} }
############################################################################### ################################################################################
# Check if a date is valid to get timelocal # Check if a date is valid to get timelocal
############################################################################### ################################################################################
sub cron_valid_date { sub cron_valid_date {
my ($min, $hour, $mday, $month, $year) = @_; my ($min, $hour, $mday, $month, $year) = @_;
my $utime; my $utime;
@ -1743,9 +1899,9 @@ sub cron_valid_date {
return $utime; return $utime;
} }
############################################################################### ################################################################################
# Attempt to resolve the given hostname. # Attempt to resolve the given hostname.
############################################################################### ################################################################################
sub resolve_hostname ($) { sub resolve_hostname ($) {
my ($hostname) = @_; my ($hostname) = @_;
@ -1755,9 +1911,9 @@ sub resolve_hostname ($) {
return inet_ntoa($resolved_hostname); return inet_ntoa($resolved_hostname);
} }
############################################################################### ################################################################################
# Returns 1 if the given regular expression is valid, 0 otherwise. # Returns 1 if the given regular expression is valid, 0 otherwise.
############################################################################### ################################################################################
sub valid_regex ($) { sub valid_regex ($) {
my $regex = shift; my $regex = shift;
@ -1773,9 +1929,9 @@ sub valid_regex ($) {
return 1; return 1;
} }
############################################################################### ################################################################################
# Returns 1 if a valid metaconsole license is configured, 0 otherwise. # Returns 1 if a valid metaconsole license is configured, 0 otherwise.
############################################################################### ################################################################################
sub is_metaconsole ($) { sub is_metaconsole ($) {
my ($pa_config) = @_; my ($pa_config) = @_;
@ -1788,9 +1944,9 @@ sub is_metaconsole ($) {
return 0; return 0;
} }
############################################################################### ################################################################################
# Returns 1 if a valid offline license is configured, 0 otherwise. # Returns 1 if a valid offline license is configured, 0 otherwise.
############################################################################### ################################################################################
sub is_offline ($) { sub is_offline ($) {
my ($pa_config) = @_; my ($pa_config) = @_;
@ -1802,9 +1958,9 @@ sub is_offline ($) {
return 0; return 0;
} }
############################################################################### ################################################################################
# Check if a given variable contents a number # Check if a given variable contents a number
############################################################################### ################################################################################
sub to_number($) { sub to_number($) {
my $n = shift; my $n = shift;
if ($n =~ /[\d+,]*\d+\.\d+/) { if ($n =~ /[\d+,]*\d+\.\d+/) {
@ -1956,10 +2112,10 @@ sub generate_agent_name_hash {
return sha256(join('|', ($agent_alias, $server_ip, time(), sprintf("%04d", rand(10000))))); return sha256(join('|', ($agent_alias, $server_ip, time(), sprintf("%04d", rand(10000)))));
} }
############################################################################### ################################################################################
# Return the SHA256 checksum of the given string as a hex string. # Return the SHA256 checksum of the given string as a hex string.
# Pseudocode from: http://en.wikipedia.org/wiki/SHA-2#Pseudocode # Pseudocode from: http://en.wikipedia.org/wiki/SHA-2#Pseudocode
############################################################################### ################################################################################
my @K2 = ( my @K2 = (
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
@ -2079,34 +2235,34 @@ sub sha256 {
unpack ("H*", pack ("N", $h7)); unpack ("H*", pack ("N", $h7));
} }
############################################################################### ################################################################################
# Rotate a 32-bit number a number of bits to the right. # Rotate a 32-bit number a number of bits to the right.
############################################################################### ################################################################################
sub rightrotate { sub rightrotate {
my ($x, $c) = @_; my ($x, $c) = @_;
return (0xFFFFFFFF & ($x << (32 - $c))) | ($x >> $c); return (0xFFFFFFFF & ($x << (32 - $c))) | ($x >> $c);
} }
############################################################################### ################################################################################
# Returns IP address(v4) in longint format # Returns IP address(v4) in longint format
############################################################################### ################################################################################
sub ip_to_long { sub ip_to_long($) {
my $ip_str = shift; my $ip_str = shift;
return unpack "N", inet_aton($ip_str); return unpack "N", inet_aton($ip_str);
} }
############################################################################### ################################################################################
# Returns IP address(v4) in longint format # Returns IP address(v4) in longint format
############################################################################### ################################################################################
sub long_to_ip { sub long_to_ip {
my $ip_long = shift; my $ip_long = shift;
return inet_ntoa pack("N", ($ip_long)); return inet_ntoa pack("N", ($ip_long));
} }
############################################################################### ################################################################################
# Returns a list with enabled servers. # Returns a list with enabled servers.
############################################################################### ################################################################################
sub get_enabled_servers { sub get_enabled_servers {
my $conf = shift; my $conf = shift;
@ -2178,12 +2334,24 @@ sub get_user_agent {
return $ua; return $ua;
} }
################################################################################
# Returns 'valid' url relative to current pandora_console installation.
################################################################################
sub ui_get_full_url {
my ($pa_config, $url) = @_;
if (is_empty($pa_config->{'console_api_url'})) {
# Do not relativize if console_api_url is empty.
return $url;
}
my $console_url = $pa_config->{'console_api_url'};
$console_url =~ s/include\/api.php$//;
return $console_url.$url;
}
1; 1;
__END__ __END__

View File

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

View File

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

View File

@ -9,7 +9,7 @@
# ********************************************************************** # **********************************************************************
PI_VERSION="7.0NG.744" PI_VERSION="7.0NG.744"
PI_BUILD="200413" PI_BUILD="200420"
MODE=$1 MODE=$1
if [ $# -gt 1 ]; then if [ $# -gt 1 ]; then

View File

@ -35,7 +35,7 @@ use PandoraFMS::Config;
use PandoraFMS::DB; use PandoraFMS::DB;
# version: define current version # version: define current version
my $version = "7.0NG.744 PS200413"; my $version = "7.0NG.744 PS200420";
# Pandora server configuration # Pandora server configuration
my %conf; my %conf;

View File

@ -36,7 +36,7 @@ use Encode::Locale;
Encode::Locale::decode_argv; Encode::Locale::decode_argv;
# version: define current version # version: define current version
my $version = "7.0NG.744 PS200413"; my $version = "7.0NG.744 PS200420";
# save program name for logging # save program name for logging
my $progname = basename($0); my $progname = basename($0);

View File

@ -0,0 +1,308 @@
#!/usr/bin/perl
#
################################################################################
#
# SNMP wizard module
#
# Requirements:
# Net::SNMP
# Crypt::DES
# Digest::SHA1
#
# (c) Enrique Martin Garcia <enrique.martin@artica.es>
#
# 2020/03/10
#
################################################################################
use strict;
use warnings;
use POSIX qw(strftime);
use Encode;
use Encode::Locale;
use Getopt::Long;
use Net::SNMP;
my $HELP=<<EO_HELP;
Get the result of an arithmetic operation using several OIDs values.
Usage: $0 -host "<ip_address>" -version "<snmp_version>" [SNMP] [SNMPv3] -oidList "<oid1>,<oid2>" -operation "<aritmetic_operation>"
-host Target host
-version SNMP version (1, 2c, 3)
-oidList Comma separated OIDs used
-operation Aritmetic operation to get data.
Macros _oN_ will be changed by OIDs in list.
Example: (_o1_ * 100) / _o2_
[SNMP]
-community Community (only version 1 and 2c)
-port Target UDP port (Default 161)
[SNMPv3]
-user Username
-authMethod Authentication method (MD5, SHA)
-authPass Authentication password
-privMethod Privacy method (DES, AES)
-privPass Privacy password
-secLevel Security level (noAuthNoPriv, authNoPriv, authPriv)
Example: $0 -host 192.168.80.43 -community public -version 1 -oidlist "1.3.6.1.2.1.2.2.1.10.1,1.3.6.1.2.1.2.2.1.16.1" -operation "_o1_ + _o2_"
EO_HELP
#
# FUNCTIONS
##############
sub new_snmp_target {
my ($config) = @_;
my $target;
my $error;
if ($config->{'version'} ne '3'){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-community => $config->{'community'}
);
}else{
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'}
);
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'}
);
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'},
-privpassword => $config->{'priv_pass'},
-privprotocol => $config->{'priv_method'}
);
}
}
return ($target, $error);
}
sub snmp_walk {
my ($target, $oid) = @_;
my $result = {};
my $walk = $target->get_table(
-baseoid => $oid,
);
if (defined($walk)){
$result = $walk;
}
return $result;
}
sub snmp_get {
my ($target, $oid) = @_;
my $result = '';
my $get = $target->get_request(
-varbindlist => [$oid],
);
if (defined($get)){
$result = $get->{$oid};
}
return $result;
}
#
# MAIN
##############
@ARGV = map { decode(locale => $_, 1) } @ARGV if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
my %Param = ();
GetOptions(
\%Param,
# General
'community=s',
'version=s',
'host=s',
'port=s',
'timeout=s',
# Version 3
'user=s',
'authMethod=s',
'authPass=s',
'privMethod=s',
'privPass=s',
'secLevel=s',
# Operation
'oidList=s',
'operation=s',
# Help option
'Help',
);
if ($Param{Help}){
print $HELP;
exit 0;
}
my $config;
# General parameters
$config->{'community'} = $Param{community} || '';
$config->{'version'} = $Param{version} || '';
$config->{'host'} = $Param{host} || '';
$config->{'port'} = $Param{port} || '161';
$config->{'timeout'} = $Param{timeout} || '2';
# Version 3 parameters
$config->{'auth_method'} = $Param{authMethod} || '';
$config->{'user'} = $Param{user} || '';
$config->{'auth_pass'} = $Param{authPass} || '';
$config->{'priv_method'} = $Param{privMethod} || '';
$config->{'priv_pass'} = $Param{privPass} || '';
$config->{'sec_level'} = $Param{secLevel} || '';
$config->{'auth_method'} = uc($config->{'auth_method'});
$config->{'priv_method'} = uc($config->{'priv_method'});
# Operation
my $operation = $Param{operation} || '';
# OIDs
my @oid_list = split /,/, $Param{oidList} || '';
# Verify parameters
if (!$config->{'host'} || !$config->{'version'} || !$operation || !@oid_list){
print $HELP;
print "Host, version, OID list and operation are required.\n";
exit 1;
}
if ($config->{'version'} ne '1' && $config->{'version'} ne '2c' && $config->{'version'} ne '3'){
print $HELP;
print "Invalid SNMP version provided.\n";
exit 1;
}
if ($config->{'version'} eq '1' || $config->{'version'} eq '2c'){
if (!$config->{'community'}){
print $HELP;
print "SNMP community required for version 1 or 2c.\n";
exit 1;
}
}
if ($config->{'version'} eq '3'){
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
if (!$config->{'user'}){
print $HELP;
print "Username required for SNMP version 3 and security level 'noAuthNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'}){
print $HELP;
print "Username, authentication password and authentication method required for SNMP version 3 and security level 'authNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'} && !$config->{'priv_pass'} && !$config->{'priv_method'}){
print $HELP;
print "Username, authentication password, authentication method, privacy password and privacy method required for SNMP version 3 and security level 'authPriv'.\n";
exit 1;
}
}else{
print $HELP;
print "Invalid SNMP security level provided for version 3.\n";
exit 1;
}
if ($config->{'auth_method'} && $config->{'auth_method'} ne 'MD5' && $config->{'auth_method'} ne 'SHA'){
print $HELP;
print "Invalid SNMP authentication method provided for version 3.\n";
exit 1;
}
if ($config->{'priv_method'} && $config->{'priv_method'} ne 'DES' && $config->{'priv_method'} ne 'AES'){
print $HELP;
print "Invalid SNMP privacy method provided for version 3.\n";
exit 1;
}
}
# Verify operation (avoid code injection)
my @operation = split //, lc($operation);
foreach my $op (@operation){
if ($op !~ /\d/ && $op ne ' ' && $op ne '(' && $op ne ')' && $op ne '_' && $op ne '-' && $op ne '+' && $op ne '*' && $op ne '/' && $op ne 'o'){
print $HELP;
print "Specified operation has invalid characters: " . $op . "\n";
exit 1;
}
}
# Create SNMP target
my ($target, $error) = new_snmp_target($config);
if (!$target){
print $error . "\n";
exit 1;
}
# Get OIDs values
my $oid_values = {};
my $i = 1;
foreach my $oid (@oid_list){
$oid_values->{'_o' . $i . '_'} = snmp_get($target, $oid);
$i++;
}
# Change operation macros with values
$i = 1;
foreach my $k (keys %{$oid_values}){
my $oid_macro = '_o' . $i . '_';
my $value = $oid_values->{$oid_macro};
$operation =~ s/$oid_macro/$value/g;
$i++;
}
# Get operation result
my $result = eval $operation;
if (defined($result)){
print $result . "\n";
}

View File

@ -0,0 +1,282 @@
#!/usr/bin/perl
#
################################################################################
#
# SNMP wizard process
#
# Requirements:
# Net::SNMP
# Crypt::DES
# Digest::SHA1
#
# (c) Enrique Martin Garcia <enrique.martin@artica.es>
#
# 2020/03/10
#
################################################################################
use strict;
use warnings;
use POSIX qw(strftime);
use Encode;
use Encode::Locale;
use Getopt::Long;
use Net::SNMP;
my $HELP=<<EO_HELP;
Check if a process is running (1) or not (0) in OID .1.3.6.1.2.1.25.4.2.1.2 SNMP tree.
Usage: $0 -host "<ip_address>" -version "<snmp_version>" [SNMP] [SNMPv3] -process "<process_name>"
-host Target host
-version SNMP version (1, 2c, 3)
-process Process name to check if is running (case sensitive)
[SNMP]
-community Community (only version 1 and 2c)
-port Target UDP port (Default 161)
[SNMPv3]
-user Username
-authMethod Authentication method (MD5, SHA)
-authPass Authentication password
-privMethod Privacy method (DES, AES)
-privPass Privacy password
-secLevel Security level (noAuthNoPriv, authNoPriv, authPriv)
Example: $0 -host 192.168.80.43 -community public -version 1 -process "httpd"
EO_HELP
#
# FUNCTIONS
##############
sub new_snmp_target {
my ($config) = @_;
my $target;
my $error;
if ($config->{'version'} ne '3'){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-community => $config->{'community'}
);
}else{
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'}
);
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'}
);
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
($target, $error) = Net::SNMP->session(
-hostname => $config->{'host'},
-port => $config->{'port'},
-version => $config->{'version'},
-timeout => $config->{'timeout'},
-translate => 0,
-username => $config->{'user'},
-authpassword => $config->{'auth_pass'},
-authprotocol => $config->{'auth_method'},
-privpassword => $config->{'priv_pass'},
-privprotocol => $config->{'priv_method'}
);
}
}
return ($target, $error);
}
sub snmp_walk {
my ($target, $oid) = @_;
my $result = {};
my $walk = $target->get_table(
-baseoid => $oid,
);
if (defined($walk)){
$result = $walk;
}
return $result;
}
sub snmp_get {
my ($target, $oid) = @_;
my $result = '';
my $get = $target->get_request(
-varbindlist => [$oid],
);
if (defined($get)){
$result = $get->{$oid};
}
return $result;
}
#
# MAIN
##############
@ARGV = map { decode(locale => $_, 1) } @ARGV if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
my %Param = ();
GetOptions(
\%Param,
# General
'community=s',
'version=s',
'host=s',
'port=s',
'timeout=s',
# Version 3
'user=s',
'authMethod=s',
'authPass=s',
'privMethod=s',
'privPass=s',
'secLevel=s',
# Process
'process=s',
# Help option
'Help',
);
if ($Param{Help}){
print $HELP;
exit 0;
}
my $config;
# General parameters
$config->{'community'} = $Param{community} || '';
$config->{'version'} = $Param{version} || '';
$config->{'host'} = $Param{host} || '';
$config->{'port'} = $Param{port} || '161';
$config->{'timeout'} = $Param{timeout} || '2';
# Version 3 parameters
$config->{'auth_method'} = $Param{authMethod} || '';
$config->{'user'} = $Param{user} || '';
$config->{'auth_pass'} = $Param{authPass} || '';
$config->{'priv_method'} = $Param{privMethod} || '';
$config->{'priv_pass'} = $Param{privPass} || '';
$config->{'sec_level'} = $Param{secLevel} || '';
$config->{'auth_method'} = uc($config->{'auth_method'});
$config->{'priv_method'} = uc($config->{'priv_method'});
# Operation
my $process = $Param{process} || '';
# Verify parameters
if (!$config->{'host'} || !$config->{'version'} || !$process){
print $HELP;
print "Host, version and process are required.\n";
exit 1;
}
if ($config->{'version'} ne '1' && $config->{'version'} ne '2c' && $config->{'version'} ne '3'){
print $HELP;
print "Invalid SNMP version provided.\n";
exit 1;
}
if ($config->{'version'} eq '1' || $config->{'version'} eq '2c'){
if (!$config->{'community'}){
print $HELP;
print "SNMP community required for version 1 or 2c.\n";
exit 1;
}
}
if ($config->{'version'} eq '3'){
if ($config->{'sec_level'} =~ /^noAuthNoPriv$/i){
if (!$config->{'user'}){
print $HELP;
print "Username required for SNMP version 3 and security level 'noAuthNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authNoPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'}){
print $HELP;
print "Username, authentication password and authentication method required for SNMP version 3 and security level 'authNoPriv'.\n";
exit 1;
}
}elsif ($config->{'sec_level'} =~ /^authPriv$/i){
if (!$config->{'user'} && !$config->{'auth_pass'} && !$config->{'auth_method'} && !$config->{'priv_pass'} && !$config->{'priv_method'}){
print $HELP;
print "Username, authentication password, authentication method, privacy password and privacy method required for SNMP version 3 and security level 'authPriv'.\n";
exit 1;
}
}else{
print $HELP;
print "Invalid SNMP security level provided for version 3.\n";
exit 1;
}
if ($config->{'auth_method'} && $config->{'auth_method'} ne 'MD5' && $config->{'auth_method'} ne 'SHA'){
print $HELP;
print "Invalid SNMP authentication method provided for version 3.\n";
exit 1;
}
if ($config->{'priv_method'} && $config->{'priv_method'} ne 'DES' && $config->{'priv_method'} ne 'AES'){
print $HELP;
print "Invalid SNMP privacy method provided for version 3.\n";
exit 1;
}
}
# Create SNMP target
my ($target, $error) = new_snmp_target($config);
if (!$target){
print $error . "\n";
exit 1;
}
# Get all running processes
my $processes = snmp_walk($target, '.1.3.6.1.2.1.25.4.2.1.2');
my $result = 0;
# Search process name
foreach my $k (keys %{$processes}){
if ($processes->{$k} eq $process){
$result = 1;
last;
}
}
print $result . "\n";

View File

@ -0,0 +1,176 @@
#!/usr/bin/perl
#
################################################################################
#
# WMI wizard module
#
# Requirements:
# wmic
#
# (c) Enrique Martin Garcia <enrique.martin@artica.es>
#
# 2020/03/10
#
################################################################################
use strict;
use warnings;
use POSIX qw(strftime);
use Encode;
use Encode::Locale;
use Getopt::Long;
use Data::Dumper;
my $HELP=<<EO_HELP;
Get the result of an arithmetic operation using distinct fields in a WMI query (Query must return only 1 row).
Usage: $0 [-wmicPath "<path_to_wmic>"] -host "<ip_address>" [-namespace "<namespace>"] -user "<username>" -pass "<password>" -wmiClass "<wmi_class>" -fieldsList "<class_fields_names>" [-queryFilter "<query_filter>"] -operation "<aritmetic_operation>"
-wmicPath Path to wmic command (Default: /usr/bin/wmic)
-host Target host
-namespace WMI namespace
-user Windows username ([domain/]username)
-pass User password
-wmiClass WMI class for query (Example: Win32_OperatingSystem)
-fieldsList Comma separated class fields list (Example: TotalVisibleMemorySize,FreePhysicalMemory)
-queryFilter WMI query class filter (Example: DeviceID = 3 AND DeviceType = 1)
-operation Aritmetic operation to get data.
Macros _fN_ will be changed by fields in list.
Example: ((_f1_ - _f2_) * 100) / _f1_
Example: $0 -host "192.168.80.43" -user "pandora/Administrator" -pass "PandoraFMS1234" -wmiClass "Win32_OperatingSystem" -fieldsList "TotalVisibleMemorySize,FreePhysicalMemory" -operation "((_f1_ - _f2_) * 100) / _f1_"
EO_HELP
#
# MAIN
##############
@ARGV = map { decode(locale => $_, 1) } @ARGV if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
my %Param = ();
GetOptions(
\%Param,
# General
'wmicPath=s',
'host=s',
'namespace=s',
'user=s',
'pass=s',
# Query
'wmiClass=s',
'fieldsList=s',
'queryFilter=s',
# Operation
'operation=s',
# Help option
'Help',
);
if ($Param{Help}){
print $HELP;
exit 0;
}
my $config;
# General parameters
$config->{'wmicPath'} = $Param{wmicPath} || '/usr/bin/wmic';
$config->{'host'} = $Param{host} || '';
$config->{'namespace'} = $Param{namespace} || '';
$config->{'user'} = $Param{user} || '';
$config->{'pass'} = $Param{pass} || '';
# Query parameters
$config->{'wmiClass'} = $Param{wmiClass} || '';
$config->{'queryFilter'} = $Param{queryFilter} || '';
$config->{'fieldsList'} = $Param{fieldsList} || '';
# Operation
my $operation = $Param{operation} || '';
# Fields
my @fields_list = split /,/, $config->{'fieldsList'} || '';
# Verify parameters
if (!$config->{'host'} || !$config->{'user'} || !$config->{'pass'} || !$config->{'wmiClass'} || !@fields_list || !$operation){
print $HELP;
print "Host, user, password, WMI class, fields list and operation are required.\n";
exit 1;
}
# Verify operation (avoid code injection)
my @operation = split //, lc($operation);
foreach my $op (@operation){
if ($op !~ /\d/ && $op ne ' ' && $op ne '(' && $op ne ')' && $op ne '_' && $op ne '-' && $op ne '+' && $op ne '*' && $op ne '/' && $op ne 'f'){
print $HELP;
print "Specified operation has invalid characters: " . $op . "\n";
exit 1;
}
}
# Build WMI query
my $wmi_query = 'SELECT ' . $config->{'fieldsList'} . ' FROM ' . $config->{'wmiClass'} . ($config->{'queryFilter'} ? ' WHERE ' . $config->{'queryFilter'} : '');
# Build wmic command
my $wmi_command = $config->{'wmicPath'} . ' -U ' . $config->{'user'} . '%' . $config->{'pass'} . ($config->{'namespace'} ? ' --namespace="' . $config->{'namespace'} . '"' : '') . ' //' . $config->{'host'} . ' "' . $wmi_query . '"';
# Run wmic and parse output
my $output = `$wmi_command 2>/dev/null`;
my @data = split("\n", $output);
if ($data[0] ne 'CLASS: ' . $config->{'wmiClass'}){
print $output;
exit 1;
}
# Parse fields positions
my @fields_pos;
my $i = 0;
foreach my $field (split /\|/, $data[1]){
my $x = 1;
foreach my $f (@fields_list){
$f =~ s/^\s*//;
$f =~ s/\s*$//;
if (lc($field) eq lc($f)){
$fields_pos[$i] = $x;
}
$x++;
}
$i++;
}
# Get fields values
my $fields_values = {};
$i = 0;
foreach my $field_value (split /\|/, $data[2]){
$fields_values->{'_f' . $fields_pos[$i] . '_'} = $field_value;
$i++;
}
# Change operation macros with values
$i = 1;
foreach my $k (keys %{$fields_values}){
my $field_macro = '_f' . $i . '_';
my $value = $fields_values->{$field_macro};
$operation =~ s/$field_macro/$value/g;
$i++;
}
# Get operation result
my $result = eval $operation;
if (defined($result)){
print $result . "\n";
}