START TRANSACTION;
INSERT INTO `role` (`roleid`,`name`,`type`,`readonly`) VALUES ('1','User role','1','0'),
('2','Admin role','2','0'),
('3','Super admin role','3','1'),
('4','Guest role','1','0');
INSERT INTO `ugset` (`ugsetid`,`hash`) VALUES ('1','b21d61561974b06cbeb97a71ca880e92f0fc06d49ac3246280afb88dfa6050a6');
INSERT INTO `users` (`userid`,`username`,`name`,`surname`,`passwd`,`url`,`autologin`,`autologout`,`refresh`,`rows_per_page`,`roleid`) VALUES ('1','Admin','Zabbix','Administrator','$2y$10$92nDno4n0Zm7Ej7Jfsz8WukBfgSS/U0QkIuu8WkJPihXBb2A1UrEK','','1','0','30s','50','3'),
('2','guest','','','$2y$10$89otZrRNmde97rIyzclecuk6LwKAsHN0BcvoOKGjbT.BwMBfm7G06','','0','15m','30s','50','4');
INSERT INTO `hstgrp` (`groupid`,`name`,`flags`,`uuid`,`type`) VALUES ('1','Templates','0','7df96b18c230490a9a0a9e2307226338','1'),
('2','Linux servers','0','dc579cd7a1a34222933f24f52a68bcd8','0'),
('4','Zabbix servers','0','6f6799aa69e844b4b3918f779f2abf08','0'),
('5','Discovered hosts','0','f2481361f99448eea617b7b1d4765566','0'),
('6','Virtual machines','0','137f19e6e2dc4219b33553b812627bc2','0'),
('7','Hypervisors','0','1b837a3c078647049a0c00c61b4d57b5','0'),
('9','Templates/Network devices','0','36bff6c29af64692839d077febfc7079','1'),
('10','Templates/Operating systems','0','846977d1dfed4968bc5f8bdb363285bc','1'),
('11','Templates/Server hardware','0','e960332b3f6c46a1956486d4f3f99fce','1'),
('12','Templates/Applications','0','a571c0d144b14fd4a87a9d9b2aa9fcd6','1'),
('13','Templates/Databases','0','748ad4d098d447d492bb935c907f652f','1'),
('14','Templates/Virtualization','0','02e4df4f20b848e79267641790f241da','1'),
('15','Templates/Telephony','0','1d12408342854fd5a4436dd6d5d1bd4a','1'),
('16','Templates/SAN','0','7c2cb727f85b492d88cd56e17127c64d','1'),
('17','Templates/Video surveillance','0','d37f71c7e3f7469bab645852a69a2018','1'),
('18','Templates/Power','0','3dcd5bbe90534f9e8eb5c2d53756af63','1'),
('19','Applications','0','a571c0d144b14fd4a87a9d9b2aa9fcd6','0'),
('20','Databases','0','748ad4d098d447d492bb935c907f652f','0'),
('21','Templates/Cloud','0','c2c162144c2d4c5491c8801193af4945','1');
INSERT INTO `drules` (`druleid`,`proxyid`,`name`,`iprange`,`delay`,`status`,`concurrency_max`) VALUES ('2',NULL,'Local network','192.168.0.1-254','1h','1','0');
INSERT INTO `dchecks` (`dcheckid`,`druleid`,`type`,`key_`,`snmp_community`,`ports`,`snmpv3_securityname`,`snmpv3_securitylevel`,`snmpv3_authpassphrase`,`snmpv3_privpassphrase`,`uniq`,`snmpv3_authprotocol`,`snmpv3_privprotocol`,`snmpv3_contextname`,`host_source`,`name_source`,`allow_redirect`) VALUES ('2','2','9','system.uname','','10050','','0','','','0','0','0','','1','0','0');
INSERT INTO `media_type` (`mediatypeid`,`type`,`name`,`smtp_server`,`smtp_helo`,`smtp_email`,`exec_path`,`gsm_modem`,`username`,`passwd`,`smtp_port`,`smtp_security`,`smtp_verify_peer`,`smtp_verify_host`,`smtp_authentication`,`maxsessions`,`maxattempts`,`attempt_interval`,`message_format`,`script`,`timeout`,`process_tags`,`show_event_menu`,`event_menu_url`,`event_menu_name`,`description`,`provider`) VALUES ('1','0','Email','mail.example.com','example.com','zabbix@example.com','','','','','25','0','0','0','0','1','3','10s','0','','30s','0','0','','','','0'),
('3','2','SMS','','','','','/dev/ttyS0','','','25','0','0','0','0','1','3','10s','1','','30s','0','0','','','','0'),
('4','0','Email (HTML)','mail.example.com','example.com','zabbix@example.com','','','','','25','0','0','0','0','1','3','10s','1','','30s','0','0','','','','0'),
('34','0','Gmail','smtp.gmail.com','example.com','zabbix@example.com','','','','','587','1','0','0','1','1','3','10s','1','','30s','0','0','','','','1'),
('35','0','Gmail relay','smtp-relay.gmail.com','example.com','zabbix@example.com','','','','','587','1','0','0','0','1','3','10s','1','','30s','0','0','','','','2'),
('36','0','Office365','smtp.office365.com','example.com','zabbix@example.com','','','','','587','1','0','0','1','1','3','10s','1','','30s','0','0','','','','3'),
('37','0','Office365 relay','example-com.mail.protection.outlook.com','example.com','zabbix@example.com','','','','','25','1','0','0','0','1','3','10s','1','','30s','0','0','','','','4'),
('70','4','Brevis.one','','','','','','','','25','0','0','0','0','1','3','10s','1','var BrevisOne = {\r\n    params: [],\r\n\r\n    addParam: function (name, value) {\r\n        BrevisOne.params.push(name + \'=\' + encodeURIComponent(value));\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        BrevisOne.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    setPayload: function (params) {\r\n        var parts = params.send_to.split(\':\'),\r\n            defaultValues = {\r\n                ring: \'true\',\r\n                flash: \'true\',\r\n                telauto: \'false\'\r\n            };\r\n\r\n        BrevisOne.addParam(\'username\', params.username);\r\n        BrevisOne.addParam(\'password\', params.password);\r\n        BrevisOne.addParam(\'text\', params.text);\r\n\r\n        if (parts.length > 1) {\r\n            BrevisOne.addParam(\'mode\', parts[0]);\r\n            BrevisOne.addParam(\'to\', parts[1]);\r\n        }\r\n        else {\r\n            BrevisOne.addParam(\'to\', parts[0]);\r\n        }\r\n\r\n        Object.keys(defaultValues)\r\n            .forEach(function (key) {\r\n                if (params[key] && params[key].trim() && params[key].toLowerCase() === defaultValues[key]) {\r\n                    BrevisOne.addParam(key, defaultValues[key]);\r\n                }\r\n            });\r\n    },\r\n\r\n    request: function () {\r\n        var response,\r\n            request = new HttpRequest(),\r\n            data = \'?\' + BrevisOne.params.join(\'&\');\r\n\r\n        request.addHeader(\'Content-Type: multipart/form-data\');\r\n\r\n        if (typeof BrevisOne.HTTPProxy !== \'undefined\' && BrevisOne.HTTPProxy !== \'\') {\r\n            request.setProxy(BrevisOne.HTTPProxy);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ BrevisOne Webhook ] Sending request.\');\r\n\r\n        response = request.post(params.endpoint + data);\r\n\r\n        Zabbix.log(4, \'[ BrevisOne Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response) {\r\n                message += \': \' + response;\r\n            }\r\n\r\n            throw message + \'. Check debug log for more information.\';\r\n        }\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value);\r\n\r\n    [\'endpoint\', \'password\', \'username\', \'text\', \'send_to\'].forEach(function (field) {\r\n        if (typeof params !== \'object\' || typeof params[field] === \'undefined\'\r\n                || !params[field].trim()) {\r\n            throw \'Required parameter is not set: "\' + field + \'".\';\r\n        }\r\n    });\r\n\r\n    if (params.send_to === \'{ALERT.SENDTO}\') {\r\n        throw \'Required parameter is not set: "send_to".\';\r\n    }\r\n\r\n    BrevisOne.setProxy(params.HTTPProxy);\r\n    BrevisOne.setPayload(params);\r\n    BrevisOne.request();\r\n\r\n    return \'OK\';\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ BrevisOne Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','0','0','','','','0'),
('71','4','Discord','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nvar SEVERITY_COLORS = [\r\n	\'#97AAB3\',\r\n	\'#7499FF\',\r\n	\'#FFC859\',\r\n	\'#FFA059\',\r\n	\'#E97659\',\r\n	\'#E45959\',\r\n	\'#009900\'\r\n],\r\n	serviceLogName = \'Discord Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	Discord = CWebhook;\r\n\r\nfunction stringTruncate(str, len) {\r\n	return str.length > len ? str.substring(0, len - 3) + \'...\' : str;\r\n}\r\n\r\nDiscord.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({discord_endpoint: {type: \'string\', url: true}, zabbix_url: {type: \'string\', url: true}, alert_message: {type: \'string\'},\r\n		alert_subject: {type: \'string\'}, event_nseverity: {type: \'integer\', default: 1}, user_agent: {type: \'string\'}}, this.params);\r\n\r\n	this.params.discord_endpoint = this.params.discord_endpoint.replace(\'/api/\', \'/api/v10/\') + \'?wait=True\';\r\n\r\n	if (this.params.event_source === \'3\' && this.params.event_value === \'1\') {\r\n		this.params.event_nseverity = 4;\r\n	}\r\n\r\n	if (this.params.event_value === \'0\') {\r\n		this.params.event_nseverity = 6;\r\n	}\r\n\r\n	if (this.params.event_source === \'0\') {\r\n		CParamValidator.validate({event_id: {type: \'integer\'}, trigger_id: {type: \'integer\'}}, this.params);\r\n	}\r\n\r\n	this.data = {\r\n		embeds: [\r\n			{\r\n				color: parseInt(SEVERITY_COLORS[this.params.event_nseverity].replace(\'#\', \'\'), 16),\r\n				url: CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id),\r\n				title: stringTruncate(this.params.alert_subject, 256),\r\n				description: stringTruncate(this.params.alert_message, 4096)\r\n			}\r\n		]\r\n	};\r\n};\r\n\r\nDiscord.prototype.onEvent = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n\r\n	this.request.addHeaders({"User-Agent": this.params.user_agent});\r\n	const response = this.request.jsonRequest(\'POST\', this.params.discord_endpoint, this.data);\r\n\r\n	if (!response.id) {\r\n		const error_message = CParamValidator.isType(response.message, \'string\') ? response.message : \'Unknown error\';\r\n\r\n		throw error_message + \'. For more details check the Zabbix server log.\';\r\n	}\r\n\r\n	return \'OK\';\r\n};\r\n\r\n\r\ntry {\r\n	var hook = new Discord(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','0','0','','','This media type integrates your Zabbix installation with your Discord server using the Zabbix webhook feature.\r\n\r\nDiscord configuration:\r\n\r\n1. Go to `https://discord.com/app` or open the Discord desktop application. Open your *Server Settings* and head to the *Integrations* tab.  \r\n2. Press the *Create Webhook* button to create a new webhook.\r\n3. Click on the webhook that has been created and edit the details if needed.\r\n4. After setting up your Discord webhook press "Save Changes". Now you can copy Discord webhook URL now by pressing "Copy Webhook URL" or you can view it later.\r\n\r\nZabbix configuration:\r\n\r\n1. Before you can start using Discord webhook, set up the global macro "{$ZABBIX.URL}":\r\n- In the Zabbix web interface, go to "Administration" → "Macros" section in the dropdown menu in the top left corner.\r\n- Set up the global macro "{$ZABBIX.URL}" which will contain the URL to the Zabbix frontend. The URL should be either an IP address, a fully qualified domain name, or localhost.\r\n- Specifying a protocol is mandatory, whereas the port is optional. Depending on the web server configuration you might also need to append "/zabbix" to the end of URL. Good examples: \r\n  - http://zabbix.com\r\n  - https://zabbix.lan/zabbix\r\n  - http://server.zabbix.lan/\r\n  - http://localhost\r\n  - http://127.0.0.1:8080\r\n- Bad examples:\r\n  - zabbix.com\r\n  - http://zabbix/\r\n\r\n2. Create a Zabbix user and add media:\r\n- If you want to create a new user, go to the "Users" → "Users" section, click the "Create user" button in the top right corner. In the "User" tab, fill in all required fields (marked with red asterisks). \r\n- In the "Media" tab, add a new media and select "Discord" type from the drop-down list. The "Send to" field must contain the URL of the Discord webhook created before.\r\n- Make sure this user has access to all hosts for which you would like problem notifications to be sent to Discord.\r\n\r\n3. Great! You can now start using this media type in actions and receive alerts!\r\n\r\nYou can find the latest version of this media and additional information in the official Zabbix repository:\r\nhttps://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/discord','0'),
('72','4','Event-Driven Ansible','','','','','','','','25','0','0','0','0','1','3','10s','1','var Eda = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        var required_params = [\r\n                \'send_to\',\r\n                \'event_source\',\r\n                \'event_value\',\r\n                \'event_date\',\r\n                \'event_time\'],\r\n            integer_fields = [\r\n                \'event_id\',\r\n                \'event_nseverity\',\r\n                \'event_object\',\r\n                \'event_source\',\r\n                \'event_value\',\r\n                \'host_id\',\r\n                \'trigger_id\'];\r\n\r\n        required_params.forEach(function (field) {\r\n            if (typeof params !== \'object\' || typeof params[field] === \'undefined\' || params[field] === \'\') {\r\n                throw \'Required param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        Eda.params = params;\r\n\r\n        integer_fields.forEach(function (key) {\r\n                if (typeof Eda.params[key] !== \'undefined\') {\r\n                    if (isNaN(Eda.params[key])) {\r\n                        throw \'Parameter "\' + key + \'" must be integer. Given value: \' + Eda.params[key];\r\n                    }\r\n                    Eda.params[key] = parseInt(Eda.params[key]);\r\n                }\r\n            });\r\n\r\n        // Check type of event. Possible values: 0 - Trigger\r\n        if (params.event_source != 0) {\r\n            throw (\'Incorrect "event_source" parameter given: \' + params.event_source \r\n                + \'\\nOnly trigger-based events are supported\');\r\n        }\r\n\r\n        // Check trigger update and trigger resolve events\r\n        if (params.event_source == 0 && params.event_value != 1) {\r\n            throw (\'Incorrect "event_value" parameter given: "\' + params.event_value \r\n                + \'".\\nOnly trigger-based events of problem are supported\');\r\n        }\r\n        \r\n        // Check endpoint\r\n        Eda.params.endpoint = (Eda.params.endpoint.startsWith(\'/\'))\r\n                ? Eda.params.endpoint : \'/\' + Eda.params.endpoint;\r\n        // Prepare groups\r\n        Eda.params.host_groups = (typeof Eda.params[\'host_groups\'] !== \'undefined\')\r\n                ? this.prepareHostgroups(Eda.params.host_groups): []\r\n        // Prepare tags\r\n        Eda.params.event_tags = (typeof Eda.params[\'event_tags\'] !== \'undefined\')\r\n                ? this.transformTags(Eda.params.event_tags): {}\r\n        // Prepare timestamp\r\n        Eda.params.event_datetime_timestamp = this.getTimestamp(\r\n            Eda.params.event_date, Eda.params.event_time)\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        Eda.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    prepareHostgroups: function (hostgroups) {\r\n        var host_groups = []; \r\n        hostgroups.split(\',\').forEach(function (group) {\r\n            group = group.trim();\r\n            if (group.length > 0) {\r\n                host_groups.push(group);\r\n            }\r\n        });\r\n        return host_groups;\r\n    },\r\n\r\n    getTimestamp: function (date, time) {\r\n        try {\r\n            return Date.parse(date.split(\'.\').join(\'-\') + \'T\' + time + \'.000Z\') / 1000 + new Date().getTimezoneOffset() * 60;\r\n        } catch (_) {}\r\n    \r\n        throw (\'Failed to parse event time.\');\r\n    },\r\n\r\n    transformTags: function (event_tags) {\r\n        var tags = {};\r\n        if (event_tags) {\r\n            try {\r\n                JSON.parse(event_tags).forEach(function (object) {\r\n                    var tag = object[\'tag\'];\r\n                    tags[tag] = tags[tag] || [];\r\n                    tags[tag].push(object[\'value\']);\r\n                });\r\n            } catch (error) {\r\n                throw \'Event tags format is invalid.\';\r\n            }\r\n        }\r\n    \r\n        return tags;\r\n    },\r\n\r\n    sendMessage: function () {\r\n        var response, request = new HttpRequest();\r\n        var url = Eda.params[\'send_to\'] + Eda.params[\'endpoint\'];\r\n        var data = JSON.stringify(Eda.params);\r\n        Zabbix.log(4, \'[ Event-Driven Ansible webhook ] URL: \' + url + \' data: \' + data);\r\n        \r\n        if (typeof Eda.HTTPProxy !== \'undefined\' && Eda.HTTPProxy !== \'\') {\r\n            request.setProxy(Eda.HTTPProxy);\r\n        }\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        response = request.post(url, data);\r\n        \r\n        Zabbix.log(4, \'[ Event-Driven Ansible webhook ] HTTP code: \' + request.getStatus()\r\n            + \' response: \' + response);\r\n\r\n        if (request.getStatus() !== 200) {\r\n            throw \'Request failed with status code \' + request.getStatus() + \': \' + response;\r\n        }\r\n    }\r\n};\r\n\r\n\r\ntry {\r\n    var params = JSON.parse(value);\r\n    \r\n    Eda.setParams(params);\r\n    Eda.setProxy(params.HTTPProxy);\r\n    Eda.sendMessage();\r\n    return true;\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ Event-Driven Ansible webhook ] notification failed: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','0','0','','','','0'),
('73','4','Express.ms','','','','','','','','25','0','0','0','0','1','3','10s','1','var Express = {\r\n    params: [],\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        Express.params = params;\r\n\r\n        if (typeof Express.params.url === \'string\' && !Express.params.url.endsWith(\'/\')) {\r\n            Express.params.url += \'/\';\r\n        }\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        Express.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    request: function (query, data) {\r\n        var response,\r\n            url = Express.params.url + query,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'Authorization: Bearer \' + Express.params.token);\r\n\r\n        if (typeof Express.HTTPProxy !== \'undefined\' && Express.HTTPProxy !== \'\') {\r\n            request.setProxy(Express.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ Express Webhook ] Sending request: \' + url +\r\n            ((typeof data === \'string\') ? (\'\\n\' + data) : \'\'));\r\n\r\n        response = request.post(url, data);\r\n\r\n        Zabbix.log(4, \'[ Express Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ Express Webhook ] Failed to parse response received from Express\');\r\n                response = {};\r\n            }\r\n        }\r\n\r\n        if (response.status !== \'ok\') {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (typeof response.reason !== \'undefined\') {\r\n                message += \': \' + JSON.stringify(response.reason);\r\n            }\r\n\r\n            throw message + \'. Check debug log for more information.\';\r\n        }\r\n\r\n        return response.result;\r\n    },\r\n\r\n    postMessage: function (is_problem) {\r\n        var data,\r\n            url,\r\n            result = {tags: {}},\r\n            response;\r\n\r\n        if (is_problem) {\r\n            data = {\r\n                group_chat_id: Express.params.send_to,\r\n                notification: {\r\n                    status: \'ok\',\r\n                    body: Express.params.message\r\n                }\r\n            };\r\n            url = \'api/v4/botx/notifications/direct\';\r\n        }\r\n        else {\r\n            data = {\r\n                reply: {\r\n                    status: \'ok\',\r\n                    body: Express.params.message\r\n                }\r\n            };\r\n            url = \'api/v3/botx/events/reply_event\';\r\n\r\n            try {\r\n                var tags = JSON.parse(Express.params.tags);\r\n            }\r\n            catch (error) {\r\n                throw \'Value of "express_tags" is not JSON. Value: \' + Express.params.tags + \'.\';\r\n            }\r\n\r\n            tags.forEach(function(tag) {\r\n                if (tag.tag === \'__zbx_ex_sync_id_\' + Express.params.send_to) {\r\n                    data.source_sync_id = tag.value;\r\n                }\r\n            });\r\n\r\n            if (!data.source_sync_id) {\r\n                throw \'Cannot update data. sync_id for the provided sender is unknown.\';\r\n            }\r\n        }\r\n\r\n        response = Express.request(url, data);\r\n\r\n        if (is_problem && response.sync_id) {\r\n            result.tags[\'__zbx_ex_sync_id_\' + Express.params.send_to] = response.sync_id;\r\n\r\n            return JSON.stringify(result);\r\n        }\r\n        else {\r\n            return \'OK\';\r\n        }\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        express = {},\r\n        required_params = [\r\n            \'express_url\', \'express_send_to\', \'express_message\', \'express_tags\', \'express_token\',\r\n            \'event_source\', \'event_value\', \'event_update_status\'\r\n        ];\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'express_\')) {\r\n                express[key.substring(8)] = params[key];\r\n            }\r\n\r\n            if (required_params.indexOf(key) !== -1\r\n                    && (params[key].trim() === \'\' || params[key] === \'{ALERT.SENDTO}\')) {\r\n                throw \'Parameter "\' + key + \'" can\\\'t be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Forcing event_value and event_update_status for non trigger-based events.\r\n    if (params.event_source !== \'0\' ) {\r\n        params.event_value = \'1\';\r\n        params.event_update_status = \'0\';\r\n    }\r\n\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\') {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    Express.setParams(express);\r\n    Express.setProxy(params.HTTPProxy);\r\n\r\n    return Express.postMessage(params.event_value === \'1\' && params.event_update_status === \'0\');\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ Express Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','0','','','','0'),
('74','4','GitHub','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nvar serviceLogName = \'GitHub Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	GitHub = CWebhook;\r\n\r\nGitHub.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({\r\n		alert_message: {type: \'string\'},\r\n		alert_subject: {type: \'string\'},\r\n		github_api_version: {type: \'string\'},\r\n		github_repo: {type: \'string\'},\r\n		github_token: {type: \'string\'},\r\n		github_url: {type: \'string\', url: true},\r\n		github_user_agent: {type: \'string\'},\r\n		github_zabbix_event_priority_label_prefix: {type: \'string\', default: \'Zabbix Event Priority: \'},\r\n		github_zabbix_event_source_label_prefix: {type: \'string\', default: \'Zabbix Event Source: \'},\r\n		github_zabbix_event_status_label_prefix: {type: \'string\', default: \'Zabbix Event Status: \'},\r\n		github_zabbix_generic_label: {type: \'string\', default: \'Zabbix GitHub Webhook\'},\r\n		zabbix_url: {type: \'string\', url: true}\r\n	}, this.params);\r\n\r\n	this.request_headers = {\r\n		\'User-Agent\': this.params.github_user_agent,\r\n		\'Accept\': \'application/vnd.github+json\',\r\n		\'X-GitHub-Api-Version\': this.params.github_api_version,\r\n		\'Authorization\': \'Bearer \' + this.params.github_token\r\n	};\r\n\r\n	this.payload_data = {\r\n		title: this.params.alert_subject,\r\n		labels: [\r\n			{\r\n				name: this.params.github_zabbix_generic_label\r\n			}\r\n		]\r\n	};\r\n\r\n	this.result = {tags: {}};\r\n};\r\n\r\nfunction checkResponse(response, received_code, required_code, response_field, error_message) {\r\n	if (received_code != required_code || !CParamValidator.isDefined(response[response_field])) {\r\n		var message = error_message + \' Request failed with status code \' + received_code;\r\n\r\n		if (CParamValidator.isDefined(response.message) && Object.keys(response.message).length > 0) {\r\n			message += \': \' + response.message;\r\n		}\r\n\r\n		throw message + \' Check debug log for more information.\';\r\n	}\r\n}\r\n\r\nGitHub.prototype.createIssue = function () {\r\n	this.payload_data.body = this.params.alert_message + \'\\n\' + CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id);\r\n\r\n	this.request.addHeaders(this.request_headers);\r\n\r\n	const response = this.request.jsonRequest(\'POST\', this.params.github_url + \'/repos/\' + this.params.github_repo + \'/issues\', this.payload_data);\r\n\r\n	checkResponse(response, this.request.getStatus(), 201, \'number\', \'Cannot create GitHub issue.\');\r\n\r\n	return response;\r\n}\r\n\r\nGitHub.prototype.updateIssue = function () {\r\n	this.request.addHeaders(this.request_headers);\r\n\r\n	const response = this.request.jsonRequest(\'PATCH\', this.params.github_url + \'/repos/\' + this.params.github_repo + \'/issues/\' + this.params.github_issue_number, this.payload_data);\r\n\r\n	checkResponse(response, this.request.getStatus(), 200, \'number\', \'Cannot update GitHub issue.\');\r\n\r\n	return response;\r\n}\r\n\r\nGitHub.prototype.addIssueComment = function () {\r\n	this.payload_data = {\r\n		body: this.params.alert_message\r\n	};\r\n\r\n	this.request.addHeaders(this.request_headers);\r\n\r\n	const response = this.request.jsonRequest(\'POST\', this.params.github_url + \'/repos/\' + this.params.github_repo + \'/issues/\' + this.params.github_issue_number + \'/comments\', this.payload_data);\r\n\r\n	checkResponse(response, this.request.getStatus(), 201, \'id\', \'Cannot add comment for GitHub issue.\');\r\n\r\n	return response;\r\n}\r\n\r\nGitHub.prototype.onProblem = function (alert) {\r\n	if (CParamValidator.isMacroSet(this.params.github_issue_number)) {\r\n		return this.onUpdate(alert);\r\n	}\r\n\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n\r\n	if (this.params.event_source === \'0\') {\r\n		CParamValidator.validate({event_id: {type: \'integer\'}, trigger_id: {type: \'integer\'}}, this.params);\r\n	}\r\n\r\n	this.payload_data.labels.push({name: this.params.github_zabbix_event_source_label_prefix + alert.source});\r\n\r\n	this.payload_data.labels.push({name: this.params.github_zabbix_event_status_label_prefix + \'Problem\'});\r\n\r\n	if (!CParamValidator.isEmpty(this.params.event_severity) && CParamValidator.isMacroSet(this.params.event_severity, \'EVENT.SEVERITY\')) {\r\n		this.payload_data.labels.push({name: this.params.github_zabbix_event_priority_label_prefix + this.params.event_severity});\r\n	}\r\n\r\n	const response = this.createIssue();\r\n\r\n	this.result.tags = {\r\n		__zbx_github_issue_number: response.number,\r\n		__zbx_github_repo: this.params.github_repo,\r\n		__zbx_github_link: response.html_url\r\n	};\r\n\r\n	return this.result;\r\n}\r\n\r\nGitHub.prototype.onUpdate = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n\r\n	if (!CParamValidator.isMacroSet(this.params.github_issue_number)) {\r\n		throw "Failed to update the existing issue: no issue number was received."\r\n	}\r\n\r\n	this.payload_data.labels.push({name: this.params.github_zabbix_event_source_label_prefix + alert.source});\r\n\r\n	if (this.params.event_value === \'0\') {\r\n		this.payload_data.labels.push({name: this.params.github_zabbix_event_status_label_prefix + \'Resolved\'});\r\n	} else {\r\n		this.payload_data.labels.push({name: this.params.github_zabbix_event_status_label_prefix + \'Problem\'});\r\n	}\r\n\r\n	if (!CParamValidator.isEmpty(this.params.event_severity) && CParamValidator.isMacroSet(this.params.event_severity, \'EVENT.SEVERITY\')) {\r\n		this.payload_data.labels.push({name: this.params.github_zabbix_event_priority_label_prefix + this.params.event_severity});\r\n	}\r\n\r\n	this.updateIssue();\r\n\r\n	this.request.clearHeader();\r\n	this.addIssueComment();\r\n\r\n	return this.result;\r\n}\r\n\r\nGitHub.prototype.onResolve = function (alert) {\r\n	return this.onUpdate(alert);\r\n}\r\n\r\nGitHub.prototype.onDiscovery = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n\r\n	this.payload_data.labels.push({name: this.params.github_zabbix_event_source_label_prefix + alert.source});\r\n\r\n	this.createIssue();\r\n\r\n	return this.result;\r\n}\r\n\r\nGitHub.prototype.onAutoreg = function (alert) {\r\n	return this.onDiscovery(alert);\r\n}\r\n\r\ntry {\r\n	var hook = new GitHub(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_github_link}','Github: Issue {EVENT.TAGS.__zbx_github_issue_number}','This media type integrates your Zabbix installation with GitHub using the Zabbix webhook feature.\r\n\r\nGitHub configuration:\r\n\r\n1. Create an access token.\r\n\r\nOne of the simplest ways to send authenticated requests is to use a personal access token - either a classic or a fine-grained one:\r\nhttps://docs.github.com/en/rest/authentication/authenticating-to-the-rest-api?apiVersion=2022-11-28#authenticating-with-a-personal-access-token\r\n\r\nClassic personal access token\r\n\r\nYou can create a new classic personal access token by following the instructions in the official documentation:\r\nhttps://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic\r\n\r\nThe token user must have a permission to create issues and issue comments in the desired repositories. For webhook to work on private repositories, the "repo" scope must be set in token settings to have full control of private repositories.\r\n\r\nAdditional information about OAuth scopes is available in the official documentation:\r\nhttps://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps#available-scopes\r\n\r\nFine-grained personal access token\r\n\r\nAlternatively, you can use a fine-grained personal access token:\r\nhttps://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token\r\n\r\nIn order to use fine-grained tokens to monitor organization-owned repositories, organizations must opt in to fine-grained personal access tokens and set up a personal access token policy:\r\nhttps://docs.github.com/en/organizations/managing-programmatic-access-to-your-organization/setting-a-personal-access-token-policy-for-your-organization\r\n\r\nThe fine-grained token needs to have the following permission set to provide access to the repository issues:\r\n- "Issues" repository permissions (write)\r\n\r\n2. Copy and save the created token somewhere, as it will be shown only once for security reasons.\r\n\r\nZabbix configuration:\r\n\r\n1. Before you can start using Zammad webhook, set up the global macro "{$ZABBIX.URL}":\r\n- In the Zabbix web interface, go to "Administration" → "Macros" section in the dropdown menu in the top left corner.\r\n- Set up the global macro "{$ZABBIX.URL}" which will contain the URL to the Zabbix frontend. The URL should be either an IP address, a fully qualified domain name, or localhost.\r\n- Specifying a protocol is mandatory, whereas the port is optional. Depending on the web server configuration you might also need to append "/zabbix" to the end of URL. Good examples:\r\n  - http://zabbix.com\r\n  - https://zabbix.lan/zabbix\r\n  - http://server.zabbix.lan/\r\n  - http://localhost\r\n  - http://127.0.0.1:8080\r\n- Bad examples:\r\n  - zabbix.com\r\n  - http://zabbix/\r\n\r\n2. Set the "github_token" webhook parameter value to the access token that you created previously.\r\n\r\nYou can also adjust the issue labels created by the webhook in the following parameters:\r\n- github_zabbix_event_priority_label_prefix - the prefix for the issue label that displays the Zabbix event priority in the supported event sources. It is set to "Zabbix Event Priority: " by default.\r\n- github_zabbix_event_source_label_prefix - the prefix for the issue label that displays the Zabbix event source. It is set to "Zabbix Event Source: " by default.\r\n- github_zabbix_event_status_label_prefix - the prefix for the issue label that displays the Zabbix event status. It is set to "Zabbix Event Status: " by default.\r\n- github_zabbix_generic_label - the label that is added to all issues created by the webhook. It is set to "Zabbix GitHub Webhook" by default.\r\n\r\nNote that the webhook will reuse the labels with the same name that already exist in the repository (including the color, so it can changed from the default value for new labels in GitHub, if needed). Also, the labels are replaced when the issue is updated, so any user-added labels will be removed.\r\n\r\n4. Create a Zabbix user and add media:\r\n- If you want to create a new user, go to the "Users" → "Users" section, click the "Create user" button in the top right corner. In the "User" tab, fill in all required fields (marked with red asterisks).\r\n- In the "Media" tab, add a new media and select "Zammad" type from the drop-down list. In field "Send to" specify the full repo name (owner/project name) e.g. johndoe/example-project.\r\n- Make sure this user has access to all hosts for which you would like problem notifications to be sent to GitHub.\r\n\r\n5. Great! You can now start using this media type in actions and create GitHub issues!\r\n\r\nYou can find the latest version of this media and additional information in the official Zabbix repository:\r\nhttps://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/github','0'),
('75','4','GLPi','','','','','','','','25','0','0','0','0','1','1','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nconst serviceLogName = \'GLPi Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	GLPi = CWebhook;\r\n\r\nGLPi.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({\r\n		alert_message: { type: \'string\' },\r\n		alert_subject: { type: \'string\' },\r\n		zabbix_url: { type: \'string\', url: true },\r\n		glpi_url: { type: \'string\', url: true },\r\n		glpi_user_token: { type: \'string\' }\r\n	}, this.params);\r\n\r\n	this.params.use_app_token = false;\r\n\r\n	if (CParamValidator.isDefined(this.params.glpi_app_token) && !CParamValidator.isEmpty(this.params.glpi_app_token)) {\r\n		this.params.use_app_token = true;\r\n	}\r\n\r\n	if (this.params.event_source === \'0\') {\r\n		CParamValidator.validate({ trigger_id: { type: \'integer\' }, event_id: { type: \'integer\' } }, this.params);\r\n		this.params.zabbix_url = CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id);\r\n	}\r\n\r\n	if (params.event_value != \'0\' && CParamValidator.isMacroSet(this.params.glpi_problem_id)) {\r\n		this.params.event_update_status = \'1\';\r\n	}\r\n\r\n	this.data = {\r\n		input: {\r\n			name: this.params.alert_subject,\r\n			urgency: (this.params.event_nseverity = isNaN(Number(this.params.event_nseverity)) ? 2 : this.params.event_nseverity)\r\n		}\r\n	};\r\n\r\n	this.dataFollowup = {\r\n		input: {\r\n			items_id: this.params.glpi_problem_id,\r\n			itemtype: \'Problem\',\r\n			content: this.params.alert_message + \'<br> <a href=\' + this.params.zabbix_url + \'>Link to problem in Zabbix</a>\',\r\n		}\r\n	};\r\n\r\n	this.result = { tags: {} };\r\n}\r\n\r\nGLPi.prototype.getAuthToken = function () {\r\n\r\n	this.request.addHeaders(\'Authorization: user_token \' + this.params.glpi_user_token);\r\n	if (this.params.use_app_token) {\r\n		this.request.addHeaders(\'App-Token: \' + this.params.glpi_app_token);\r\n	}\r\n	var response = this.request.jsonRequest(\'post\', this.params.glpi_url + \'/apirest.php/initSession\');\r\n\r\n	if ((this.request.getStatus() !== 200 && this.request.getStatus() !== 201)) {\r\n		Logger.log(Logger.INFO, \'HTTP code: \' + this.request.getStatus());\r\n		if (CParamValidator.isType(response.description, \'string\')) {\r\n			throw response.description;\r\n		}\r\n		else {\r\n			Logger.log(Logger.INFO, \'Request not successful. Received response: \' + JSON.stringify(response));\r\n			throw \'Unknown INFO. Check debug log for more information.\';\r\n		}\r\n	}\r\n	if (!CParamValidator.isType(response.session_token, \'string\') || CParamValidator.isEmpty(response.session_token)) {\r\n		Logger.log(Logger.INFO, \'Check getting GLPi sessionToken: \' + response.session_token);\r\n		throw \'Required GLPi sessionToken is not received.\';\r\n	}\r\n\r\n	return response.session_token;\r\n}\r\n\r\nGLPi.prototype.sendRequest = function (method, path, data) {\r\n\r\n	this.request.clearHeader();\r\n	this.request.addHeaders(\'Session-Token:\' + this.params.authToken);\r\n	if (this.params.use_app_token) {\r\n		this.request.addHeaders(\'App-Token: \' + this.params.glpi_app_token);\r\n	}\r\n	var response = this.request.jsonRequest(method, this.params.glpi_url + path, data);\r\n\r\n	if ((this.request.getStatus() !== 200 && this.request.getStatus() !== 201)) {\r\n		Logger.log(Logger.INFO, \'HTTP code: \' + this.request.getStatus());\r\n		if (CParamValidator.isType(response.description, \'string\')) {\r\n			throw response.description;\r\n		}\r\n		else {\r\n			Logger.log(Logger.INFO, \'Request not successful. Received response: \' + JSON.stringify(response));\r\n			throw \'Unknown INFO. Check debug log for more information.\';\r\n		}\r\n	}\r\n\r\n	return response;\r\n}\r\n\r\nGLPi.prototype.createProblem = function (status) {\r\n	this.data.input.content = this.params.alert_message + \'<br> <a href=\' + this.params.zabbix_url + \'>Link to problem in Zabbix</a>\';\r\n\r\n	if (CParamValidator.isDefined(status)) {\r\n		this.data.input.status = status;\r\n	}\r\n\r\n	var response = this.sendRequest(\'post\', \'/apirest.php/Problem/\', this.data);\r\n\r\n	if (!CParamValidator.isDefined(response.id)) {\r\n		throw \'Cannot create GPLi problem. Check debug log for more information.\';\r\n	}\r\n\r\n	return response.id\r\n}\r\n\r\nGLPi.prototype.updateProblem = function (status) {\r\n	CParamValidator.validate({ glpi_problem_id: { type: \'string\' } }, this.params);\r\n	this.data.id = this.params.glpi_problem_id;\r\n\r\n	if (CParamValidator.isDefined(status)) {\r\n		this.data.input.status = status;\r\n	}\r\n\r\n	this.sendRequest(\'put\', \'/apirest.php/Problem/\' + this.params.glpi_problem_id, this.data);\r\n	this.sendRequest(\'post\', \'/apirest.php/Problem/\' + this.params.glpi_problem_id + \'/ITILFollowup\', this.dataFollowup);\r\n}\r\n\r\nGLPi.prototype.onProblem = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	const problem_id = this.createProblem(1)\r\n\r\n	this.result.tags.__zbx_glpi_problem_id = problem_id;\r\n	this.result.tags.__zbx_glpi_link = this.params.glpi_url + \'/front/problem.form.php?id=\' + problem_id;\r\n\r\n	return this.result;\r\n}\r\n\r\nGLPi.prototype.onUpdate = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	this.updateProblem();\r\n\r\n	return this.result;\r\n}\r\n\r\nGLPi.prototype.onResolve = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	this.updateProblem(5);\r\n\r\n	return this.result;\r\n}\r\n\r\nGLPi.prototype.onDiscovery = function () {\r\n	return this.createProblem();\r\n}\r\n\r\nGLPi.prototype.onAutoreg = function () {\r\n	return this.createProblem();\r\n}\r\n\r\ntry {\r\n	var hook = new GLPi(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	hook.params.authToken = hook.getAuthToken();\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_glpi_link}','GLPi: Problem {EVENT.TAGS.__zbx_glpi_problem_id}','This media type integrates your Zabbix installation with your GLPi installation using the Zabbix webhook feature.\r\n\r\nGLPi configuration:\r\n\r\n1. Enable access to the GLPi REST API:\r\n- In the GLPi web interface, go to "Setup" → "General" → "API".\r\n- Set the "Enable Rest API" and "Enable Rest API" options to "Yes" and click the "Save" button.\r\n\r\n2. Add a new API client:\r\n- Click the "Add API client" button.\r\n- Specify the API client name and set the "Active" option to "Yes".\r\n- For security reasons, you may want to restrict the API client to the IP address of Zabbix server and/or create an additional application token (will be generated by default; you can uncheck the "Regenerate" checkbox if you don\'t want to use it).\r\n- Click the "Add" button.\r\n- If you\'ve opted to create an application token, open the settings of the created API client, and then copy and save the generated application token.\r\n\r\n3. Create a new user profile with permissions to create problems and followups (alternatively, you can use an existing profile with sufficient privileges):\r\n- Go to "Administration" → "Profiles" and click the "Add" button on the top of the page.\r\n- Specify the profile name and set the "Profile\'s Interface" option to "Standard Interface", and then click the "Add" button.\r\n- Open the created profile and click the "Assistance" tab.\r\n- Set the "Add followup (requester)" permission for the "Followups" line in the "Followups/Tasks" section.\r\n- Set the "Update", "Create", and "See all" permissions in the "Problems" section.\r\n- Click the "Save" button.\r\n\r\n4. Create a new user:\r\n- Go to "Administration" → "Users" and click the "Add User" button on the top of the page.\r\n- Specify the user login and set the "Profiles" option to the profile that you created in the previous step (or any other existing profile with permissions to create problems and followups).\r\n- Click the "Add" button.\r\n- Open the profile of the created user and check the "Regenerate" checkbox of the "API token" option; click "Save".\r\n- Copy and save the generated user API token.\r\n\r\nZabbix configuration:\r\n\r\n1. Before you can start using the GLPi webhook, set the global macro "{$ZABBIX.URL}":\r\n- In the Zabbix web interface, go to "Administration" → "Macros" in the top-left drop-down menu.\r\n- Set the global macro "{$ZABBIX.URL}" to the URL of the Zabbix frontend. The URL should be either an IP address, a fully qualified domain name, or localhost.\r\n- Specifying a protocol is mandatory, whereas the port is optional. Depending on the web server configuration, you might also need to append "/zabbix" to the end of URL. Good examples:\r\n  - http://zabbix.com\r\n  - https://zabbix.lan/zabbix\r\n  - http://server.zabbix.lan/\r\n  - http://localhost\r\n  - http://127.0.0.1:8080\r\n- Bad examples:\r\n  - zabbix.com\r\n  - http://zabbix/\r\n\r\n2. Set the following webhook parameters:\r\n- glpi_app_token - if you\'ve opted to use an application token during the creation of API client, specify it here; otherwise leave it empty\r\n- glpi_url - the frontend URL of your GLPi installation\r\n- glpi_user_token - the user token that was generated during creation of GLPi user\r\n\r\n3. Click the "Enabled" checkbox to enable the media type and click the "Update" button to save the webhook settings.\r\n\r\n4. Create a Zabbix user and add media:\r\n- To create a new user, go to the "Users" → "Users" section, click the "Create user" button in the top right corner. In the "User" tab, fill in all required fields (marked with red asterisks).\r\n- In the "Media" tab, click "Add" and select the type "GLPi" from the drop-down list. Add any value in the "Send to" field: it is not used in the webhook, but is required.\r\n- Make sure this user has access to all hosts for which you would like problem notifications to be sent to GLPi.\r\n\r\n5. Done! You can now start using this media type in actions and create problem items in GLPi.\r\n\r\nYou can find the latest version of this media and additional information in the official Zabbix repository:\r\nhttps://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/glpi','0'),
('76','4','iLert','','','','','','','','25','0','0','0','0','1','3','10s','1','try {\r\n    var result = { tags: {} },\r\n        params = JSON.parse(value),\r\n        req = new HttpRequest(),\r\n        resp = \'\';\r\n\r\n    if (typeof params.HTTPProxy === \'string\' && params.HTTPProxy.trim() !== \'\') {\r\n        req.setProxy(params.HTTPProxy);\r\n    }\r\n    var alertSourceKey = params[\'.ILERT.ALERT.SOURCE.KEY\'];\r\n    if (!alertSourceKey || (typeof alertSourceKey === \'string\' && alertSourceKey.trim() === \'\')) {\r\n        throw \'incorrect value for variable "ILERT.ALERT.SOURCE.KEY". The value must be a non-empty string.\';\r\n    }\r\n    delete params[\'.ILERT.ALERT.SOURCE.KEY\'];\r\n    \r\n    var ilertApiBaseURL = "https://api.ilert.com";\r\n    var reqURL = encodeURI(ilertApiBaseURL + "/api/v1/events/zabbix-mt/" + alertSourceKey)\r\n\r\n    var incidentKey = "zabbix-" + params[\'EVENT.ID\'];\r\n    var incidentViewURL = ilertApiBaseURL + "/api/v1/incidents/resolve-ik/" + alertSourceKey + "/" + incidentKey;\r\n\r\n    req.addHeader(\'Accept: application/json\');\r\n    req.addHeader(\'Content-Type: application/json\');\r\n\r\n    Zabbix.log(4, \'[iLert Webhook] Sending request:\' + JSON.stringify(params));\r\n    resp = req.post(reqURL, JSON.stringify(params));\r\n    Zabbix.log(4, \'[iLert Webhook] Receiving response:\' + resp);\r\n\r\n    try {\r\n        resp = JSON.parse(resp);\r\n    }\r\n    catch (error) {\r\n        throw \'incorrect response. iLert returned a non-JSON object.\';\r\n    }\r\n\r\n    if (req.getStatus() == 200) {\r\n        result.tags.__ilert_incident_url = incidentViewURL;\r\n        return JSON.stringify(result);\r\n    }\r\n\r\n    if (req.getStatus() == 400 && typeof resp === \'object\' && typeof resp.code === \'string\') {\r\n        if (resp.code === \'NO_OPEN_INCIDENT_WITH_KEY\') {\r\n          return JSON.stringify(result);\r\n        }\r\n        if (resp.code === \'INCIDENT_ALREADY_ACCEPTED\') {\r\n          result.tags.__ilert_incident_url = incidentViewURL;\r\n          return JSON.stringify(result);\r\n        }\r\n    }\r\n\r\n    if (typeof resp === \'object\' && typeof resp.message === \'string\') {\r\n        throw resp.message;\r\n    }\r\n    else {\r\n        throw \'Unknown error.\';\r\n    }\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[iLert Webhook] Notification failed : \' + error);\r\n    throw \'iLert notification failed : \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__ilert_incident_url}','iLert incident','Please refer to https://docs.ilert.com/integrations/zabbix/native \r\n  \r\nSet global macro {$ZABBIX.URL} with your Zabbix server URL.\r\nAdd a dedicated user with the media type "iLert". You can also rewrite the incident summary via ".ILERT.INCIDENT.SUMMARY" parameter or leave it empty to use the standard pattern.','0'),
('77','4','iTop','','','','','','','','25','0','0','0','0','1','3','10s','1','var Itop = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        if (params.log !== \'private_log\' && params.log !== \'public_log\') {\r\n            throw \'Incorrect "itop_log" parameter given: \' + params.log + \'\\nMust be "private_log" or "public_log".\';\r\n        }\r\n\r\n        Itop.params = params;\r\n        if (typeof Itop.params.url === \'string\') {\r\n            if (!Itop.params.url.endsWith(\'/\')) {\r\n                Itop.params.url += \'/\';\r\n            }\r\n\r\n            Itop.params.url += \'webservices/rest.php?version=\' + encodeURIComponent(Itop.params.api_version);\r\n        }\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        Itop.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    setCreatePayload: function () {\r\n        json_data.operation = \'core/create\';\r\n        json_data.fields.org_id = Itop.params.organization_id;\r\n        json_data.fields.title = params.alert_subject;\r\n        json_data.fields.description = params.alert_message.replace(\'<\', \'&lt;\')\r\n            .replace(\'>\', \'&gt;\')\r\n            .replace(/(?:\\r\\n|\\r|\\n)/g, \'<br>\');\r\n    },\r\n\r\n    setUpdatePayload: function () {\r\n        json_data.operation = \'core/update\';\r\n        json_data.key = Itop.params.id;\r\n        json_data.fields.title = params.alert_subject;\r\n        json_data.fields[Itop.params.log] = {\r\n            add_item: {\r\n                message: params.alert_subject + \'\\n\' + params.alert_message,\r\n                format: \'text\'\r\n            }\r\n        };\r\n    },\r\n\r\n    request: function (data) {\r\n        [\'url\', \'user\', \'password\', \'organization_id\', \'class\', \'api_version\', \'id\'].forEach(function (field) {\r\n            if (typeof Itop.params !== \'object\' || typeof Itop.params[field] === \'undefined\'\r\n                    || Itop.params[field] === \'\' ) {\r\n                throw \'Required Itop param is not set: "itop_\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = Itop.params.url,\r\n            request = new HttpRequest(),\r\n            object;\r\n\r\n        request.addHeader(\'Content-Type: multipart/form-data\');\r\n        request.addHeader(\'Authorization: Basic \' + btoa(Itop.params.user + \':\' + Itop.params.password));\r\n\r\n        if (Itop.HTTPProxy) {\r\n            request.setProxy(Itop.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ iTop Webhook ] Sending request: \' + url + \'&json_data=\' + data);\r\n\r\n        response = request.post(url + \'&json_data=\' + encodeURIComponent(data));\r\n\r\n        Zabbix.log(4, \'[ iTop Webhook ] Received response with status code \' + request.getStatus() + \'\\n\' + response);\r\n\r\n        try {\r\n            response = JSON.parse(response);\r\n        }\r\n        catch (error) {\r\n            Zabbix.log(4, \'[ iTop Webhook ] Failed to parse response received from iTop\');\r\n            throw \'Failed to parse response received from iTop.\\nRequest status code \' +\r\n                    request.getStatus() + \'. Check debug log for more information.\';\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            throw \'Request failed with status code \' + request.getStatus() + \'. Check debug log for more information.\';\r\n        }\r\n        else if (typeof response.code !== \'undefined\' && response.code !== 0) {\r\n            throw \'Request failed with iTop code \' + response.code + \': \' +\r\n                    JSON.stringify(response.message) + \'. Check debug log for more information.\';\r\n        }\r\n        else {\r\n            Object.keys(response.objects)\r\n                .forEach(function (key) {\r\n                    object = response.objects[key];\r\n                });\r\n    \r\n            return {\r\n                status: request.getStatus(),\r\n                response: object.fields\r\n            };\r\n        }\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        json_data = {},\r\n        itop_params = {},\r\n        result = {tags: {}},\r\n        required_params = [\r\n            \'alert_subject\', \'summary\', \'event_recovery_value\',\r\n            \'event_source\', \'event_value\', \'action_name\'\r\n        ];\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'itop_\')) {\r\n                itop_params[key.substring(5)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key] === \'\') {\r\n                throw \'Parameter "\' + key + \'" can\\\'t be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n            && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_recovery_value === \'0\') {\r\n        throw \'Recovery operations are supported only for trigger-based actions.\';\r\n    }\r\n\r\n    Itop.setParams(itop_params);\r\n    Itop.setProxy(params.HTTPProxy);\r\n\r\n    json_data.operation = \'\';\r\n    json_data.class = Itop.params.class;\r\n    json_data.comment = Itop.params.comment;\r\n    json_data.output_fields = \'id, friendlyname\';\r\n    json_data.fields = {};\r\n\r\n    // Create issue for non trigger-based events.\r\n    if (params.event_source !== \'0\' && params.event_recovery_value !== \'0\') {\r\n        Itop.setCreatePayload();\r\n        Itop.request(json_data);\r\n    }\r\n    // Create issue for trigger-based events.\r\n    else if (params.event_value === \'1\' && params.event_update_status === \'0\'\r\n            && (Itop.params.id === \'{EVENT.TAGS.__zbx_itop_id}\' || Itop.params.id === \'*UNKNOWN*\')) {\r\n        Itop.setCreatePayload();\r\n\r\n        var response = Itop.request(json_data);\r\n\r\n        result.tags.__zbx_itop_id = response.response.id;\r\n        result.tags.__zbx_itop_key = response.response.friendlyname;\r\n        result.tags.__zbx_itop_link = params.itop_url + (params.itop_url.endsWith(\'/\') ? \'\' : \'/\') +\r\n                \'pages/UI.php?operation=details&class=\' + encodeURIComponent(Itop.params.class) + \'&id=\' +\r\n                encodeURIComponent(response.response.id);\r\n    }\r\n    // Update created issue for trigger-based event.\r\n    else {\r\n        if (Itop.params.id === \'{EVENT.TAGS.__zbx_itop_id}\' || Itop.params.id === \'*UNKNOWN*\') {\r\n            throw \'Incorrect iTop ticket ID given: \' + Itop.params.id;\r\n        }\r\n        Itop.setUpdatePayload();\r\n        Itop.request(json_data);\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ iTop Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_itop_link}','iTop: {EVENT.TAGS.__zbx_itop_key}','','0'),
('78','4','Jira','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nvar ZABBIX_SEVERITY_MAP = ["not_classified", "information", "warning", "average", "high", "disaster"];\r\n\r\nvar serviceLogName = \'Jira Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	Jira = CWebhook;\r\n\r\nJira.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({\r\n		jira_url: { type: \'string\', url: true},\r\n		jira_user: { type: \'string\' },\r\n		jira_password: { type: \'string\' },\r\n		jira_issue_type: { type: \'string\' },\r\n		jira_project_key: { type: \'string\' },\r\n		event_source: { type: \'string\' },\r\n		alert_subject: { type: \'string\' },\r\n		alert_message: { type: \'string\' },\r\n		event_nseverity: { type: \'integer\', default: 0 }\r\n	}, this.params);\r\n\r\n	this.priority = this.params.event_source == 3 ? this.params.jira_priority_internal : this.params[\'severity_\' + ZABBIX_SEVERITY_MAP[this.params.event_nseverity]];\r\n	this.params.event_tags_json = parseTags(this.params.event_tags_json, false);\r\n\r\n	if (this.params.event_tags_json.length > 0) {\r\n		this.labels = setLabels(this.params.event_tags_json);\r\n	}\r\n\r\n	parseOptionalFields();\r\n\r\n	this.result = { tags: {} };\r\n}\r\n\r\nfunction escapeMarkup(str) {\r\n	var length = str.length,\r\n		result = \'\',\r\n		markup = [\'{\', \'|\', \'}\', \'~\', \'_\', \'\\\\\', \'[\', \']\', \'^\', \'<\', \'>\', \'?\', \'!\', \'#\', \'+\', \'*\', \'&\'];\r\n\r\n	for (var i = 0; i < length; i++) {\r\n		var char = str[i];\r\n		result += (markup.indexOf(char) !== -1) ? (\'&#\' + str[i].charCodeAt() + \';\') : char;\r\n	}\r\n\r\n	return result;\r\n}\r\n\r\nfunction parseOptionalFields() {\r\n	this.params.customfields = {};\r\n	this.params.components = [];\r\n\r\n	Object.keys(this.params).forEach(function (key) {\r\n		if (key.startsWith(\'customfield_\')) {\r\n			this.params.customfields[key] = this.params[key];\r\n		}\r\n\r\n		if (key.startsWith(\'component_\')) {\r\n			this.params.components.push({"name": this.params[key]})\r\n		}\r\n	});\r\n}\r\n\r\nJira.prototype.addCustomFields = function (data) {\r\n	if (typeof this.params.customfields === \'object\' && Object.keys(this.params.customfields).length) {\r\n		var schemaData = this.sendRequest(\'GET\', \'/rest/api/latest/field\'),\r\n			schema = {};\r\n\r\n		schemaData.forEach(function (item) {\r\n			schema[item.id] = item.schema;\r\n		});\r\n\r\n		Object.keys(this.params.customfields).forEach(function (field) {\r\n			if (typeof schema[field] === \'object\' && schema[field].type) {				\r\n				const type = schema[field].type;\r\n\r\n				if (type === \'number\') {\r\n					data.fields[field] = parseInt(this.params.customfields[field]);\r\n				}\r\n				else if (type === \'string\' && schema[field][\'custom\'].split(\':\')[1] === \'url\') {\r\n					if (this.params.customfields[field] === \'zabbix_url\') {\r\n						data.fields[field] = CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id);\r\n					} else {\r\n						data.fields[field] = this.params.customfields[field];\r\n					}\r\n				}\r\n				else if (type === \'date\') {\r\n					if (this.params.customfields[field].match(/\\d+[.-]\\d+[.-]\\d+/) !== null) {\r\n						data.fields[field] = this.params.customfields[field].replace(/\\./g, \'-\');\r\n					}\r\n				}\r\n				else if (type === \'datetime\') {\r\n					if (this.params.customfields[field].match(/\\d+[.-]\\d+[.-]\\d+T\\d+:\\d+:\\d+/) !== null) {\r\n						data.fields[field] = this.params.customfields[field].replace(/\\./g, \'-\');\r\n					}\r\n				}\r\n				else if (type === \'option\') {\r\n					data.fields[field] = { \'value\': this.params.customfields[field] };\r\n				}\r\n				else if (type === \'array\') {\r\n					if (schema[field].items === \'option\') {\r\n						const valuesList = this.params.customfields[field].split(\',\');\r\n						data.fields[field] = [];\r\n						valuesList.forEach(function (val) {\r\n							data.fields[field].push({\'value\': val})\r\n						});\r\n					}\r\n					else {\r\n						data.fields[field] = [this.params.customfields[field]];\r\n					}\r\n				}\r\n				else {\r\n					data.fields[field] = this.params.customfields[field];\r\n				}\r\n			}\r\n		});\r\n	}\r\n	else {\r\n		Logger.log(Logger.WARN, \'No customfields found.\');\r\n	}\r\n\r\n	return data;\r\n}\r\n\r\nfunction parseTags(event_tags) {\r\n	try {\r\n		return JSON.parse(event_tags);\r\n	}\r\n	catch (error) {\r\n		if (this.params.event_source == 0 || this.params.event_source > 2) {\r\n			Logger.log(Logger.WARN, \'No event tags were found. Should be an object. Received event tags: "\' + event_tags + \'".\');\r\n		}\r\n		return [];\r\n	}\r\n}\r\n\r\nfunction getTagValue(tags, key, throw_on_fail) {\r\n	for (i in tags) {\r\n		if (tags[i].tag === key) {\r\n			return tags[i].value\r\n		}\r\n	}\r\n\r\n	if (!throw_on_fail) {\r\n		return false;\r\n	} else {\r\n		throw \'Tag "\' + key + \'" is not in the event tag list.\'\r\n	}\r\n};\r\n\r\nfunction setLabels(event_tags_json) {\r\n	var buffer = [];\r\n\r\n	event_tags_json.forEach(function (tag) {\r\n		if (typeof tag.tag !== \'undefined\' && typeof tag.value !== \'undefined\' && !tag.tag.startsWith(\'__zbx\')) {\r\n			label = (tag.tag + (tag.value ? (\':\' + tag.value) : \'\')).replace(/\\s/g, \'_\');\r\n			if (label.length < 256) {\r\n				buffer.push(label);\r\n			}\r\n		}\r\n	});\r\n\r\n	if (buffer.length === 0) {\r\n		Logger.log(Logger.WARN, \'No labels were set.\');\r\n	}\r\n\r\n	return buffer;\r\n}\r\n\r\nJira.prototype.commentIssue = function (issue_key) {\r\n	var data = {\r\n		body: this.params.alert_message,\r\n	};\r\n	this.sendRequest(\'POST\', \'/rest/api/latest/issue/\' + encodeURIComponent(issue_key) + \'/comment\', data);\r\n}\r\n\r\nJira.prototype.sendRequest = function (method, path, data) {\r\n	this.request.clearHeader();\r\n	this.request.addHeaders(\'Authorization: Basic \' + btoa(this.params.jira_user + \':\' + this.params.jira_password));\r\n\r\n	var response = this.request.jsonRequest(method, this.params.jira_url + path, data);\r\n\r\n	if ((this.request.getStatus() !== 200 && this.request.getStatus() !== 201)) {\r\n		Logger.log(Logger.WARN, \'HTTP code: \' + this.request.getStatus());\r\n		if (CParamValidator.isType(response.description, \'string\')) {\r\n			throw response.description;\r\n		}\r\n		else {\r\n			Logger.log(Logger.WARN, \'Request not successful. Received response: \' + JSON.stringify(response));\r\n			throw \'Unknown error. Check debug log for more information.\';\r\n		}\r\n	}\r\n\r\n	return response;\r\n}\r\n\r\nJira.prototype.onProblem = function (alert) {\r\n	if (this.params.event_tags_json.length > 0 && getTagValue(this.params.event_tags_json, \'__zbx_jira_issuekey\', false) !== false) {\r\n		return this.onUpdate(alert, true);\r\n	}\r\n\r\n	var data = {\r\n		fields: {\r\n			project: {\r\n				key: this.params.jira_project_key\r\n			},\r\n			issuetype: {\r\n				name: this.params.jira_issue_type\r\n			},\r\n			summary: this.params.alert_subject,\r\n			description: this.params.alert_message,\r\n			priority: {\r\n				"name": this.priority\r\n			}\r\n		}\r\n	};\r\n\r\n	if (this.labels && this.labels.length > 0) {\r\n		data.fields.labels = this.labels;\r\n	}\r\n\r\n	if (this.params.components && this.params.components.length > 0) {\r\n		data.fields.components = this.params.components;\r\n	}\r\n\r\n	var response = this.sendRequest(\'POST\', \'/rest/api/latest/issue\', this.addCustomFields(data));\r\n	this.result.tags = {\r\n		__zbx_jira_issuekey: response.key,\r\n		__zbx_jira_issuelink: this.params.jira_url + \'/browse/\' + response.key\r\n	}\r\n	return this.result;\r\n}\r\n\r\nJira.prototype.onUpdate = function (alert, dontUpdatePriority) {\r\n	var data = {\r\n		fields: {\r\n			summary: this.params.alert_subject,\r\n			priority: {\r\n				"name": this.priority\r\n			}\r\n		}\r\n	};\r\n\r\n	if (dontUpdatePriority && this.params.event_source != 0) {\r\n		delete data[\'fields\'][\'priority\'];\r\n	}\r\n\r\n	var jira_issue_key = getTagValue(this.params.event_tags_json, \'__zbx_jira_issuekey\', true);\r\n	this.sendRequest(\'PUT\', \'/rest/api/latest/issue/\' + encodeURIComponent(jira_issue_key) + \'?returnIssue=true\', this.addCustomFields(data));\r\n	this.commentIssue(jira_issue_key);\r\n\r\n	return this.result;\r\n}\r\n\r\nJira.prototype.onResolve = function (alert) {\r\n	return this.onUpdate(alert, true);\r\n}\r\n\r\nJira.prototype.onDiscovery = function (alert) {\r\n	this.priority = this.params.jira_priority_discovery;\r\n	return this.onProblem(alert);\r\n}\r\n\r\nJira.prototype.onAutoreg = function (alert) {\r\n	this.priority = this.params.jira_priority_autoregistration;\r\n	return this.onProblem(alert);\r\n}\r\n\r\ntry {\r\n	var hook = new Jira(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_jira_issuelink}','Jira: {EVENT.TAGS.__zbx_jira_issuekey}','https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/jira\r\n\r\n1. To make this integration work, you will need the following from Jira:\r\n  * Jira instance URL;\r\n  * Jira project key and issue type that the issues created by Zabbix will use;\r\n  * Jira username and password or API token. API token is strongly recommended and can be obtained at https://id.atlassian.com/manage/api-tokens.\r\n2. In the Zabbix web interface, go to Administration → Macros section. Set up the global macro "{$ZABBIX.URL}" which will contain the URL to the Zabbix frontend.\r\n3. On this page replace the placeholder \'<...>\' values with the ones from the step #1.\r\n4. In Zabbix, you need to have a Zabbix user and add Media with the Jira media type. Make sure this user has access to all hosts for which you would like problem issues to be created in Jira.','0'),
('79','4','Jira Service Management','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nvar ZABBIX_SEVERITY_MAP = ["not_classified", "information", "warning", "average", "high", "disaster"];\r\n\r\nvar serviceLogName = \'Jira Service Management Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	Jira = CWebhook;\r\n\r\nJira.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({\r\n		jira_url: { type: \'string\', url: true},\r\n		jira_user: { type: \'string\' },\r\n		jira_password: { type: \'string\' },\r\n		jira_request_type_id: { type: \'string\' },\r\n		jira_servicedesk_id: { type: \'string\' },\r\n		issue_comments_public: {type: \'boolean\', default: false},\r\n		event_source: { type: \'string\' },\r\n		alert_subject: { type: \'string\' },\r\n		alert_message: { type: \'string\' },\r\n		event_nseverity: { type: \'integer\', default: 0 }\r\n	}, this.params);\r\n\r\n	this.priority = this.params.event_source == 3 ? this.params.jira_priority_internal : this.params[\'severity_\' + ZABBIX_SEVERITY_MAP[this.params.event_nseverity]];\r\n	this.params.event_tags_json = parseTags(this.params.event_tags_json, false);\r\n\r\n	if (this.params.event_tags_json.length > 0) {\r\n		this.labels = setLabels(this.params.event_tags_json);\r\n	}\r\n\r\n	parseOptionalFields();\r\n\r\n	this.result = { tags: {} };\r\n}\r\n\r\nfunction escapeMarkup(str) {\r\n	var length = str.length,\r\n		result = \'\',\r\n		markup = [\'{\', \'|\', \'}\', \'~\', \'_\', \'\\\\\', \'[\', \']\', \'^\', \'<\', \'>\', \'?\', \'!\', \'#\', \'+\', \'*\', \'&\'];\r\n\r\n	for (var i = 0; i < length; i++) {\r\n		var char = str[i];\r\n		result += (markup.indexOf(char) !== -1) ? (\'&#\' + str[i].charCodeAt() + \';\') : char;\r\n	}\r\n\r\n	return result;\r\n}\r\n\r\nfunction parseOptionalFields() {\r\n	this.params.customfields = {};\r\n	this.params.components = [];\r\n\r\n	Object.keys(this.params).forEach(function (key) {\r\n		if (key.startsWith(\'customfield_\')) {\r\n			this.params.customfields[key] = this.params[key];\r\n		}\r\n\r\n		if (key.startsWith(\'component_\')) {\r\n			this.params.components.push({"name": this.params[key]})\r\n		}\r\n	});\r\n}\r\n\r\nJira.prototype.addCustomFields = function (data, requestFieldValues) {\r\n	if (typeof this.params.customfields === \'object\' && Object.keys(this.params.customfields).length) {\r\n		var schemaData = this.sendRequest(\'GET\', \'/rest/api/latest/field\'),\r\n			schema = {};\r\n\r\n		schemaData.forEach(function (item) {\r\n			schema[item.id] = item.schema;\r\n		});\r\n\r\n		var placeholder = (requestFieldValues ? \'requestFieldValues\' : \'fields\');\r\n\r\n		Object.keys(this.params.customfields).forEach(function (field) {\r\n			if (typeof schema[field] === \'object\' && schema[field].type) {\r\n				const type = schema[field].type;\r\n\r\n				if (type === \'number\') {\r\n					data[placeholder][field] = parseInt(this.params.customfields[field]);\r\n				}\r\n				else if (type === \'string\' && schema[field][\'custom\'].split(\':\')[1] === \'url\') {\r\n					if (this.params.customfields[field] === \'zabbix_url\') {\r\n						data[placeholder][field] = CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id);\r\n					} else {\r\n						data[placeholder][field] = this.params.customfields[field];\r\n					}\r\n				}\r\n				else if (type === \'date\') {\r\n					if (this.params.customfields[field].match(/\\d+[.-]\\d+[.-]\\d+/) !== null) {\r\n						data[placeholder][field] = this.params.customfields[field].replace(/\\./g, \'-\');\r\n					}\r\n				}\r\n				else if (type === \'datetime\') {\r\n					if (this.params.customfields[field].match(/\\d+[.-]\\d+[.-]\\d+T\\d+:\\d+:\\d+/) !== null) {\r\n						data[placeholder][field] = this.params.customfields[field].replace(/\\./g, \'-\');\r\n					}\r\n				}\r\n				else if (type === \'option\') {\r\n					data[placeholder][field] = { \'value\': this.params.customfields[field] };\r\n				}\r\n				else if (type === \'array\') {\r\n					if (schema[field].items === \'option\') {\r\n						const valuesList = this.params.customfields[field].split(\',\');\r\n						data[placeholder][field] = [];\r\n						valuesList.forEach(function (val) {\r\n							data[placeholder][field].push({\'value\': val})\r\n						});\r\n					}\r\n					else {\r\n						data[placeholder][field] = [this.params.customfields[field]];\r\n					}\r\n				}\r\n				else {\r\n					data[placeholder][field] = this.params.customfields[field];\r\n				}\r\n			}\r\n		});\r\n	}\r\n	else {\r\n		Logger.log(Logger.WARN, \'No customfields found.\');\r\n	}\r\n\r\n	return data;\r\n}\r\n\r\nfunction parseTags(event_tags) {\r\n	try {\r\n		return JSON.parse(event_tags);\r\n	}\r\n	catch (error) {\r\n		if (this.params.event_source == 0 || this.params.event_source > 2) {\r\n			Logger.log(Logger.WARN, \'No event tags were found. Should be an object. Received event tags: "\' + event_tags + \'".\');\r\n		}\r\n		return [];\r\n	}\r\n}\r\n\r\nfunction getTagValue(tags, key, throw_on_fail) {\r\n	for (i in tags) {\r\n		if (tags[i].tag === key) {\r\n			return tags[i].value\r\n		}\r\n	}\r\n\r\n	if (!throw_on_fail) {\r\n		return false;\r\n	} else {\r\n		throw \'Tag "\' + key + \'" is not in the event tag list.\'\r\n	}\r\n};\r\n\r\nfunction setLabels(event_tags_json) {\r\n	var buffer = [];\r\n\r\n	event_tags_json.forEach(function (tag) {\r\n		if (typeof tag.tag !== \'undefined\' && typeof tag.value !== \'undefined\' && !tag.tag.startsWith(\'__zbx\')) {\r\n			label = (tag.tag + (tag.value ? (\':\' + tag.value) : \'\')).replace(/\\s/g, \'_\');\r\n			if (label.length < 256) {\r\n				buffer.push(label);\r\n			}\r\n		}\r\n	});\r\n\r\n	if (buffer.length === 0) {\r\n		Logger.log(Logger.WARN, \'No labels were set.\');\r\n	}\r\n\r\n	return buffer;\r\n}\r\n\r\nJira.prototype.commentIssue = function (issue_key) {\r\n	var data = {\r\n		body: this.params.alert_message,\r\n		public: this.params.issue_comments_public\r\n	};\r\n	this.sendRequest(\'POST\', \'/rest/servicedeskapi/request/\' + encodeURIComponent(issue_key) + \'/comment\', data);\r\n}\r\n\r\nJira.prototype.sendRequest = function (method, path, data) {\r\n	this.request.clearHeader();\r\n	this.request.addHeaders(\'Authorization: Basic \' + btoa(this.params.jira_user + \':\' + this.params.jira_password));\r\n\r\n	var response = this.request.jsonRequest(method, this.params.jira_url + path, data);\r\n\r\n	if ((this.request.getStatus() !== 200 && this.request.getStatus() !== 201)) {\r\n		Logger.log(Logger.WARN, \'HTTP code: \' + this.request.getStatus());\r\n		if (CParamValidator.isType(response.description, \'string\')) {\r\n			throw response.description;\r\n		}\r\n		else {\r\n			Logger.log(Logger.WARN, \'Request not successful. Received response: \' + JSON.stringify(response));\r\n			throw \'Unknown error. Check debug log for more information.\';\r\n		}\r\n	}\r\n\r\n	return response;\r\n}\r\n\r\nJira.prototype.onProblem = function (alert) {\r\n	if (this.params.event_tags_json.length > 0 && getTagValue(this.params.event_tags_json, \'__zbx_jira_requestkey\', false) !== false) {\r\n		return this.onUpdate(alert, true);\r\n	}\r\n\r\n	var data = {\r\n		serviceDeskId: this.params.jira_servicedesk_id,\r\n		requestTypeId: this.params.jira_request_type_id,\r\n		requestFieldValues: {\r\n			summary: this.params.alert_subject,\r\n			description: this.params.alert_message,\r\n			priority: {\r\n				"name": this.priority\r\n			}\r\n		}\r\n	};\r\n\r\n	if (this.labels && this.labels.length > 0) {\r\n		data.requestFieldValues.labels = this.labels;\r\n	}\r\n\r\n	if (this.params.components && this.params.components.length > 0) {\r\n		data.requestFieldValues.components = this.params.components;\r\n	}\r\n\r\n	var response = this.sendRequest(\'POST\', \'/rest/servicedeskapi/request\', this.addCustomFields(data, true));\r\n	this.result.tags = {\r\n		__zbx_jira_requestkey: response.issueKey,\r\n		__zbx_jira_requestlink: this.params.jira_url + \'/browse/\' + response.issueKey\r\n	}\r\n	return this.result;\r\n}\r\n\r\nJira.prototype.onUpdate = function (alert, dontUpdatePriority) {\r\n	var data = {\r\n		fields: {\r\n			summary: this.params.alert_subject,\r\n			priority: {\r\n				"name": this.priority\r\n			}\r\n		}\r\n	};\r\n\r\n	if (dontUpdatePriority && this.params.event_source != 0) {\r\n		delete data[\'fields\'][\'priority\'];\r\n	}\r\n\r\n	var jira_issue_key = getTagValue(this.params.event_tags_json, \'__zbx_jira_requestkey\', true);\r\n	this.sendRequest(\'PUT\', \'/rest/api/latest/issue/\' + encodeURIComponent(jira_issue_key) + \'?returnIssue=true\', this.addCustomFields(data));\r\n	this.commentIssue(jira_issue_key);\r\n\r\n	return this.result;\r\n}\r\n\r\nJira.prototype.onResolve = function (alert) {\r\n	return this.onUpdate(alert, true);\r\n}\r\n\r\nJira.prototype.onDiscovery = function (alert) {\r\n	this.priority = this.params.jira_priority_discovery;\r\n	return this.onProblem(alert);\r\n}\r\n\r\nJira.prototype.onAutoreg = function (alert) {\r\n	this.priority = this.params.jira_priority_autoregistration;\r\n	return this.onProblem(alert);\r\n}\r\n\r\ntry {\r\n	var hook = new Jira(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_jira_requestlink}','Jira Service Management: {EVENT.TAGS.__zbx_jira_requestkey}','https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/jira_service_management\r\n\r\n1. To make this integration work, you will need the following from Jira:\r\n  * Jira instance URL;\r\n  * Jira service desk id and request type id that the issues created by Zabbix will use;\r\n  * Jira username and password or API token. API token is strongly recommended and can be obtained at https://id.atlassian.com/manage/api-tokens.\r\n2. In the Zabbix web interface, go to Administration → Macros section. Set up the global macro "{$ZABBIX.URL}" which will contain the URL to the Zabbix frontend.\r\n3. On this page replace the placeholder \'<...>\' values with the ones from the step #1.\r\n4. In Zabbix, you need to have a Zabbix user and add Media with the Jira Service Management media type. Make sure this user has access to all hosts for which you would like problem issues to be created in Jira.','0'),
('80','4','Line','','','','','','','','25','0','0','0','0','1','3','10s','1','function sendMessage(to, messages, params) {\r\n    var response,\r\n        request = new HttpRequest();\r\n\r\n    if (typeof params.HTTPProxy === \'string\' && params.HTTPProxy.trim() !== \'\') {\r\n        request.setProxy(params.HTTPProxy);\r\n    }\r\n\r\n    request.addHeader(\'Content-Type: application/json\');\r\n    request.addHeader(\'Authorization: Bearer \' + params.bot_token);\r\n\r\n    response = request.post(\'https://api.line.me/v2/bot/message/push\', JSON.stringify({\r\n        "to": to,\r\n        "messages": messages\r\n    }));\r\n\r\n    if (request.getStatus() !== 200) {\r\n        throw response;\r\n    }\r\n}\r\n\r\nfunction validateParams(params) {\r\n    if (typeof params.bot_token !== \'string\' || params.bot_token.trim() === \'\') {\r\n        throw \'Field "bot_token" cannot be empty\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: "\' + params.event_source + \'".\\nMust be 0-3.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\') {\r\n        params.event_nseverity = \'0\';\r\n        params.event_severity = \'Not classified\';\r\n        params.event_update_status = \'0\';\r\n    }\r\n\r\n    if (params.event_source === \'1\' || params.event_source === \'2\') {\r\n        params.event_value = \'1\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        throw \'Incorrect "event_nseverity" parameter given: \' + params.event_nseverity + \'\\nMust be 0-5.\';\r\n    }\r\n\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\') {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (isNaN(params.trigger_id) && params.event_source === \'0\') {\r\n        throw \'field "trigger_id" is not a number\';\r\n    }\r\n\r\n    if (typeof params.zabbix_url !== \'string\' || params.zabbix_url.trim() === \'\') {\r\n        throw \'Field "zabbix_url" cannot be empty\';\r\n    }\r\n\r\n    if (!/^(http|https):\\/\\/.+/.test(params.zabbix_url)) {\r\n        throw \'Field "zabbix_url" must contain a schema\';\r\n    }\r\n}\r\n\r\nfunction getZabbixProblemLink(params) {\r\n    return params.zabbix_url + (params.zabbix_url.endsWith(\'/\') ? \'\' : \'/\') + \'tr_events.php?triggerid=\' + params.trigger_id + \'&eventid=\' + params.event_id;    \r\n}\r\n\r\ntry {\r\n    var params = JSON.parse(value);\r\n\r\n    validateParams(params);\r\n\r\n    severity_emoji = [\r\n        "\\u26AA",\r\n        "\\uD83D\\uDD35",\r\n        "\\uD83D\\uDFE4",\r\n        "\\uD83D\\uDFE1",\r\n        "\\uD83D\\uDFE0",\r\n        "\\uD83D\\uDD34",\r\n    ];\r\n\r\n    // If its a trigger and a recovery operation and not an update operation.\r\n    if (params.event_source === \'0\' && params.event_value === \'0\' && params.event_update_status === \'0\') {\r\n        var line_message = [\r\n            {\r\n                "type": "text",\r\n                "text": \'\\u2705 \' + params.alert_subject + \'\\n\\n\' + params.alert_message + \'\\n\' + params.trigger_description + \'\\n\\n\' + getZabbixProblemLink(params)\r\n            }\r\n        ];\r\n    }\r\n    // If its a trigger and its a problem.\r\n    else if (params.event_source === \'0\' && params.event_value === \'1\') {\r\n        var line_message = [\r\n            {\r\n                "type": "text",\r\n                "text": severity_emoji[params.event_nseverity] + \' \' + params.alert_subject + \'\\n\\n\' + params.alert_message + \'\\n\' + params.trigger_description + \'\\n\\n\' + getZabbixProblemLink(params)\r\n            }\r\n        ];\r\n    }\r\n    // If its a trigger and its an update operation.\r\n    else if (params.event_source === \'0\' && params.event_update_status === \'1\') {\r\n        var line_message = [\r\n            {\r\n                "type": "text",\r\n                "text": \'\\u2733 \' + severity_emoji[params.event_nseverity] + \' \' + params.alert_subject + \'\\n\\n\' + params.alert_message + \'\\n\' + params.trigger_description + \'\\n\\n\' + getZabbixProblemLink(params)\r\n            }\r\n        ];\r\n    }\r\n    else {\r\n        var line_message = [\r\n            {\r\n                "type": "text",\r\n                "text": params.alert_subject + \'\\n\\n\' + params.alert_message + \'\\n\'\r\n            }\r\n        ];\r\n    }\r\n\r\n    sendMessage(params.send_to, line_message, params);\r\n\r\n    return \'OK\';\r\n}\r\ncatch (err) {\r\n    Zabbix.log(4, \'[ Line Webhook ] Line notification failed : \' + err);\r\n    throw \'Line notification failed : \' + err;\r\n}','30s','0','0','','','Please refer to setup guide here: https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/line\r\n\r\nSet bot_token parameter to your Line bot token.\r\nWhen assigning Line media to the Zabbix user - add the ID of the target recipient. Use a userId, groupId, or roomId value.','0'),
('81','4','ManageEngine ServiceDesk','','','','','','','','25','0','0','0','0','1','3','10s','1','var MEngine = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        MEngine.params = params;\r\n        if (typeof MEngine.params.url === \'string\') {\r\n            if (!MEngine.params.url.endsWith(\'/\')) {\r\n                MEngine.params.url += \'/\';\r\n            }\r\n\r\n            MEngine.params.url += \'api/v3/\';\r\n        }\r\n\r\n        if (MEngine.params.on_premise.toLowerCase() !== \'true\'\r\n                && typeof MEngine.params.on_demand_url_auth === \'string\') {\r\n            if (!MEngine.params.on_demand_url_auth.endsWith(\'/\')) {\r\n                MEngine.params.on_demand_url_auth += \'/\';\r\n            }\r\n\r\n            MEngine.params.on_demand_url_auth += \'oauth/v2/token?\';\r\n        }\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        MEngine.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    createLink: function (id, url) {\r\n        return url + (url.endsWith(\'/\') ? \'\' : \'/\') +\r\n            ((MEngine.params.on_premise.toLowerCase() === \'true\')\r\n                ? (\'WorkOrder.do?woMode=viewWO&woID=\' + id)\r\n                : (\'app/itdesk/ui/requests/\' + id + \'/details\')\r\n            );\r\n    },\r\n\r\n    refreshAccessToken: function () {\r\n        [\r\n            \'on_demand_url_auth\',\r\n            \'on_demand_refresh_token\',\r\n            \'on_demand_client_id\',\r\n            \'on_demand_client_secret\'\r\n        ].forEach(function (field) {\r\n            if (typeof MEngine.params !== \'object\' || typeof MEngine.params[field] === \'undefined\'\r\n                    || MEngine.params[field].trim() === \'\' ) {\r\n                throw \'Required MEngine param is not set: "sd_\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            request = new HttpRequest(),\r\n            url = MEngine.params.on_demand_url_auth +\r\n                \'refresh_token=\' + encodeURIComponent(MEngine.params.on_demand_refresh_token) +\r\n                \'&grant_type=refresh_token&client_id=\' + encodeURIComponent(MEngine.params.on_demand_client_id) +\r\n                \'&client_secret=\' + encodeURIComponent(MEngine.params.on_demand_client_secret) +\r\n                \'&redirect_uri=https://www.zoho.com&scope=SDPOnDemand.requests.ALL\';\r\n\r\n        if (MEngine.HTTPProxy) {\r\n            request.setProxy(MEngine.HTTPProxy);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ ManageEngine Webhook ] Refreshing access token. Request: \' + url);\r\n\r\n        response = request.post(url);\r\n\r\n        Zabbix.log(4, \'[ ManageEngine Webhook ] Received response with status code \' +\r\n        request.getStatus() + \'\\n\' + response);\r\n\r\n        try {\r\n            response = JSON.parse(response);\r\n        }\r\n        catch (error) {\r\n            Zabbix.log(4, \'[ ManageEngine Webhook ] Failed to parse response received from Zoho Accounts\');\r\n        }\r\n\r\n        if ((request.getStatus() < 200 || request.getStatus() >= 300) && !response.access_token) {\r\n            throw \'Access token refresh failed with HTTP status code \' + request.getStatus() +\r\n                \'. Check debug log for more information.\';\r\n        }\r\n        else {\r\n            MEngine.params.on_demand_auth_token = response.access_token;\r\n        }\r\n    },\r\n\r\n    request: function (method, query, data) {\r\n        var response,\r\n            url = MEngine.params.url + query,\r\n            input,\r\n            request = new HttpRequest(),\r\n            message;\r\n\r\n        if (MEngine.params.on_premise.toLowerCase() === \'true\') {\r\n            request.addHeader(\'TECHNICIAN_KEY: \' + MEngine.params.on_premise_auth_token);\r\n        }\r\n        else {\r\n            request.addHeader(\'Authorization: Zoho-oauthtoken \' + MEngine.params.on_demand_auth_token);\r\n            request.addHeader(\'Accept: application/v3+json\');\r\n        }\r\n\r\n        if (MEngine.HTTPProxy) {\r\n            request.setProxy(MEngine.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        input = \'input_data=\' + encodeURIComponent(data);\r\n        Zabbix.log(4, \'[ ManageEngine Webhook ] Sending request: \' + url + \'?\' + input);\r\n\r\n        switch (method) {\r\n            case \'post\':\r\n                response = request.post(url, input);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, input);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ ManageEngine Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        try {\r\n            response = JSON.parse(response);\r\n        }\r\n        catch (error) {\r\n            Zabbix.log(4, \'[ ManageEngine Webhook ] Failed to parse response received from ManageEngine\');\r\n        }\r\n\r\n        if ((request.getStatus() < 200 || request.getStatus() >= 300)\r\n                && typeof response.response_status !== \'object\') {\r\n            throw \'Request failed with HTTP status code \' + request.getStatus() +\r\n                \'. Check debug log for more information.\';\r\n        }\r\n        else if (typeof response.response_status === \'object\' && response.response_status.status === \'failed\') {\r\n            message = \'Request failed with status_code \';\r\n\r\n            if (typeof response.response_status.messages === \'object\'\r\n                    && response.response_status.messages[0]\r\n                    && response.response_status.messages[0].message) {\r\n                message += response.response_status.messages[0].status_code +\r\n                    \'. Message: \' + response.response_status.messages[0].message;\r\n            }\r\n            else {\r\n                message += response.response_status.status_code;\r\n            }\r\n\r\n            message += \'. Check debug log for more information.\';\r\n            throw message;\r\n        }\r\n        else if (response.request) {\r\n            return response.request.id;\r\n        }\r\n    },\r\n\r\n    createPaylaod: function (fields, isNote) {\r\n        var data = {},\r\n            result;\r\n\r\n        if (isNote) {\r\n            data.description = fields[\'field_string:description\'].replace(/(?:\\r\\n|\\r|\\n)/g, \'<br>\');\r\n            result = {request_note: data};\r\n        }\r\n        else {\r\n            Object.keys(fields)\r\n                .forEach(function(field) {\r\n                    if (fields[field].trim() === \'\') {\r\n                        Zabbix.log(4, \'[ ManageEngine Webhook ] Field "\' + field +\r\n                            \'" can\\\'t be empty. The field ignored.\');\r\n                    }\r\n                    else {\r\n                        try {\r\n                            var prefix = field.split(\':\')[0],\r\n                                root;\r\n\r\n                            if  (prefix.startsWith(\'udf_\') && !data.udf_fields) {\r\n                                data.udf_fields = {};\r\n                                root = data.udf_fields;\r\n                            }\r\n                            else if (prefix.startsWith(\'udf_\')) {\r\n                                root = data.udf_fields;\r\n                            }\r\n                            else {\r\n                                root = data;\r\n                            }\r\n\r\n                            if (prefix.endsWith(\'string\')) {\r\n                                root[field.substring(field.indexOf(\':\') + 1)\r\n                                    .toLowerCase()] = fields[field];\r\n                            }\r\n                            else {\r\n                                root[field.substring(field.indexOf(\':\') + 1)\r\n                                    .toLowerCase()] = {\r\n                                    name: fields[field]\r\n                                };\r\n                            }\r\n                        }\r\n                        catch (error) {\r\n                            Zabbix.log(4, \'[ ManageEngine Webhook ] Can\\\'t parse field "\' + field +\r\n                                \'". The field ignored.\');\r\n                        }\r\n                    }\r\n                });\r\n            if (data.description) {\r\n                data.description = data.description.replace(/(?:\\r\\n|\\r|\\n)/g, \'<br>\');\r\n            }\r\n\r\n            result = {request: data};\r\n        }\r\n\r\n        return result;\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        fields = {},\r\n        sd = {},\r\n        result = {tags: {}},\r\n        required_params = [\r\n            \'sd_on_premise\', \'field_string:subject\', \'field_string:description\',\r\n            \'event_recovery_value\', \'event_source\', \'event_value\', \'event_update_status\'\r\n        ],\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'default\', color: \'#000000\'}\r\n        ];\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'sd_\')) {\r\n                sd[key.substring(3)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'field_\') || key.startsWith(\'udf_field_\')) {\r\n                fields[key] = params[key];\r\n            }\r\n\r\n            if (required_params.indexOf(key) !== -1 && params[key].trim() === \'\') {\r\n                throw \'Parameter "\' + key + \'" can\\\'t be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_recovery_value === \'0\') {\r\n        throw \'Recovery operations are supported only for trigger-based actions.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    if (params.event_update_status === \'1\' && (typeof params.sd_request_id === \'undefined\'\r\n            || params.sd_request_id.trim() === \'\'\r\n            || params.sd_request_id === \'{EVENT.TAGS.__zbx_sd_request_id}\'\r\n            || params.sd_request_id === \'*UNKNOWN*\')) {\r\n        throw \'Parameter "sd_request_id" can\\\'t be empty for update operation.\';\r\n    }\r\n\r\n    MEngine.setParams(sd);\r\n    MEngine.setProxy(params.HTTPProxy);\r\n\r\n    if (MEngine.params.on_premise.toLowerCase() !== \'true\') {\r\n        MEngine.refreshAccessToken();\r\n    }\r\n\r\n    // Create issue for non trigger-based events.\r\n    if (params.event_source !== \'0\' && params.event_recovery_value !== \'0\') {\r\n        fields[\'field_object:priority\'] = params[\'priority_\' + severities[params.event_nseverity].name]\r\n        || \'Normal\';\r\n\r\n        MEngine.request(\'post\', \'requests\', MEngine.createPaylaod(fields));\r\n    }\r\n    // Create issue for trigger-based events.\r\n    else if (params.event_value === \'1\' && params.event_update_status === \'0\') {\r\n        fields[\'field_object:priority\'] = params[\'priority_\' + severities[params.event_nseverity].name]\r\n        || \'Normal\';\r\n\r\n        var id = MEngine.request(\'post\', \'requests\', MEngine.createPaylaod(fields));\r\n\r\n        result.tags.__zbx_sd_request_id = id;\r\n        result.tags.__zbx_sd_request_link = MEngine.createLink(id, params.sd_url);\r\n    }\r\n    // Update created issue for trigger-based event.\r\n    else {\r\n        if (params.event_update_status === \'1\') {\r\n            MEngine.request(\'post\', \'requests/\' + params.sd_request_id + \'/notes\',\r\n                MEngine.createPaylaod(fields, true)\r\n            );\r\n        }\r\n        delete fields[\'field_string:description\'];\r\n        MEngine.request(\'put\', \'requests/\' + params.sd_request_id, MEngine.createPaylaod(fields));\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ ManageEngine Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_sd_request_link}','ManageEngine: {EVENT.TAGS.__zbx_sd_request_id}','','0'),
('82','4','MantisBT','','','','','','','','25','0','0','0','0','1','1','10s','1','var Mantisbt = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n        Mantisbt.params = params;\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        Mantisbt.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    checkUrlFormat: function (url) {\r\n        if (typeof url === \'string\' && !url.endsWith(\'/\')) {\r\n            url += \'/\';\r\n        }\r\n\r\n        if (url.indexOf(\'http://\') === -1 && url.indexOf(\'https://\') === -1) {\r\n            url = \'https://\' + url;\r\n        }\r\n\r\n        return url;\r\n    },\r\n\r\n    getProblemURL: function (zabbix_url, triggerid, eventid, event_source) {\r\n        var problem_url = zabbix_url;\r\n\r\n        if (event_source === \'0\') {\r\n            problem_url += \'tr_events.php?triggerid=\' + triggerid + \'&eventid=\' + eventid;\r\n        }\r\n\r\n        return problem_url;\r\n    },\r\n\r\n    request: function (method, url, data) {\r\n        [\'token\', \'url\', \'category\'].forEach(function (field) {\r\n            if (typeof Mantisbt.params !== \'object\' || typeof Mantisbt.params[field] === \'undefined\' || Mantisbt.params[field] === \'\') {\r\n                throw \'Required MantisBT param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'Authorization: \' + Mantisbt.params.token);\r\n\r\n        if (typeof Mantisbt.HTTPProxy !== \'undefined\' && Mantisbt.HTTPProxy !== \'\') {\r\n            request.setProxy(Mantisbt.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ MantisBT Webhook ] Sending request: \' + url + ((typeof data === \'string\') ? (\'\\n\' + data) : \'\'));\r\n\r\n        switch (method) {\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'patch\':\r\n                response = request.patch(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ MantisBT Webhook ] Received response with status code \' + request.getStatus() + \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ MantisBT Webhook ] Failed to parse the response received from MantisBT\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (typeof response !== \'object\') {\r\n            throw \'Failed to process the response received from MantisBT. Check debug log for more information.\';\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (typeof response.message !== \'undefined\') {\r\n                message += \': \' + response.message;\r\n            }\r\n\r\n            throw message;\r\n        }\r\n\r\n        return response;\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        mantisbt = {},\r\n        url = \'\',\r\n        data = {},\r\n        result = { tags: {} },\r\n        required_params = [\r\n            \'alert_subject\', \'alert_message\', \'event_source\', \'event_value\', \'event_update_action\',\r\n            \'event_update_status\', \'event_recovery_value\', \'event_nseverity\', \'event_tagsjson\',\r\n            \'event_id\', \'trigger_id\', \'zabbix_url\', \'alert_sendto\',\r\n            \'mantisbt_token\', \'mantisbt_url\', \'mantisbt_category\', \'mantisbt_issue_number\', \'mantisbt_use_zabbix_tags\'\r\n        ],\r\n        method,\r\n        severities = [\'none\', \'low\', \'normal\', \'high\', \'urgent\', \'immediate\'];\r\n\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'mantisbt_\')) {\r\n                mantisbt[key.substring(9)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key] === \'\') {\r\n                throw \'Parameter "\' + key + \'" cannot be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\' && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_recovery_value === \'0\') {\r\n        throw \'Recovery operations are supported for trigger-based actions only.\';\r\n    }\r\n\r\n    if (typeof params.zabbix_url !== \'string\' || params.zabbix_url.trim() === \'\' || params.zabbix_url === \'{$ZABBIX.URL}\') {\r\n        throw \'Field "zabbix_url" cannot be empty.\';\r\n    }\r\n\r\n    // Check for backslash in the end of url and schema.\r\n    mantisbt.url = Mantisbt.checkUrlFormat(mantisbt.url);\r\n    params.zabbix_url = Mantisbt.checkUrlFormat(params.zabbix_url);\r\n\r\n    // In case of resolve event.\r\n    if (params.event_source === \'0\' && params.event_value === \'0\') {\r\n        method = "patch";\r\n        url = mantisbt.url + \'api/rest/issues/\' + mantisbt.issue_number;\r\n        data = {\r\n            summary: params.alert_subject,\r\n            status: {\r\n                name: "resolved"\r\n            }\r\n        };\r\n        if (/commented/.test(params.event_update_action)) {\r\n            data.additional_information = params.event_update_message;\r\n        }\r\n        process_tags = false;\r\n    }\r\n    // In case of update event.\r\n    else if (params.event_source === \'0\' && params.event_update_status === \'1\') {\r\n        method = "patch";\r\n        url = mantisbt.url + \'api/rest/issues/\' + mantisbt.issue_number;\r\n        data = {\r\n            status: {},\r\n            priority: {\r\n                name: severities[parseInt(params.event_nseverity, 10)]\r\n            }\r\n        };\r\n        if (/commented/.test(params.event_update_action)) {\r\n            data.additional_information = params.event_update_message;\r\n        }\r\n        if (/acknowledged/.test(params.event_update_action)) {\r\n            data.status.name = "acknowledged";\r\n        }\r\n        if (/unacknowledged/.test(params.event_update_action)) {\r\n            data.status.name = "new";\r\n        }\r\n        process_tags = false;\r\n    }\r\n    else {\r\n        method = \'post\';\r\n        url = mantisbt.url + \'api/rest/issues\';\r\n\r\n        data = {\r\n            summary: params.alert_subject,\r\n            description: params.alert_message,\r\n            project: { name: params.alert_sendto },\r\n            category: { name: mantisbt.category },\r\n            priority: {\r\n                name: parseInt(params.event_nseverity, 10) ? severities[parseInt(params.event_nseverity, 10)] : "none"\r\n            }\r\n        };\r\n        if (params.event_source === \'0\') {\r\n            problem_url = Mantisbt.getProblemURL(params.zabbix_url, params.trigger_id, params.event_id, params.event_source);\r\n            data.description += \'\\n\' + problem_url;\r\n\r\n            if (mantisbt.use_zabbix_tags === "true") {\r\n                var alert_tags = JSON.parse(params.event_tagsjson);\r\n                data.tags = alert_tags.map(function (t) { return { name: t.value ? (t.tag + \': \' + t.value) : t.tag }; });\r\n            }\r\n        }\r\n        process_tags = true;\r\n    }\r\n\r\n    Mantisbt.setParams(mantisbt);\r\n    Mantisbt.setProxy(params.HTTPProxy);\r\n\r\n    var response = Mantisbt.request(method, url, data);\r\n\r\n    if (process_tags) {\r\n        result.tags.__zbx_mantisbt_issue_number = response.issue.id;\r\n        result.tags.__zbx_mantisbt_link = mantisbt.url + \'view.php?id=\' + response.issue.id;\r\n    }\r\n\r\n    Zabbix.log(4, \'[ MantisBT Webhook ] Result: \' + JSON.stringify(result));\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(4, \'[ MantisBT Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_mantisbt_link}','MantisBT: Issue ID {EVENT.TAGS.__zbx_mantisbt_issue_number}','','0'),
('83','4','Mattermost','','','','','','','','25','0','0','0','0','1','1','10s','1','var SEVERITY_COLORS = [\r\n    \'#97AAB3\', \'#7499FF\', \'#FFC859\',\r\n    \'#FFA059\', \'#E97659\', \'#E45959\'\r\n];\r\n\r\nvar RESOLVE_COLOR = \'#009900\';\r\n\r\nvar SEND_MODE_HANDLERS = {\r\n    alarm: handlerAlarm,\r\n    event: handlerEvent\r\n};\r\n\r\nif (!String.prototype.format) {\r\n    String.prototype.format = function() {\r\n        var args = arguments;\r\n\r\n        return this.replace(/{(\\d+)}/g, function(match, number) {\r\n            return number in args\r\n                ? args[number]\r\n                : match\r\n            ;\r\n        });\r\n    };\r\n}\r\n\r\nfunction isEventProblem(params) {\r\n    return params.event_value == 1\r\n        && params.event_update_status == 0\r\n    ;\r\n}\r\n\r\nfunction isEventUpdate(params) {\r\n    return params.event_value == 1\r\n        && params.event_update_status == 1\r\n    ;\r\n}\r\n\r\nfunction isEventResolve(params) {\r\n    return params.event_value == 0;\r\n}\r\n\r\nfunction getPermalink(mattermost_url, team_name, postid) {\r\n    return \'{0}/{1}/pl/{2}\'.format(\r\n        mattermost_url.replace(/\\/+$/, \'\'),\r\n        team_name,\r\n        postid\r\n    );\r\n}\r\n\r\nfunction getChannel(send_to) {\r\n    switch (true) {\r\n        case /.+\\/#.+/.test(send_to):\r\n            return getChannelByName(send_to);\r\n\r\n        case /@.+/.test(send_to):\r\n            return getDirectChannel(send_to);\r\n\r\n        default:\r\n            return getChannelByID(send_to);\r\n    }\r\n}\r\n\r\nfunction getChannelByName(send_to) {\r\n    var team_chan = send_to\r\n        .trim()\r\n        .split(\'/#\');\r\n\r\n    var resp = JSON.parse(req.get(\r\n        Mattermost.channel_byname.format(team_chan[0], team_chan[1]),\r\n        JSON.stringify(fields)\r\n    )\r\n    );\r\n\r\n    if (req.getStatus() != 200) {\r\n        throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n    }\r\n\r\n    return resp;\r\n}\r\n\r\nfunction getDirectChannel(send_to) {\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Call {0}({1})\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(arguments)\r\n    ));\r\n\r\n    var teamUser = send_to\r\n            .trim()\r\n            .split(\'/@\'),\r\n        bot = getBotUser(),\r\n        user = getUserByName(teamUser[1]);\r\n\r\n    var resp = JSON.parse(req.post(\r\n        Mattermost.direct_channel,\r\n        JSON.stringify([bot.id, user.id])\r\n    )\r\n    );\r\n\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Result {0}: {1}\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(resp)\r\n    ));\r\n\r\n    if (req.getStatus() != 201) {\r\n        throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n    }\r\n\r\n    resp.team_name = teamUser[0];\r\n\r\n    return resp;\r\n}\r\n\r\nfunction getChannelByID(channelID) {\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Call {0}({1})\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(arguments)\r\n    ));\r\n\r\n    var resp = JSON.parse(req.get(\r\n        Mattermost.get_channel.format(channelID),\r\n        JSON.stringify(fields)\r\n    )\r\n    );\r\n\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Result {0}: {1}\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(resp)\r\n    ));\r\n\r\n    if (req.getStatus() != 200) {\r\n        throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n    }\r\n\r\n    return resp;\r\n}\r\n\r\nfunction getBotUser() {\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Call {0}({1})\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(arguments)\r\n    ));\r\n\r\n    var resp = JSON.parse(req.get(\r\n        Mattermost.bot_user,\r\n        JSON.stringify(fields)\r\n    )\r\n    );\r\n\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Result {0}: {1}\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(resp)\r\n    ));\r\n\r\n    if (req.getStatus() != 200) {\r\n        throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n    }\r\n\r\n    return resp;\r\n}\r\n\r\nfunction getUserByName(userName) {\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Call {0}({1})\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(arguments)\r\n    ));\r\n\r\n    var resp = JSON.parse(req.get(\r\n        Mattermost.user_byname.format(userName),\r\n        JSON.stringify(fields)\r\n    )\r\n    );\r\n\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Result {0}: {1}\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(resp)\r\n    ));\r\n\r\n    if (req.getStatus() != 200) {\r\n        throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n    }\r\n\r\n    return resp;\r\n}\r\n\r\nfunction getTeamByID(teamID) {\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Call {0}({1})\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(arguments)\r\n    ));\r\n\r\n    var resp = JSON.parse(req.get(\r\n        Mattermost.get_team.format(teamID),\r\n        JSON.stringify(fields)\r\n    )\r\n    );\r\n\r\n    Zabbix.log(5, \'[ Mattermost Webhook ] Result {0}: {1}\'.format(\r\n        arguments.callee.name,\r\n        JSON.stringify(resp)\r\n    ));\r\n\r\n    if (req.getStatus() != 200) {\r\n        throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n    }\r\n\r\n    return resp;\r\n}\r\n\r\nfunction createProblemURL(zabbix_url, triggerid, eventid, event_source) {\r\n    var problem_url = \'\';\r\n    if (event_source === \'0\') {\r\n        problem_url = \'{0}/tr_events.php?triggerid={1}&eventid={2}\'\r\n            .format(\r\n                zabbix_url,\r\n                triggerid,\r\n                eventid\r\n            );\r\n    }\r\n    else {\r\n        problem_url = zabbix_url;\r\n    }\r\n\r\n    return problem_url;\r\n}\r\n\r\nfunction getTagValue(event_tags, key) {\r\n    var pattern = new RegExp(\'(\' + key + \':.+)\');\r\n    var tagValue = event_tags\r\n        .split(\',\')\r\n        .filter(function (v) {\r\n            return v.match(pattern);\r\n        })\r\n        .map(function (v) {\r\n            return v.split(\':\')[1];\r\n        })[0]\r\n        || 0;\r\n\r\n    return tagValue;\r\n}\r\n\r\nfunction handlerAlarm(req, params) {\r\n    var channel = getChannel(params.send_to);\r\n    var fields = {\r\n        channel_id: channel.id,\r\n        props: {}\r\n    };\r\n\r\n    if (isEventProblem(params)) {\r\n        var team_name = channel.team_name\r\n            ? channel.team_name\r\n            : getTeamByID(channel.team_id).name;\r\n\r\n        fields.props.attachments = [\r\n            createMessage(\r\n                SEVERITY_COLORS[params.event_nseverity] || 0,\r\n                params.event_date,\r\n                params.event_time,\r\n                createProblemURL(params.zabbix_url, params.trigger_id, params.event_id, params.event_source)\r\n            )\r\n        ];\r\n\r\n        var resp = JSON.parse(req.post(\r\n            Mattermost.post_message,\r\n            JSON.stringify(fields)\r\n        )\r\n        );\r\n\r\n        if (req.getStatus() != 201) {\r\n            throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n        }\r\n\r\n        result.tags.__mattermost_post_id = resp.id;\r\n        result.tags.__mattermost_channel_id = channel.id;\r\n        result.tags.__mattermost_channel_name = channel.name;\r\n        result.tags.__mattermost_message_link = getPermalink(\r\n            params.mattermost_url,\r\n            team_name,\r\n            resp.id\r\n        );\r\n\r\n    }\r\n    else if (isEventUpdate(params)) {\r\n        fields.root_id = getTagValue(params.event_tags, \'mattermost_post_id\');\r\n\r\n        if (params.event_source === \'0\') {}\r\n        fields.props.attachments = [\r\n            createMessage(\r\n                SEVERITY_COLORS[params.event_nseverity] || 0,\r\n                params.event_update_date,\r\n                params.event_update_time,\r\n                createProblemURL(params.zabbix_url, params.trigger_id, params.event_id, params.event_source),\r\n                true\r\n            )\r\n        ];\r\n\r\n        resp = JSON.parse(req.post(\r\n            Mattermost.post_message, JSON.stringify(fields)\r\n        )\r\n        );\r\n\r\n        if (req.getStatus() != 201) {\r\n            throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n        }\r\n\r\n    }\r\n    else if (isEventResolve(params)) {\r\n        fields.channel_id = getTagValue(params.event_tags, \'mattermost_channel_id\');\r\n        fields.id = getTagValue(params.event_tags, \'mattermost_post_id\');\r\n        fields.props.attachments = [\r\n            createMessage(\r\n                RESOLVE_COLOR,\r\n                params.event_date,\r\n                params.event_time,\r\n                createProblemURL(params.zabbix_url, params.trigger_id, params.event_id, params.event_source)\r\n            )\r\n        ];\r\n\r\n        var post_id = getTagValue(params.event_tags, \'mattermost_post_id\');\r\n\r\n        resp = JSON.parse(req.put(\r\n            Mattermost.chat_update.format(post_id),\r\n            JSON.stringify(fields)\r\n        )\r\n        );\r\n\r\n        if (req.getStatus() != 200) {\r\n            throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n        }\r\n    }\r\n}\r\n\r\nfunction handlerEvent(req, params) {\r\n    var channel = getChannel(params.send_to);\r\n    var fields = {\r\n        channel_id: channel.id,\r\n        props: {}\r\n    };\r\n\r\n    if (isEventProblem(params)) {\r\n        var team_name = channel.team_name\r\n            ? channel.team_name\r\n            : getTeamByID(channel.team_id).name;\r\n\r\n        fields.props.attachments = [\r\n            createMessage(\r\n                SEVERITY_COLORS[params.event_nseverity] || 0,\r\n                params.event_date,\r\n                params.event_time,\r\n                createProblemURL(params.zabbix_url, params.trigger_id, params.event_id, params.event_source)\r\n            )\r\n        ];\r\n\r\n        var resp = JSON.parse(req.post(Mattermost.post_message, JSON.stringify(fields)));\r\n\r\n        if (req.getStatus() != 201) {\r\n            throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n        }\r\n\r\n        result.tags.__mattermost_channel_name = channel.name;\r\n        result.tags.__mattermost_message_link = getPermalink(\r\n            params.mattermost_url,\r\n            team_name,\r\n            resp.id\r\n        );\r\n\r\n    }\r\n    else if (isEventUpdate(params)) {\r\n        fields.props.attachments = [\r\n            createMessage(\r\n                SEVERITY_COLORS[params.event_nseverity] || 0,\r\n                params.event_update_date,\r\n                params.event_update_time,\r\n                createProblemURL(params.zabbix_url, params.trigger_id, params.event_id, params.event_source),\r\n                false\r\n            )\r\n        ];\r\n\r\n        resp = JSON.parse(req.post(Mattermost.post_message, JSON.stringify(fields)));\r\n\r\n        if (req.getStatus() != 201) {\r\n            throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n        }\r\n\r\n    }\r\n    else if (isEventResolve(params)) {\r\n        fields.props.attachments = [\r\n            createMessage(\r\n                RESOLVE_COLOR,\r\n                params.event_recovery_date,\r\n                params.event_recovery_time,\r\n                createProblemURL(params.zabbix_url, params.trigger_id, params.event_id, params.event_source)\r\n            )\r\n        ];\r\n\r\n        resp = JSON.parse(req.post(Mattermost.post_message, JSON.stringify(fields)));\r\n\r\n        if (req.getStatus() != 201) {\r\n            throw \'[{0}] {1}\'.format(resp.status_code, resp.message);\r\n        }\r\n    }\r\n}\r\n\r\nfunction createMessage(\r\n    event_severity_color,\r\n    event_date,\r\n    event_time,\r\n    problem_url,\r\n    isShort\r\n) {\r\n    var message = {\r\n        fallbac: params.alert_subject,\r\n        title: params.alert_subject,\r\n        color: event_severity_color,\r\n        title_link: problem_url,\r\n        footer: problem_url,\r\n\r\n        fields: [\r\n            {\r\n                title: \'Host\',\r\n                value: \'{0} [{1}]\'.format(params.host_name, params.host_ip),\r\n                short: true\r\n            },\r\n            {\r\n                title: \'Event time\',\r\n                value: \'{0} {1}\'.format(event_date, event_time),\r\n                short: true\r\n            }\r\n        ],\r\n    };\r\n\r\n    \r\n    if (params.event_source === \'0\') {\r\n        message.fields.push(\r\n            {\r\n                title: \'Severity\',\r\n                value: params.event_severity,\r\n                short: true\r\n            },\r\n            {\r\n                title: \'Opdata\',\r\n                value: params.event_opdata,\r\n                short: true\r\n            }\r\n        );\r\n    }\r\n\r\n    if (!isShort && params.event_source === \'0\') {\r\n        message.fields.push(\r\n            {\r\n                title: \'Event tags\',\r\n                value: \'`{0}`\'.format(params.event_tags.replace(/__.+?:(.+?,|.+)/g, \'\') || \'None\'),\r\n                short: true\r\n            },\r\n            {\r\n                title: \'Trigger description\',\r\n                value: params.trigger_description,\r\n                short: true\r\n            }\r\n        );\r\n    }\r\n\r\n    if (params.event_source !== \'0\' || params.event_update_status === \'1\') {\r\n        message.fields.push(\r\n            {\r\n                title: \'Details\',\r\n                value: params.alert_message,\r\n                short: false\r\n            }\r\n        );\r\n    }\r\n\r\n    return message;\r\n}\r\n\r\nfunction validateParams(params) {\r\n    if (typeof params.bot_token !== \'string\' || params.bot_token.trim() === \'\') {\r\n        throw \'Field "bot_token" cannot be empty\';\r\n    }\r\n\r\n    if (isNaN(params.event_id)) {\r\n        throw \'Field "event_id" is not a number\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: "\' + params.event_source + \'".\\nMust be 0-3.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\') {\r\n        params.event_nseverity = \'0\';\r\n        params.event_severity = \'Not classified\';\r\n        params.event_update_status = \'0\';\r\n        params.send_mode = \'event\';\r\n    }\r\n\r\n    if (params.event_source === \'1\' || params.event_source === \'2\') {\r\n        params.event_value = \'1\';\r\n    }\r\n\r\n    if (params.event_source === \'1\') {\r\n        params.host_name = params.discovery_host_dns;\r\n        params.host_ip = params.discovery_host_ip;\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        throw \'Incorrect "event_nseverity" parameter given: \' + params.event_nseverity + \'\\nMust be 0-5.\';\r\n    }\r\n\r\n    if (typeof params.event_severity !== \'string\' || params.event_severity.trim() === \'\') {\r\n        throw \'Field "event_severity" cannot be empty\';\r\n    }\r\n\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\') {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (typeof params.host_ip !== \'string\' || params.host_ip.trim() === \'\') {\r\n        throw \'Field "host_ip" cannot be empty\';\r\n    }\r\n\r\n    if (typeof params.host_name !== \'string\' || params.host_name.trim() === \'\') {\r\n        throw \'Field "host_name" cannot be empty\';\r\n    }\r\n\r\n    if (typeof params.mattermost_url !== \'string\' || params.mattermost_url.trim() === \'\') {\r\n        throw \'Field "mattermost_url" cannot be empty\';\r\n    }\r\n\r\n    if (!/^(http|https):\\/\\/.+/.test(params.mattermost_url)) {\r\n        throw \'Field "mattermost_url" must contain a schema\';\r\n    }\r\n\r\n    if ([\'alarm\', \'event\'].indexOf(params.send_mode) === -1) {\r\n        throw \'Incorrect "send_mode" parameter given: \' + params.send_mode + \'\\nMust be "alarm" or "event".\';\r\n    }\r\n\r\n    if (typeof params.send_to !== \'string\' || params.send_to.trim() === \'\') {\r\n        throw \'Field "send_to" cannot be empty\';\r\n    }\r\n\r\n    if (isNaN(params.trigger_id) && params.event_source === \'0\') {\r\n        throw \'field "trigger_id" is not a number\';\r\n    }\r\n\r\n    if (typeof params.zabbix_url !== \'string\' || params.zabbix_url.trim() === \'\') {\r\n        throw \'Field "zabbix_url" cannot be empty\';\r\n    }\r\n\r\n    if (!/^(http|https):\\/\\/.+/.test(params.zabbix_url)) {\r\n        throw \'Field "zabbix_url" must contain a schema\';\r\n    }\r\n\r\n}\r\n\r\ntry {\r\n    var params = JSON.parse(value);\r\n\r\n    validateParams(params);\r\n\r\n    var req = new HttpRequest(),\r\n        fields = {},\r\n        result = {tags: {}};\r\n\r\n    if (typeof params.HTTPProxy === \'string\' && params.HTTPProxy.trim() !== \'\') {\r\n        req.setProxy(params.HTTPProxy);\r\n    }\r\n\r\n    req.addHeader(\'Content-Type: application/json; charset=utf-8\');\r\n    req.addHeader(\'Authorization: Bearer \' + params.bot_token);\r\n\r\n    params.mattermost_url = params.mattermost_url.replace(/\\/+$/, \'\');\r\n    params.zabbix_url = params.zabbix_url.replace(/\\/+$/, \'\');\r\n\r\n    var APIEndpoint = params.mattermost_url + \'/api/v4/\';\r\n\r\n    var Mattermost = {\r\n        post_message: APIEndpoint + \'posts\',\r\n        get_channel: APIEndpoint + \'channels/{0}\',\r\n        get_team: APIEndpoint + \'teams/{0}\',\r\n        chat_update: APIEndpoint + \'posts/{0}\',\r\n        direct_channel: APIEndpoint + \'channels/direct\',\r\n        channel_byname: APIEndpoint + \'teams/name/{0}/channels/name/{1}\',\r\n        user_byname: APIEndpoint + \'users/username/{0}\',\r\n        bot_user: APIEndpoint + \'users/me\'\r\n\r\n    };\r\n\r\n    params.send_mode = params.send_mode.toLowerCase();\r\n    params.send_mode = params.send_mode in SEND_MODE_HANDLERS\r\n        ? params.send_mode\r\n        : \'alarm\';\r\n\r\n    SEND_MODE_HANDLERS[params.send_mode](req, params);\r\n\r\n    if (params.event_source === \'0\') {\r\n        return JSON.stringify(result);\r\n    }\r\n    else {\r\n        return \'OK\';\r\n    }\r\n}\r\ncatch (error) {\r\n    Zabbix.log(4, \'[ Mattermost Webhook ] Mattermost notification failed: \' + error);\r\n    throw \'Mattermost notification failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__mattermost_message_link}','Open in Mattermost: {EVENT.TAGS.__mattermost_channel_name}','','0'),
('84','4','MS Teams','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nvar SEVERITY_COLORS = [\r\n	\'#97AAB3\',\r\n	\'#7499FF\',\r\n	\'#FFC859\',\r\n	\'#FFA059\',\r\n	\'#E97659\',\r\n	\'#E45959\',\r\n	\'#009900\',\r\n	\'#1F1F1F\'\r\n],\r\n	serviceLogName = \'MS Teams Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	MSTeams = CWebhook;\r\n\r\nMSTeams.prototype.addBodyFact = function (name, value) {\r\n	if (!CParamValidator.isDefined(this.data.sections[0].facts)) {\r\n		this.data.sections[0].facts = [];\r\n	}\r\n	this.data.sections[0].facts.push({name: name, value: value});\r\n}\r\n\r\nMSTeams.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({teams_endpoint: {type: \'string\'}, event_source: {type: \'string\'}, alert_subject: {type: \'string\'},\r\n		alert_message: {type: \'string\'}, host_ip: {type: \'string\', default: \'\'}, zabbix_url: {type: \'string\', url: true},\r\n		use_default_message: {type: \'boolean\', default: false}, event_nseverity: {type: \'integer\', default: 7}}, this.params);\r\n	var actionName = \'Zabbix Home\';\r\n	if (!CParamValidator.inArray(this.params.event_source, [\'0\',\'3\',\'4\'])\r\n		|| this.params.alert_message.startsWith("NOTE: Escalation canceled:")) {\r\n		this.params[\'use_default_message\'] = true;\r\n	}\r\n	if (this.params.event_source === \'0\') {\r\n		CParamValidator.validate({event_id: {type: \'integer\'}, trigger_id: {type: \'integer\'}}, this.params);\r\n		actionName = \'Event Info\';\r\n	}\r\n	var actionURL = CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id);\r\n	if (this.params.event_value === \'0\') {\r\n		this.params.event_nseverity = 6;\r\n	}\r\n	this.data = {\r\n		themeColor: SEVERITY_COLORS[this.params.event_nseverity].replace(\'#\', \'\'),\r\n		summary: this.params.alert_subject,\r\n		sections: [{\r\n			markdown: \'false\',\r\n			activityTitle: this.params.alert_subject,\r\n			text: (this.params.event_source === \'0\' && !this.params.use_default_message) ? this.params.trigger_description : this.params.alert_message\r\n		}],\r\n		potentialAction: [{\r\n			\'@type\': \'OpenUri\',\r\n			name: actionName,\r\n			targets: [{\r\n				os: \'default\',\r\n				uri: actionURL\r\n			}]\r\n		}]\r\n	};\r\n};\r\n\r\nMSTeams.prototype.makeUpDefaultMessage = function () {\r\n	if (!this.params.use_default_message) {\r\n		if (!CParamValidator.isEmpty(this.params.host_name) && CParamValidator.isMacroSet(this.params.host_name, \'HOST.NAME\')) {\r\n			this.addBodyFact(\'Host\', this.params.host_name + ((!CParamValidator.isEmpty(this.params.host_ip)) ? \' [\' + this.params.host_ip + \']\' : \'\'));\r\n		}\r\n		if (!CParamValidator.isEmpty(this.params.event_severity) && CParamValidator.isMacroSet(this.params.event_severity, \'EVENT.SEVERITY\')) {\r\n			this.addBodyFact(\'Severity\', this.params.event_severity);\r\n		}\r\n		if (!CParamValidator.isEmpty(this.params.event_opdata) && CParamValidator.isMacroSet(this.params.event_opdata, \'EVENT.OPDATA\')) {\r\n			this.addBodyFact(\'Operational data\', this.params.event_opdata);\r\n		}\r\n		if (!CParamValidator.isEmpty(this.params.event_tags) && CParamValidator.isMacroSet(this.params.event_tags, \'EVENT.TAGS\')) {\r\n			this.addBodyFact(\'Event tags\', this.params.event_tags);\r\n		}\r\n\r\n		Object.keys(this.params).forEach(function (key) {\r\n			if (key.startsWith(\'fact_\') && this.params[key] !== \'\') {\r\n				this.addBodyFact(key.substring(5), this.params[key]);\r\n			}\r\n			else if (key.startsWith(\'openUri_\') && this.params[key] !== \'\' && !this.params[key].startsWith(\'{\')) {\r\n				this.data.potentialAction.push({\r\n					\'@type\': \'OpenUri\',\r\n					name: key.substring(8),\r\n					targets: [{\r\n						os: \'default\',\r\n						uri: this.params[key]\r\n					}]\r\n				});\r\n			}\r\n		});\r\n	}\r\n}\r\n\r\nconst htmlMultiline = function (text) {\r\n	return text.replace(/(?:\\r\\n|\\r|\\n)/g, \'<br>\');\r\n}\r\n\r\nMSTeams.prototype.sendRequest = function () {\r\n	this.request.addHeaders({"Content-Type": "application/json"});\r\n	var response = this.request.plainRequest(\'POST\', this.params.teams_endpoint, JSON.stringify(this.data));\r\n\r\n	if (response !== \'1\') {\r\n		Logger.log(Logger.WARN, \'FAILED with response: \' + response);\r\n		throw response;\r\n	}\r\n	return \'OK\';\r\n};\r\n\r\nMSTeams.prototype.onProblem = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	if (!this.params.use_default_message) {\r\n		this.addBodyFact(\'Event time\', this.params.event_time + \' \' + this.params.event_date);\r\n		this.makeUpDefaultMessage();\r\n	}\r\n	this.data.sections[0].text = htmlMultiline(this.data.sections[0].text);\r\n\r\n	return this.sendRequest();\r\n}\r\n\r\nMSTeams.prototype.onUpdate = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	if (!this.params.use_default_message) {\r\n		this.data.sections[0].text = this.params.event_update_user + \' \' + this.params.event_update_action + \'.\';\r\n		if (this.params.event_update_message) {\r\n			this.data.sections[0].text += \'<br>Message:<br>\' + this.params.event_update_message;\r\n		}\r\n		this.addBodyFact(\'Event update time\', this.params.event_update_time + \' \' + this.params.event_update_date);\r\n		this.makeUpDefaultMessage();\r\n	}\r\n	this.data.sections[0].text = htmlMultiline(this.data.sections[0].text);\r\n\r\n	return this.sendRequest();\r\n}\r\n\r\nMSTeams.prototype.onResolve = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	if (!this.params.use_default_message) {\r\n		this.addBodyFact(\'Recovery time\', this.params.event_recovery_time + \' \' + this.params.event_recovery_date);\r\n		this.makeUpDefaultMessage();\r\n	}\r\n	this.data.sections[0].text = htmlMultiline(this.data.sections[0].text);\r\n\r\n	return this.sendRequest();\r\n}\r\n\r\nMSTeams.prototype.onDiscovery = function (alert) {\r\n	return this.onProblem(alert);\r\n}\r\n\r\nMSTeams.prototype.onAutoreg = function (alert) {\r\n	return this.onProblem(alert);\r\n}\r\n\r\ntry {\r\n	var hook = new MSTeams(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','0','0','','','https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/msteams\r\n\r\n1. Add official Zabbix webhook connector from MS Teams apps for the channel, where you want to receive notifications.\r\n2. Create Incoming webhook for your channel.\r\n3. In the Zabbix web interface go to Administration → Macros section. Setup the global macro "{$ZABBIX.URL}" which will contain the URL to the Zabbix frontend. \r\n4. On this page replace placeholder <PLACE WEBHOOK URL HERE> with the incoming webhook URL, created during the webhook setup in MS Teams.\r\n5. To receive Zabbix notifications in MS Teams, you need to create a Zabbix user and add Media with the MS Teams media type. Make sure this user has access to all hosts for which you would like problem notifications to be sent to MS Teams.','0'),
('85','4','MS Teams Workflow','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\n\r\nvar serviceLogName = \'MS Teams Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	MSTeams = CWebhook;\r\n\r\nMSTeams.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({\r\n		alert_subject: { type: \'string\' }, alert_message: { type: \'string\' },\r\n		zabbix_url: { type: \'string\', url: true }, teams_endpoint: { type: \'string\', url: true }\r\n	}, this.params);\r\n\r\n	if (this.params.event_source === \'0\') {\r\n		CParamValidator.validate({ event_id: { type: \'integer\' }, trigger_id: { type: \'integer\' } }, this.params);\r\n	}\r\n\r\n	this.body = {\r\n		type: "message",\r\n		attachments: [\r\n			{\r\n				contentType: "application/vnd.microsoft.card.adaptive",\r\n				contentUrl: null,\r\n				content: {\r\n					$schema: "http://adaptivecards.io/schemas/adaptive-card.json",\r\n					type: "AdaptiveCard",\r\n					version: "1.4",\r\n					body: [\r\n						{\r\n							type: "Container",\r\n							items: [\r\n								{\r\n									type: "TextBlock",\r\n									size: "Medium",\r\n									wrap: "true",\r\n									weight: "Bolder",\r\n									text: this.params.alert_subject\r\n								}\r\n							],\r\n							style: "",\r\n							bleed: true\r\n						}\r\n					],\r\n					actions: [\r\n						{\r\n							type: "Action.OpenUrl",\r\n							title: "Event info",\r\n							url: CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id)\r\n						}\r\n					]\r\n				}\r\n			}\r\n		]\r\n	};\r\n\r\n	this.params.alert_message = this.params.alert_message.split(\'\\n\');\r\n\r\n	for (line in this.params.alert_message) {\r\n		this.body.attachments[0].content.body.push({\r\n			type: "TextBlock",\r\n			wrap: "true",\r\n			text: this.params.alert_message[line]\r\n		});\r\n	}\r\n\r\n};\r\n\r\nMSTeams.prototype.sendRequest = function (color) {\r\n	this.body.attachments[0].content.body[0].style = color;\r\n\r\n	this.request.addHeaders({ "Content-Type": "application/json" });\r\n	var response = this.request.plainRequest(\'POST\', this.params.teams_endpoint, JSON.stringify(this.body));\r\n\r\n	var status = this.request.getStatus();\r\n	if (status < 200 || status >= 300) {\r\n		Logger.log(Logger.INFO, \'HTTP code: \' + status + \'. Endpoint response: \' + response);\r\n		throw \'HTTP code: \' + status + \'. Endpoint response: \' + response;\r\n	}\r\n\r\n	return \'OK\';\r\n};\r\n\r\nMSTeams.prototype.onProblem = function () {\r\n	return this.sendRequest("attention");\r\n};\r\n\r\nMSTeams.prototype.onResolve = function () {\r\n	return this.sendRequest("good");\r\n};\r\n\r\nMSTeams.prototype.onUpdate = function () {\r\n	return this.sendRequest("emphasis");\r\n};\r\n\r\nMSTeams.prototype.onDiscovery = function () {\r\n	return this.sendRequest("emphasis");\r\n};\r\n\r\nMSTeams.prototype.onAutoreg = function () {\r\n	return this.sendRequest("emphasis");\r\n};\r\n\r\ntry {\r\n	var hook = new MSTeams(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n};','30s','0','0','','','To set up a webhook, please follow these steps:\r\n\r\n- Create a workflow in MS Teams. You can use the "Post a message in a channel when a webhook request is received" template for it.\r\n- Copy the endpoint URL and place it in the teams_endpoint parameter.\r\n- Set up the global macro {$ZABBIX.URL}, which will contain the URL to the Zabbix frontend.\r\n- Create a Zabbix user and add the MS Teams Workflow media to it.\r\n\r\nFor more detailed instructions, please visit https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/.','0'),
('86','4','Opsgenie','','','','','','','','25','0','0','0','0','1','3','10s','1','var method,\r\n    Media = {\r\n    params: {},\r\n    name: \'\',\r\n    labels: [],\r\n    HTTPProxy: \'\',\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        Media.params = params;\r\n        Media.params.api += Media.params.api.endsWith(\'/\') ? \'\' : \'/\';\r\n        Media.params.web += Media.params.web.endsWith(\'/\') ? \'\' : \'/\';\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        if (typeof HTTPProxy !== \'undefined\' && HTTPProxy.trim() !== \'\') {\r\n            Media.HTTPProxy = HTTPProxy;\r\n        }\r\n    },\r\n\r\n    setTags: function(event_tags_json) {\r\n        if (typeof event_tags_json !== \'undefined\' && event_tags_json !== \'\'\r\n                && event_tags_json !== \'{EVENT.TAGSJSON}\') {\r\n\r\n            try {\r\n                var tags = JSON.parse(event_tags_json),\r\n                    label;\r\n\r\n                tags.forEach(function (tag) {\r\n                    if (typeof tag.tag === \'string\') {\r\n                        label = (tag.tag + (typeof tag.value !== \'undefined\'\r\n                                && tag.value !== \'\' ? (\':\' + tag.value) : \'\')).replace(/\\s/g, \'_\');\r\n                        Media.labels.push(label);\r\n                    }\r\n                });\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Failed to parse "event_tags_json" param\');\r\n            }\r\n        }\r\n    },\r\n\r\n    request: function (method, query, data, allow_404) {\r\n        if (typeof(allow_404) === \'undefined\') {\r\n            allow_404 = false;\r\n        }\r\n\r\n        [\'api\', \'token\'].forEach(function (field) {\r\n            if (typeof Media.params !== \'object\' || typeof Media.params[field] === \'undefined\'\r\n                    || Media.params[field] === \'\') {\r\n                throw \'Required \' + Media.name + \' param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = Media.params.api + query,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'Authorization: \' + Media.params.token);\r\n        request.setProxy(Media.HTTPProxy);\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Sending request: \' +\r\n            url + ((typeof data === \'string\') ? (\'\\n\' + data) : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Failed to parse response.\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if ((request.getStatus() < 200 || request.getStatus() >= 300)\r\n                && (!allow_404 || request.getStatus() !== 404)) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null) {\r\n                if (typeof response.errors === \'object\' && Object.keys(response.errors).length > 0) {\r\n                    message += \': \' + JSON.stringify(response.errors);\r\n                }\r\n                else if (typeof response.errorMessages === \'object\' && Object.keys(response.errorMessages).length > 0) {\r\n                    message += \': \' + JSON.stringify(response.errorMessages);\r\n                }\r\n                else if (typeof response.message === \'string\') {\r\n                    message += \': \' + response.message;\r\n                }\r\n            }\r\n\r\n            throw message + \' Check debug log for more information.\';\r\n        }\r\n\r\n        return {\r\n            status: request.getStatus(),\r\n            response: response\r\n        };\r\n    },\r\n\r\n    getAlertId: function (requestId) {\r\n        status_counter = params.status_counter || 25; \r\n        do {\r\n            resp = Media.request(\'get\', \'requests/\' + requestId, undefined, true);\r\n        status_counter -= 1;            \r\n        }\r\n        while ( status_counter > 0 && \r\n            ( \r\n            typeof resp.response !== \'object\' || \r\n            typeof resp.response.data === \'undefined\' ||\r\n            resp.response.data.success === false &&\r\n                !resp.response.data.status.includes("There is no open alert") &&\r\n                !resp.response.data.status.includes("Alert is already")\r\n            ) \r\n        );\r\n\r\n        if (typeof resp.response !== \'object\' || typeof resp.response.data === \'undefined\') {\r\n            throw \'Cannot get \' + Media.name + \' issue ID. Check debug log for more information.\';\r\n        }\r\n        else if (resp.response.data.success === false ) {\r\n            throw Media.name + \': Operation status (\' + resp.response.data.status + \')\';\r\n        }\r\n\r\n        return resp;\r\n    }\r\n};\r\n\r\ntry {\r\n    var result = {tags: {}},\r\n        params = JSON.parse(value),\r\n        media = {},\r\n        fields = {},\r\n        resp = {},\r\n        responders = [],\r\n        tags = [],\r\n        required_params = [\r\n            \'alert_subject\',\r\n            \'alert_message\',\r\n            \'event_id\',\r\n            \'event_source\',\r\n            \'event_value\',\r\n            \'event_update_status\',\r\n            \'opsgenie_api\',\r\n            \'opsgenie_web\',\r\n            \'opsgenie_token\'\r\n        ],\r\n        severities = [\r\n            \'not_classified\',\r\n            \'information\',\r\n            \'warning\',\r\n            \'average\',\r\n            \'high\',\r\n            \'disaster\',\r\n            \'resolved\',\r\n            \'default\'\r\n        ],\r\n        priority;\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (required_params.indexOf(key) !== -1 && params[key].trim() === \'\') {\r\n                throw \'Parameter "\' + key + \'" cannot be empty.\';\r\n            }\r\n            if (key.startsWith(\'opsgenie_\')) {\r\n                media[key.substring(9)] = params[key];\r\n            }\r\n        });\r\n\r\n    // Possible values of event_source:\r\n    // 0 - Trigger, 1 - Discovery, 2 - Autoregistration, 3 - Internal.\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: "\' + params.event_source + \'".\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check event_value for trigger-based and internal events.\r\n    // Possible values: 1 for problem, 0 for recovering\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check event_update_status only for trigger-based events.\r\n    // Possible values: 0 - Webhook was called because of problem/recovery event, 1 - Update operation.\r\n    if (params.event_source === \'0\' && params.event_update_status !== \'0\' && params.event_update_status !== \'1\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check event_id for a numeric value.\r\n    if (isNaN(parseInt(params.event_id)) || params.event_id < 1) {\r\n        throw \'Incorrect "event_id" parameter given: \' + params.event_id + \'\\nMust be a positive number.\';\r\n    }\r\n\r\n    if ((params.event_source === \'1\' || params.event_source === \'2\')  && params.event_value === \'0\') {\r\n        throw \'Recovery operations are supported only for Trigger and Internal actions.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    priority = params[\'severity_\' + severities[params.event_nseverity]];\r\n    params.zbxurl = params.zbxurl + (params.zbxurl.endsWith(\'/\') ? \'\' : \'/\');\r\n\r\n    Media.name = \'Opsgenie\';\r\n    Media.setParams(media);\r\n    Media.params.token = \'GenieKey \' + Media.params.token;\r\n    Media.setProxy(params.HTTPProxy);\r\n    Media.setTags(params.event_tags_json); // Set Media.labels\r\n\r\n    // Create an issue.\r\n    // Numeric value of the event that triggered an action (1 for problem, 0 for recovering).\r\n    // Numeric value of the problem update status. Possible values:\r\n    // 0 - Webhook was called because of problem/recovery event, 1 - Update operation.\r\n    if ((params.event_source == 0 && params.event_value == 1 && params.event_update_status == 0)\r\n            || (params.event_source == 3 && params.event_value == 1)\r\n            || params.event_source == 1 || params.event_source == 2) {\r\n        fields.message = params.alert_subject;\r\n        fields.alias = params.event_id;\r\n        fields.description = params.alert_message;\r\n        fields.priority = priority;\r\n        fields.source = \'Zabbix\';\r\n\r\n        if (params.event_source === \'0\') {\r\n            fields.details = {\r\n                \'Zabbix server\': params.zbxurl,\r\n                Problem: params.zbxurl + \'tr_events.php?triggerid=\' + params.trigger_id + \'&eventid=\' + params.event_id\r\n            };\r\n        }\r\n        else {\r\n            fields.details = {\'Zabbix server\': params.zbxurl};\r\n        }\r\n\r\n        if (typeof params.opsgenie_teams === \'string\') {\r\n            responders = params.opsgenie_teams.split(\',\');\r\n            fields.responders = responders.map(function(team) {\r\n                return {type: \'team\', name: team.trim()};\r\n            });\r\n        }\r\n\r\n        fields.tags = Media.labels;\r\n        if (typeof params.opsgenie_tags === \'string\') {\r\n            tags = params.opsgenie_tags.split(\',\');\r\n            tags.forEach(function(item) {\r\n                fields.tags.push(item.trim());\r\n            });\r\n        }\r\n\r\n        resp = Media.request(\'post\', \'\', fields);\r\n        if (typeof resp.response !== \'object\' || typeof resp.response.result === \'undefined\') {\r\n            throw \'Cannot create \' + Media.name + \' issue. Check debug log for more information.\';\r\n        }\r\n\r\n        if (resp.status === 202) {\r\n            resp = Media.getAlertId(resp.response.requestId);\r\n            if (params.event_source == 0 && params.event_value == 1 && params.event_update_status == 0) {\r\n                result.tags.__zbx_ops_issuekey = resp.response.data.alertId;\r\n                result.tags.__zbx_ops_issuelink = Media.params.web + \'alert/detail/\' + resp.response.data.alertId;\r\n            }\r\n        }\r\n        else {\r\n            throw Media.name + \' response code is unexpected. Check debug log for more information.\';\r\n        }\r\n    }\r\n    // Update or close the created issue.\r\n    else {\r\n        fields.user = (params.event_value != 0) ? params.zbxuser : \'\';\r\n        fields.note = params.alert_message;\r\n        if ( [0, 3].indexOf(parseInt(params.event_source)) > -1  && params.event_value == 0 ) {\r\n            // skip sending of close request from update operation(mandatory when both update & recovery operations are defined in action)  \r\n            method = params.event_update_status == 0 ? "close" : "skip";\r\n        }\r\n        else if ( params.event_source == 0 && params.event_value == 1 && params.event_update_status == 1 && params.event_update_action.includes(\'acknowledged\')) {\r\n            method = params.event_update_action.includes(\'unacknowledged\') ? "unacknowledge" : "acknowledge";\r\n        }\r\n        else {\r\n            method = "notes";\r\n        }\r\n\r\n        if (method !== "skip") {\r\n        resp = Media.request(\'post\', params.event_id + \'/\' + method +\'?identifierType=alias\', fields);\r\n\r\n        if (typeof resp.response !== \'object\' || typeof resp.response.result === \'undefined\') {\r\n            throw \'Cannot update \' + Media.name + \' issue. Check debug log for more information.\';\r\n        }\r\n\r\n        if (resp.status === 202) {\r\n            resp = Media.getAlertId(resp.response.requestId);\r\n        }\r\n        else {\r\n            throw Media.name + \' response code is unexpected. Check debug log for more information.\';\r\n        }\r\n    }\r\n    }\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ \' + Media.name + \' Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_ops_issuelink}','Opsgenie: {EVENT.TAGS.__zbx_ops_issuekey}','Please refer to https://docs.opsgenie.com/docs/alert-api and https://www.zabbix.com/documentation/7.4/manual/config/notifications/media/webhook#example_scripts.\r\n  \r\nSet global macro {$ZABBIX.URL} with your Zabbix server URL.\r\nAdd dedicated user with media type "Opsgenie".\r\nChange the values of the variables opsgenie_api (https://api.opsgenie.com/v2/alerts or https://api.eu.opsgenie.com/v2/alerts),\r\nopsgenie_web (for example, https://myzabbix.app.opsgenie.com), opsgenie_token.','0'),
('87','4','OTRS CE','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nconst SEVERITIES = ["not_classified", "information", "warning", "average", "high", "disaster"],\r\n	serviceLogName = \' ((OTRS)) CE Webhook \',\r\n	Logger = new CLogger(serviceLogName),\r\n	OTRS = CWebhook;\r\n\r\nOTRS.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({alert_subject: {type: \'string\'}, alert_message: {type: \'string\'},\r\n		event_nseverity: {type: \'integer\', default: -1}, otrs_url: {type: \'string\', url: true}, otrs_auth_user: {type: \'string\'},\r\n		otrs_auth_password: {type: \'string\'}, otrs_customer: {type: \'string\'}, otrs_default_priority_id: {type: \'integer\', min: 1, max: 5},\r\n		otrs_queue: {type: \'string\'}, otrs_ticket_type: {type: \'string\'}, otrs_ticket_state: {type: \'string\'}, otrs_time_unit: {type: \'integer\'},\r\n		otrs_closed_state_id: {type: \'integer\', default: 0}, zabbix_url: {type: \'string\', url: true}}, this.params);\r\n	this.params.entrypoint = \'/nph-genericinterface.pl/Webservice/ZabbixTicketConnector/Ticket\';\r\n\r\n	var priority;\r\n	if (this.params.event_nseverity >= 0 && this.params.event_nseverity < SEVERITIES.length) {\r\n		priority = this.params[\'severity_\' + SEVERITIES[this.params.event_nseverity]];\r\n	}\r\n	this.priority = (CParamValidator.isDefined(priority)) ? priority.trim() : this.params.otrs_default_priority_id;\r\n\r\n	if (this.params.event_source === \'0\') {\r\n		CParamValidator.validate({trigger_id: {type: \'integer\'}, event_id: {type: \'integer\'}}, this.params);\r\n		this.params.zabbix_url = CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id);\r\n		this.params.alert_message = this.params.alert_subject + \'\\n\' + this.params.alert_message + \'\\n\' +\r\n			this.params.zabbix_url + \'\\n\';\r\n	}\r\n	if (this.params.event_value != \'0\' && CParamValidator.isMacroSet(this.params.otrs_ticket_id)) {\r\n		this.params.event_update_status = \'1\';\r\n	}\r\n	this.dynamicFields = {}\r\n	Object.keys(this.params).forEach(function (key) {\r\n		if (key.startsWith(\'dynamicfield_\')) {\r\n			this.dynamicFields[key.substring(13)] = this.params[key];\r\n		}\r\n	});\r\n\r\n	this.data = {\r\n		Article: {\r\n			Subject: this.params.alert_subject,\r\n			Body: (CParamValidator.isDefined(this.params.alert_message)) ? this.params.alert_message : \'\',\r\n			TimeUnit: this.params.otrs_time_unit.toString(),\r\n			ContentType: \'text/plain; charset=utf8\'\r\n		}\r\n	};\r\n\r\n	this.result = {tags: {}};\r\n};\r\n\r\nOTRS.prototype.sendRequest = function (method) {\r\n	var url = this.params.otrs_url + this.params.entrypoint +\r\n		\'?UserLogin=\' + encodeURIComponent(this.params.otrs_auth_user) +\r\n		\'&Password=\' + encodeURIComponent(this.params.otrs_auth_password);\r\n\r\n	var response = this.request.jsonRequest(method, url, this.data);\r\n\r\n	if (!CParamValidator.isType(response, \'object\')) {\r\n		Logger.log(Logger.INFO, \'API response ERROR: \' + response);\r\n		throw \'Unknown error. Check debug log for more information.\';\r\n	}\r\n	if (this.request.getStatus() < 200 || this.request.getStatus() >= 300) {\r\n		var message = \'status code \' + this.request.getStatus();\r\n		Logger.log(Logger.INFO, \'API response ERROR with \' + message + \': \' + response);\r\n		throw \'Request failed with \' + message + \'. Check debug log for more information.\';\r\n	}\r\n	if (CParamValidator.isDefined(response.Error) && Object.keys(response.Error).length > 0) {\r\n		Logger.log(Logger.INFO, \'API response ERROR: \' + JSON.stringify(response.Error));\r\n		throw \'Request failed: \' + JSON.stringify(response.Error);\r\n	}\r\n\r\n	return {\r\n		status: this.request.getStatus(),\r\n		response: response\r\n	};\r\n};\r\n\r\nOTRS.prototype.createTicket = function () {\r\n	this.data[\'Ticket\'] = {\r\n		Title: this.params.alert_subject,\r\n		Queue: this.params.otrs_queue,\r\n		Type: this.params.otrs_ticket_type,\r\n		State: this.params.otrs_ticket_state,\r\n		PriorityID: this.priority.toString(),\r\n		CustomerUser: this.params.otrs_customer\r\n	}\r\n\r\n	var result = this.sendRequest(\'post\');\r\n\r\n	if (!CParamValidator.isDefined(result.response.TicketID) || result.status != 200) {\r\n		throw \'Cannot create ((OTRS)) CE ticket. Check debug log for more information.\';\r\n	}\r\n\r\n	return result.response.TicketID;\r\n}\r\n\r\nOTRS.prototype.updateTicket = function () {\r\n	CParamValidator.validate({otrs_ticket_id: {type: \'string\'}, entrypoint: {type: \'string\'}}, this.params);\r\n	this.params.entrypoint += \'/\' + encodeURIComponent(this.params.otrs_ticket_id);\r\n\r\n	var result = this.sendRequest(\'put\');\r\n\r\n	if (!CParamValidator.isDefined(result.response.TicketID) || result.status != 200) {\r\n		throw \'Cannot update ((OTRS)) CE ticket. Check debug log for more information.\';\r\n	}\r\n\r\n	return result.response.TicketID;\r\n}\r\n\r\nOTRS.prototype.onProblem = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	if (CParamValidator.isDefined(alert.source) && CParamValidator.inArray(alert.source, [\'trigger\', \'service\', \'internal\'])) {\r\n		if (Object.keys(this.dynamicFields).length > 0) {\r\n			this.data.DynamicField = [];\r\n			Object.keys(this.dynamicFields).forEach(function(field) {\r\n				if (field !== undefined) {\r\n					if (this.dynamicFields[field].match(/^\\d{4}[.-]\\d{2}[.-]\\d{2}$/)) {\r\n						this.dynamicFields[field] = this.dynamicFields[field].replace(/\\./g, \'-\');\r\n					}\r\n	\r\n					this.data.DynamicField.push({Name: field, Value: this.dynamicFields[field]});\r\n				}\r\n			});\r\n		}\r\n		const ticket_id = this.createTicket(alert);\r\n		this.result.tags.__zbx_otrs_ticket_id = ticket_id;\r\n		this.result.tags.__zbx_otrs_ticketlink = this.params.otrs_url + \'index.pl?Action=AgentTicketZoom;TicketID=\' + ticket_id;\r\n\r\n		return this.result;\r\n	}\r\n	return this.createTicket();\r\n}\r\n\r\nOTRS.prototype.onUpdate = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	this.updateTicket();\r\n\r\n	return this.result;\r\n}\r\n\r\nOTRS.prototype.onResolve = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	if (this.params.otrs_closed_state_id > 0) {\r\n		this.data[\'Ticket\'] = {\r\n			StateID: this.params.otrs_closed_state_id\r\n		}\r\n	}\r\n	this.updateTicket();\r\n\r\n	return this.result;\r\n}\r\n\r\nOTRS.prototype.onDiscovery = function (alert) {\r\n	return this.onProblem(alert);\r\n}\r\n\r\nOTRS.prototype.onAutoreg = function (alert) {\r\n	return this.onProblem(alert);\r\n}\r\n\r\ntry {\r\n	var hook = new OTRS(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_otrs_ticketlink}','((OTRS)) CE: ticket #{EVENT.TAGS.__zbx_otrs_ticket_id}','This media type integrates your Zabbix installation with your ((OTRS)) CE installation using the Zabbix webhook feature.\r\n\r\n((OTRS)) CE configuration:\r\n\r\n1. Create a new web service. To do so, navigate to "Admin" → "Web services" and import the "ZabbixTicketConnector.yml" file (it can be found in the official Zabbix repository next to the media type file).\r\n\r\n2. Create a new customer.\r\n\r\n3. Create a new customer user. Select the ID of the customer that you created in the previous step.\r\n\r\n4. Create a new agent. Depending on the ticket queue you want to use for tickets created by the webhook, set the "RW" permission for the group that this ticket queue belongs to. In the example below, if you want to use the "Misc" queue, you must set the "RW" permission for the group "users".\r\n\r\nZabbix configuration:\r\n\r\n1. Before you can start using the ((OTRS)) CE webhook, set the global macro "{$ZABBIX.URL}":\r\n- In the Zabbix web interface, go to "Administration" → "Macros" in the top-left dropdown menu.\r\n- Set the global macro "{$ZABBIX.URL}" to the URL of the Zabbix frontend. The URL should be either an IP address, a fully qualified domain name, or localhost.\r\n- Specifying a protocol is mandatory, whereas the port is optional. Depending on the web server configuration, you might also need to append "/zabbix" to the end of URL. Good examples:\r\n  - http://zabbix.com\r\n  - https://zabbix.lan/zabbix\r\n  - http://server.zabbix.lan/\r\n  - http://localhost\r\n  - http://127.0.0.1:8080\r\n- Bad examples:\r\n  - zabbix.com\r\n  - http://zabbix/\r\n\r\n2. Set the following webhook parameters:\r\n- otrs_auth_user - the username of the agent\r\n- otrs_auth_password - the password of the agent\r\n- otrs_customer - the email of the customer user\r\n- otrs_queue - the queue that will be used for tickets created by the webhook\r\n- otrs_url - the frontend URL of your ((OTRS)) CE installation (for example, "https://otrs.example.com/otrs")\r\n\r\n3. If you want to prioritize issues according to the severity values in Zabbix, you can define mapping parameters (create them as additional webhook parameters):\r\n- severity_<name> - the ((OTRS)) CE priority ID (<name> in the parameter name can be one of the following values: "not_classified", "information", "warning", "average", "high", "disaster")\r\n\r\n4. If you have dynamic fields in ((OTRS)) CE and want them to be filled with values from Zabbix, add webhook parameters in the format "dynamicfield_<((OTRS)) CE dynamic field name>", similarly to the previous step. Dynamic fields can only be of the types "text", "textarea", "checkbox", or "date".\r\n\r\n5. If you want the webhook to close tickets related to **resolved** problems in Zabbix, you can change the following parameter value:\r\n- otrs_closed_state_id - ((OTRS)) CE state ID for closed tasks (possible values: 0 - Disable tickets closing, >0 - State ID from the State Management page).\r\n\r\n6. If you use the ticket type feature, you can change the type of the created tickets:\r\n- otrs_ticket_type - ((OTRS)) CE ticket type (set to "Unclassified" by default; present on fresh installations).\r\n\r\n7. Click the "Enabled" checkbox to enable the mediatype and click the "Update" button to save the webhook settings.\r\n\r\n8. Create a Zabbix user and add media:\r\n- To create a new user, go to the "Users" → "Users" section, click the "Create user" button in the top right corner. In the "User" tab, fill in all required fields (marked with red asterisks).\r\n- In the "Media" tab, click "Add" and select the type "OTRS CE" from the drop-down list. Add any value in the "Send to" field: it is not used in the webhook, but is required.\r\n- Make sure this user has access to all hosts for which you would like problem notifications to be sent to ((OTRS)) CE.\r\n\r\n9. Done! You can now start using this media type in actions and create tickets.\r\n\r\nYou can find the latest version of this media and additional information in the official Zabbix repository:\r\nhttps://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/otrs_ce','0'),
('88','4','PagerDuty','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nvar severityMapping = [\r\n	\'info\',\r\n	\'info\',\r\n	\'warning\',\r\n	\'warning\',\r\n	\'error\',\r\n	\'critical\'\r\n],\r\n	serviceLogName = \'PagerDuty Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	PagerDuty = CWebhook;\r\n\r\nfunction getDefaultEventData(data, params) {\r\n	data.event_action = \'trigger\';\r\n	data.payload.custom_details = {\r\n		\'Alert message\': params.alert_message\r\n	};\r\n	Object.keys(params).forEach(function (key) {\r\n		if (key.startsWith(\'customdetails_\') && !CParamValidator.isEmpty(params[key])) {\r\n			data.payload.custom_details[key.substring(14)] = params[key];\r\n		}\r\n	});\r\n	data.client = \'Zabbix\';\r\n	data.client_url = params.zabbix_url;\r\n\r\n	return data;\r\n};\r\n\r\nPagerDuty.prototype.onCheckParams = function () {\r\n	this.params.url = \'https://events.pagerduty.com/v2/enqueue\';\r\n	CParamValidator.validate({api_token: {type: \'string\'}, event_id: {type: \'integer\'},\r\n		alert_subject: {type: \'string\'}, host_ip: {type: \'string\', default: \'\'}, zabbix_url: {type: \'string\', url: true},\r\n		event_nseverity: {type: \'integer\', min: 0, max: 5, default: 0}}, this.params);\r\n	if (CParamValidator.inArray(this.params.event_source, [\'0\',\'3\',\'4\'])) {\r\n		CParamValidator.validate({host_name: {type: \'string\', default: \'\'}}, this.params);\r\n		if (this.params.event_source === \'0\') {\r\n			CParamValidator.validate({trigger_id: {type: \'integer\'}, event_update_status: {type: \'string\', array: [\'0\', \'1\']},\r\n				event_ack: {type: \'boolean\'}}, this.params);\r\n		}\r\n		else {\r\n			CParamValidator.validate({alert_message: {type: \'string\'}, event_ack: {type: \'boolean\', default: false}}, this.params);\r\n		}\r\n	}\r\n	this.data = {\r\n		routing_key: this.params.api_token,\r\n		dedup_key: String(this.params.event_id),\r\n		payload: {\r\n			summary: this.params.alert_subject,\r\n			source: (!CParamValidator.isEmpty(this.params.host_name)) ? (this.params.host_name +\r\n				((!CParamValidator.isEmpty(this.params.host_ip)) ? \' : \' + this.params.host_ip : \'\')) : \'Zabbix\',\r\n			severity: severityMapping[this.params.event_nseverity],\r\n		}\r\n	}\r\n}\r\n\r\nPagerDuty.prototype.onProblem = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	this.data = getDefaultEventData(this.data, this.params);\r\n	if (CParamValidator.isDefined(alert.source) && alert.source === \'Trigger\') {\r\n		this.data.links = [{\r\n			href: CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id),\r\n			text: \'Event link\'\r\n		}];\r\n	}\r\n\r\n	return this.sendRequest();\r\n}\r\n\r\nPagerDuty.prototype.onUpdate = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	if (this.params.event_ack === true) {\r\n		this.data.event_action = \'acknowledge\';\r\n		return this.sendRequest();\r\n	}\r\n	this.data = getDefaultEventData(this.data, this.params);\r\n\r\n	return this.sendRequest();\r\n}\r\n\r\nPagerDuty.prototype.onResolve = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	this.data = getDefaultEventData(this.data, this.params);\r\n	this.data.event_action = \'resolve\';\r\n	\r\n	return this.sendRequest();\r\n}\r\n\r\nPagerDuty.prototype.onDiscovery = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	this.data = getDefaultEventData(this.data, this.params);\r\n	this.data.payload.source = \'Discovery\';\r\n\r\n	return this.sendRequest();\r\n}\r\n\r\nPagerDuty.prototype.onAutoreg = function (alert) {\r\n	return this.onProblem(alert);\r\n}\r\n\r\nPagerDuty.prototype.sendRequest = function () {\r\n	var response = this.request.jsonRequest(\'POST\', this.params.url, this.data);\r\n	if (!CParamValidator.isType(response, \'object\')) {\r\n		Logger.log(Logger.INFO, \'API response ERROR: \' + response);\r\n		throw \'Unknown error. Check debug log for more information.\';\r\n	}\r\n	if (this.request.getStatus() != 202) {\r\n		if (CParamValidator.isType(response.errors, \'array\') && CParamValidator.isType(response.errors[0], \'string\')) {\r\n			throw response.errors[0];\r\n		}\r\n		else {\r\n			throw \'Unknown error. HTTP status: \' + this.request.getStatus();\r\n		}\r\n	}\r\n	if (response.status != \'success\') {\r\n		Logger.log(Logger.INFO, \'API response ERROR: \' + response);\r\n		throw \'Unknown error. Check debug log for more information.\';\r\n	}\r\n\r\n	return \'OK\';\r\n};\r\n\r\ntry {\r\n	var hook = new PagerDuty(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','0','0','','','Please refer to https://v2.developer.pagerduty.com/docs/send-an-event-events-api-v2 and https://www.zabbix.com/documentation/7.4/manual/config/notifications/media/webhook#example_scripts.\r\n\r\nSet global macro {$ZABBIX.URL} with your Zabbix server URL.\r\nAdd a dedicated user with the media type "PagerDuty" and place the integration key in the user\'s "Send to" parameter to integrate into the service.','0'),
('89','4','Pushover','','','','','','','','25','0','0','0','0','0','3','10s','1','try {\r\n    var params = JSON.parse(value),\r\n        request = new HttpRequest(),\r\n        data,\r\n        response,\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'resolved\', color: \'#009900\'},\r\n            {name: \'default\', color: \'#000000\'}\r\n        ],\r\n        priority;\r\n\r\n    if (typeof params.HTTPProxy === \'string\' && params.HTTPProxy.trim() !== \'\') {\r\n        request.setProxy(params.HTTPProxy);\r\n    }\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: "\' + params.event_source + \'".\\nMust be 0-3.\';\r\n    }\r\n\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    priority = params[\'priority_\' + severities[params.event_nseverity].name] || params.priority_default;\r\n\r\n    if (isNaN(priority) || priority < -2 || priority > 2) {\r\n        throw \'"priority" should be -2..2\';\r\n    }\r\n\r\n    if (params.event_source === \'0\' && isNaN(params.triggerid)) {\r\n        throw \'field "triggerid" is not a number\';\r\n    }\r\n\r\n    if (isNaN(params.eventid)) {\r\n        throw \'field "eventid" is not a number\';\r\n    }\r\n\r\n    if (typeof params.message !== \'string\' || params.message.trim() === \'\') {\r\n        throw \'field "message" cannot be empty\';\r\n    }\r\n\r\n    data = {\r\n        token: params.token,\r\n        user: params.user,\r\n        title: params.title,\r\n        message: params.message,\r\n        url: (params.event_source === \'0\') \r\n            ? params.url + \'/tr_events.php?triggerid=\' + params.triggerid + \'&eventid=\' + params.eventid\r\n            : params.url,\r\n        url_title: params.url_title,\r\n        priority: priority\r\n    };\r\n\r\n    if (priority == 2) {\r\n        if (isNaN(params.retry) || params.retry < 30) {\r\n            throw \'field "retry" should be a number with value of at least 30 if "priority" is set to 2\';\r\n        }\r\n\r\n        if (isNaN(params.expire) || params.expire > 10800) {\r\n            throw \'field "expire" should be a number with value of at most 10800 if "priority" is set to 2\';\r\n        }\r\n\r\n        data.retry = params.retry;\r\n        data.expire = params.expire;\r\n    }\r\n\r\n    data = JSON.stringify(data);\r\n    Zabbix.log(4, \'[ Pushover Webhook ] Sending request: \' + params.endpoint + \'\\n\' + data);\r\n\r\n    request.addHeader(\'Content-Type: application/json\');\r\n    response = request.post(params.endpoint, data);\r\n\r\n    Zabbix.log(4, \'[ Pushover Webhook ] Received response with status code \' + request.getStatus() + \'\\n\' + response);\r\n\r\n    if (response !== null) {\r\n        try {\r\n            response = JSON.parse(response);\r\n        }\r\n        catch (error) {\r\n            Zabbix.log(4, \'[ Pushover Webhook ] Failed to parse response received from Pushover\');\r\n            response = null;\r\n        }\r\n    }\r\n\r\n    if (request.getStatus() != 200 || response === null || typeof response !== \'object\' || response.status !== 1) {\r\n        if (response !== null && typeof response === \'object\' && typeof response.errors === \'object\'\r\n                && typeof response.errors[0] === \'string\') {\r\n            throw response.errors[0];\r\n        }\r\n        else {\r\n            throw \'Unknown error. Check debug log for more information.\';\r\n        }\r\n    }\r\n\r\n    return \'OK\';\r\n}\r\ncatch (error) {\r\n    Zabbix.log(4, \'[ Pushover Webhook ] Pushover notification failed: \' + error);\r\n    throw \'Pushover notification failed: \' + error;\r\n}','30s','0','0','','','Please refer to setup guide here: https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/pushover\r\n\r\nSet token parameter with to your Pushover application key.\r\nWhen assigning Pushover media to the Zabbix user - add user key into send to field.','0'),
('90','4','Redmine','','','','','','','','25','0','0','0','0','1','3','10s','1','var Redmine = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        Redmine.params = params;\r\n        if (typeof Redmine.params.url === \'string\') {\r\n            if (!Redmine.params.url.endsWith(\'/\')) {\r\n                Redmine.params.url += \'/\';\r\n            }\r\n        }\r\n    },\r\n\r\n    addCustomFields: function (data, fields) {\r\n        if (typeof fields === \'object\' && Object.keys(fields).length) {\r\n\r\n            data.issue.custom_fields = [];\r\n            Object.keys(fields)\r\n                .forEach(function (field) {\r\n                    var field_value = fields[field];\r\n\r\n                    if (field_value !== undefined) {\r\n                        data.issue.custom_fields.push({ id: field, value: field_value });\r\n                    }\r\n                });\r\n\r\n        }\r\n        return data;\r\n    },\r\n\r\n    request: function (method, query, data) {\r\n        [\'url\', \'access_key\'].forEach(function (field) {\r\n            if (typeof Redmine.params !== \'object\' || typeof Redmine.params[field] === \'undefined\'\r\n                || Redmine.params[field] === \'\' ) {\r\n                throw \'Required param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = Redmine.params.url + query,\r\n            request = new HttpRequest();\r\n\r\n        if (typeof Redmine.HTTPProxy === \'string\' && Redmine.HTTPProxy.trim() !== \'\') {\r\n            request.setProxy(Redmine.HTTPProxy);\r\n        }\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'X-Redmine-API-Key: \' + Redmine.params.access_key);\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ Redmine Webhook ] Sending request: \' +\r\n            url + ((typeof data === \'string\') ? (\' \' + data) : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ Redmine Webhook ] Received response with status code \' + request.getStatus() + \': \' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ Redmine Webhook ] Failed to parse response received from Redmine\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null && typeof response.errors !== \'undefined\'\r\n                && Object.keys(response.errors).length > 0) {\r\n                message += \': \' + JSON.stringify(response.errors);\r\n            }\r\n            else if (response !== null && typeof response.errorMessages !== \'undefined\'\r\n                && Object.keys(response.errorMessages).length > 0) {\r\n                message += \': \' + JSON.stringify(response.errorMessages);\r\n            }\r\n\r\n            throw message + \' Check debug log for more information.\';\r\n        }\r\n\r\n        return {\r\n            status: request.getStatus(),\r\n            response: response\r\n        };\r\n    },\r\n\r\n    getProjectID: function(name) {\r\n        var result = Redmine.request(\'get\', \'projects.json\'),\r\n            project_id;\r\n\r\n        if (result.response) {\r\n            var projects = result.response.projects || [];\r\n\r\n            for (var i in projects) {\r\n                if (projects[i].name === name) {\r\n                    project_id = projects[i].id;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            Zabbix.log(4, \'[ Redmine Webhook ] Failed to retrieve project data.\');\r\n        }\r\n\r\n        if (typeof project_id === \'undefined\') {\r\n            throw \'Cannot find project with name: \' + name;\r\n        }\r\n\r\n        return project_id;\r\n    },\r\n\r\n    createIssue: function(subject, description, priority, fields) {\r\n        var project_id = /^\\d+$/.test(Redmine.params.project)\r\n                ? Redmine.params.project\r\n                : Redmine.getProjectID(Redmine.params.project),\r\n            data = {\r\n                issue: {\r\n                    project_id: project_id,\r\n                    tracker_id: Redmine.params.tracker_id,\r\n                    subject: subject,\r\n                    description: description\r\n                }\r\n            },\r\n            result;\r\n\r\n        if (priority) {\r\n            data.issue.priority_id = priority;\r\n        }\r\n\r\n        result = Redmine.request(\'post\', \'issues.json\', Redmine.addCustomFields(data, fields));\r\n\r\n        if (typeof result.response !== \'object\'\r\n            || typeof result.response.issue.id === \'undefined\'\r\n            || result.status != 201) {\r\n            throw \'Cannot create Redmine issue. Check debug log for more information.\';\r\n        }\r\n\r\n        return result.response.issue.id;\r\n    },\r\n\r\n    updateIssue: function (note, fields, status) {\r\n        var data = {\r\n            issue: {\r\n                notes: note || \'\'\r\n            }\r\n        };\r\n\r\n        if (status) {\r\n            data.issue.status_id = status;\r\n        }\r\n\r\n        Redmine.request(\'put\', \'issues/\' + Redmine.params.issue_key + \'.json\', Redmine.addCustomFields(data, fields));\r\n    }\r\n\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        params_redmine = {},\r\n        params_fields = {},\r\n        params_update = {},\r\n        result = {tags: {}},\r\n        required_params = [\r\n            \'alert_subject\', \'tracker_id\', \'project\',\r\n            \'event_source\', \'event_value\',  \'event_update_status\'\r\n        ],\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'resolved\', color: \'#009900\'},\r\n            {name: null, color: \'#000000\'}\r\n        ],\r\n        priority;\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'redmine_\')) {\r\n                params_redmine[key.substring(8)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'customfield_\')) {\r\n                params_fields[key.substring(12)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'event_update_\')) {\r\n                params_update[key.substring(13)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key].trim() === \'\') {\r\n                throw \'Parameter "\' + key + \'" cannot be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_source === \'0\' && params.event_update_status !== \'0\' && params.event_update_status !== \'1\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n\r\n    if (typeof params_redmine.close_status_id === \'string\' && params_redmine.close_status_id.trim() !== \'\' && !parseInt(params_redmine.close_status_id, 10)) {\r\n        throw \'Incorrect "redmine_close_status_id" parameter given! Must be an integer.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_value === \'0\') {\r\n        throw \'Recovery operations are supported only for trigger-based actions.\';\r\n    }\r\n\r\n    if (params.event_source === \'0\'\r\n        && ((params.event_value === \'1\' && params.event_update_status === \'1\')\r\n            || (params.event_value === \'0\'\r\n                && (params.event_update_status === \'0\' || params.event_update_status === \'1\')))\r\n        && (isNaN(parseInt(params.redmine_issue_key)) || parseInt(params.redmine_issue_key) < 1 )) {\r\n        throw \'Incorrect "redmine_issue_key" parameter given: \' + params.redmine_issue_key +\r\n            \'\\nMust be positive integer.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    priority = params[\'severity_\' + severities[params.event_nseverity].name];\r\n    priority = priority && priority.trim() || severities[7].name;\r\n\r\n    Redmine.setParams(params_redmine);\r\n    Redmine.HTTPProxy = params.HTTPProxy;\r\n\r\n    // Create issue for non trigger-based events.\r\n    if (params.event_source !== \'0\'\r\n        && params.event_value !== \'0\') {\r\n        Redmine.createIssue(params.alert_subject, params.alert_message, priority);\r\n    }\r\n    // Create issue for trigger-based events.\r\n    else if (params.event_value === \'1\' && params_update.status === \'0\') {\r\n        var issue_id = Redmine.createIssue(params.alert_subject,\r\n            params.alert_subject + \'\\n\' + params.alert_message + \'\\n\' +\r\n            params.zabbix_url + (params.zabbix_url.endsWith(\'/\') ? \'\' : \'/\') +\r\n            \'tr_events.php?triggerid=\' + params.trigger_id + \'&eventid=\' + params.event_id + \'\\n\',\r\n            priority,\r\n            params_fields);\r\n\r\n        result.tags.__zbx_redmine_issue_id = issue_id;\r\n        result.tags.__zbx_redmine_issuelink = params.redmine_url +\r\n            (params.redmine_url.endsWith(\'/\') ? \'\' : \'/\') + \'issues/\' + issue_id;\r\n    }\r\n    // Close issue if parameter close_status_id is set and it is a recovery operation\r\n    else if (params.event_value === \'0\' && typeof params_redmine.close_status_id === \'string\' && params_redmine.close_status_id.trim() !== \'\') {\r\n        Redmine.updateIssue(params.alert_subject + \'\\n\' + params.alert_message, params_fields, params_redmine.close_status_id);\r\n    }\r\n    // Update created issue for trigger-based event.\r\n    else {\r\n        Redmine.updateIssue(params.alert_subject + \'\\n\' + params.alert_message, params_fields);\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ Redmine Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_redmine_issuelink}','Redmine: issue #{EVENT.TAGS.__zbx_redmine_issue_id}','','0'),
('91','4','Rocket.Chat','','','','','','','','25','0','0','0','0','1','3','10s','1','var RocketChat = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        RocketChat.params = params;\r\n        if (RocketChat.params.url && RocketChat.params.api_url) {\r\n            if (!RocketChat.params.url.endsWith(\'/\')) {\r\n                RocketChat.params.url += \'/\';\r\n            }\r\n            if (!RocketChat.params.api_url.endsWith(\'/\')) {\r\n                RocketChat.params.api_url += \'/\';\r\n            }\r\n            if (RocketChat.params.api_url.startsWith(\'/\')) {\r\n                RocketChat.params.api_url = RocketChat.params.api_url.substring(1);\r\n            }\r\n\r\n            RocketChat.params.url += RocketChat.params.api_url;\r\n        }\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        RocketChat.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    addFields: function (fields) {\r\n        var data = [];\r\n\r\n        if (typeof fields === \'object\' && Object.keys(fields).length) {\r\n            Object.keys(fields)\r\n                .forEach(function(field) {\r\n                    if (fields[field] === \'\') {\r\n                        Zabbix.log(4, \'[ RocketChat Webhook ] Field "\' + field +\r\n                            \'" can\\\'t be empty. The field ignored.\');\r\n                    }\r\n                    else {\r\n                        try {\r\n                            var parts = field.split(\':\'),\r\n                                prefix = parts[0].split(\'_\');\r\n\r\n                            if (typeof prefix[2] === \'undefined\'\r\n                                    || (prefix[2] === \'p\' && params.event_value === \'1\')\r\n                                    || (prefix[2] === \'r\' && params.event_value === \'0\')) {\r\n                                data.push({\r\n                                    title: field.substring(field.indexOf(\':\') + 1),\r\n                                    value: fields[field],\r\n                                    short: prefix[1] === \'short\'\r\n                                });\r\n                            }\r\n                        }\r\n                        catch (error) {\r\n                            Zabbix.log(4, \'[ RocketChat Webhook ] Can\\\'t parse field "\' + field +\r\n                                \'". The field ignored.\');\r\n                        }\r\n                    }\r\n                });\r\n        }\r\n\r\n        return data;\r\n    },\r\n\r\n    request: function (method, query, data) {\r\n        [\'url\', \'api_url\', \'user_id\', \'user_token\', \'send_to\'].forEach(function (field) {\r\n            if (typeof RocketChat.params !== \'object\' || typeof RocketChat.params[field] === \'undefined\'\r\n                    || RocketChat.params[field] === \'\' ) {\r\n                throw \'Required parameter is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = RocketChat.params.url + query,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'X-Auth-Token:\' + RocketChat.params.user_token);\r\n        request.addHeader(\'X-User-Id:\' + RocketChat.params.user_id);\r\n\r\n        if (typeof RocketChat.HTTPProxy !== \'undefined\' && RocketChat.HTTPProxy !== \'\') {\r\n            request.setProxy(RocketChat.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ RocketChat Webhook ] Sending request: \' + url +\r\n            ((typeof data === \'string\') ? (\'\\n\' + data) : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ RocketChat Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ RocketChat Webhook ] Failed to parse response received from RocketChat\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null && typeof response.message !== \'undefined\') {\r\n                message += \': \' + JSON.stringify(response.message);\r\n            }\r\n            else if (response !== null && typeof response.error !== \'undefined\') {\r\n                message += \': \' + JSON.stringify(response.error);\r\n            }\r\n\r\n            throw message + \'. Check debug log for more information.\';\r\n        }\r\n\r\n        return {\r\n            status: request.getStatus(),\r\n            response: response\r\n        };\r\n    },\r\n\r\n    postMessage: function(use_default_message, message, fields) {\r\n        var data = {\r\n            channel: RocketChat.params.send_to,\r\n            attachments: [{\r\n                collapsed: false,\r\n                color: RocketChat.params.color,\r\n                title: params.alert_subject\r\n            }]\r\n        };\r\n\r\n        if (RocketChat.params.title_link) {\r\n            data.attachments[0].title_link = RocketChat.params.title_link;\r\n        }\r\n\r\n        if (use_default_message) {\r\n            data.attachments[0].text = message;\r\n        }\r\n        else {\r\n            data.attachments[0].fields = RocketChat.addFields(fields);\r\n        }\r\n\r\n        var result = RocketChat.request(\'post\', \'chat.postMessage\', data);\r\n\r\n        if (typeof result.response !== \'object\' || typeof result.response.message._id === \'undefined\') {\r\n            throw \'Cannot send RocketChat message. Check debug log for more information.\';\r\n        }\r\n\r\n        return {\r\n            id: result.response.message._id,\r\n            rid: result.response.message.rid,\r\n            channel: result.response.channel\r\n        };\r\n    },\r\n\r\n    sendMessage: function(update, fields) {\r\n\r\n        var data = {\r\n            message: {\r\n                rid: RocketChat.params.room_id,\r\n                tmid: RocketChat.params.msg_id,\r\n                tshow: true\r\n            }\r\n        };\r\n\r\n        if (update.status === \'0\') {\r\n            data.message.attachments = [{\r\n                collapsed: false,\r\n                color: RocketChat.params.color,\r\n                title: params.alert_subject,\r\n                title_link: RocketChat.params.title_link,\r\n                fields: RocketChat.addFields(fields)\r\n            }];\r\n        }\r\n        else {\r\n            data.message.alias = update.user;\r\n            data.message.msg = update.action;\r\n            if (update.message) {\r\n                data.message.attachments = [{\r\n                    color: RocketChat.params.color,\r\n                    text: update.message\r\n                }];\r\n            }\r\n        }\r\n\r\n        RocketChat.request(\'post\', \'chat.sendMessage\', data);\r\n    },\r\n\r\n    getMessageLink: function(rid, id) {\r\n        var room = RocketChat.request(\'get\', \'rooms.info?roomId=\' + encodeURIComponent(rid)),\r\n            link = params.rc_url +\r\n                (params.rc_url.endsWith(\'/\') ? \'\' : \'/\');\r\n\r\n        switch (room.response.room.t) {\r\n            case \'c\':\r\n                link += \'channel/\' + room.response.room.name + \'?msg=\' + id;\r\n                break;\r\n\r\n            case \'p\':\r\n                link += \'group/\' + room.response.room.name + \'?msg=\' + id;\r\n                break;\r\n\r\n            case \'d\':\r\n                link += \'direct/\' + rid + \'?msg=\' + id;\r\n                break;\r\n\r\n            default:\r\n                Zabbix.log(4, \'[ RocketChat Webhook ] Can\\\'t get room type. Link to message will not be added.\');\r\n        }\r\n\r\n        return link;\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        response,\r\n        fields = {},\r\n        rc = {},\r\n        update = {},\r\n        result = {tags: {}},\r\n        required_params = [\'alert_subject\', \'alert_message\', \'event_source\', \'event_value\'],\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'resolved\', color: \'#009900\'},\r\n            {name: \'default\', color: \'#000000\'}\r\n        ];\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'rc_\')) {\r\n                rc[key.substring(3)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'field_\')) {\r\n                fields[key.substring(6)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'event_update_\')) {\r\n                update[key.substring(13)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key] === \'\') {\r\n                throw \'Parameter "\' + key + \'" can\\\'t be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Forcing parameters for non trigger-based events.\r\n    if (params.event_source !== \'0\') {\r\n        params.use_default_message = \'true\';\r\n        params.event_nseverity = \'0\';\r\n        params.rc_title_link = false;\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n            && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    RocketChat.setParams(rc);\r\n    RocketChat.setProxy(params.HTTPProxy);\r\n    RocketChat.params.color = severities[params.event_nseverity].color;\r\n\r\n    // Send default message if use_default_message === true.\r\n    if (params.use_default_message.toLowerCase() === \'true\') {\r\n        response = RocketChat.postMessage(true, params.alert_message);\r\n        result.tags.__zbx_rc_id = response.id;\r\n        result.tags.__zbx_rc_rid = response.rid;\r\n        result.tags.__zbx_rc_msg_url = RocketChat.getMessageLink(response.rid, response.id);\r\n    }\r\n    // Send message for trigger-based events.\r\n    else if (params.event_value === \'1\' && update.status === \'0\') {\r\n        response = RocketChat.postMessage(false, params.alert_message, fields);\r\n        result.tags.__zbx_rc_id = response.id;\r\n        result.tags.__zbx_rc_rid = response.rid;\r\n        result.tags.__zbx_rc_msg_url = RocketChat.getMessageLink(response.rid, response.id);\r\n    }\r\n    // Send thread message for trigger-based event.\r\n    else {\r\n        RocketChat.sendMessage(update, fields);\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ RocketChat Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_rc_msg_url}','Rocket.Chat','','0'),
('92','4','ServiceNow','','','','','','','','25','0','0','0','0','1','3','10s','1','var ServiceNow = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        ServiceNow.params = params;\r\n        if (typeof ServiceNow.params.url === \'string\') {\r\n            if (!ServiceNow.params.url.endsWith(\'/\')) {\r\n                ServiceNow.params.url += \'/\';\r\n            }\r\n\r\n            ServiceNow.params.url += \'api/now/table/incident\';\r\n        }\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        ServiceNow.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    setFields: function (data, fields) {\r\n        if (typeof fields === \'object\' && Object.keys(fields).length) {\r\n            Object.keys(fields)\r\n                .forEach(function(field) {\r\n                    data[field] = (fields[field].match(/^\\d{4}\\.\\d{2}\\.\\d{2}$/) !== null)\r\n                        ? fields[field].replace(/\\./g, \'-\')\r\n                        : fields[field];\r\n                });\r\n        }\r\n    },\r\n\r\n    request: function (method, data) {\r\n        [\'url\', \'user\', \'password\'].forEach(function (field) {\r\n            if (typeof ServiceNow.params !== \'object\' || typeof ServiceNow.params[field] === \'undefined\'\r\n                || ServiceNow.params[field] === \'\' ) {\r\n                throw \'Required ServiceNow param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = ServiceNow.params.url,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'Authorization: Basic \' + btoa(ServiceNow.params.user + \':\' + ServiceNow.params.password));\r\n\r\n        if (typeof ServiceNow.HTTPProxy !== \'undefined\' && ServiceNow.HTTPProxy !== \'\') {\r\n            request.setProxy(ServiceNow.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ ServiceNow Webhook ] Sending request: \' + url + ((typeof data === \'string\')\r\n            ? (\'\\n\' + data)\r\n            : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ ServiceNow Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ ServiceNow Webhook ] Failed to parse response received from ServiceNow\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null && typeof response.error.message !== \'undefined\'\r\n                && Object.keys(response.error).length > 0) {\r\n                message += \': \' + JSON.stringify(response.error.message);\r\n            }\r\n\r\n            throw message + \' Check debug log for more information.\';\r\n        }\r\n        else if (typeof response.result !== \'object\' || typeof response.result.sys_id === \'undefined\') {\r\n            throw \'Cannot create ServiceNow incident. Check debug log for more information.\';\r\n        }\r\n\r\n        return response.result;\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        fields = {},\r\n        servicenow = {},\r\n        data = {},\r\n        result = {tags: {}},\r\n        required_params = [\r\n            \'alert_subject\', \'alert_message\', \'event_source\', \'event_value\',\r\n            \'event_update_status\', \'event_recovery_value\', \'event_nseverity\'\r\n        ],\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'resolved\', color: \'#009900\'},\r\n            {name: \'default\', color: \'#000000\'}\r\n        ],\r\n        method = \'post\',\r\n        process_tags = true;\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'servicenow_\')) {\r\n                servicenow[key.substring(11)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'u_\')) {\r\n                fields[key] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key] === \'\') {\r\n                throw \'Parameter "\' + key + \'" can\\\'t be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_recovery_value === \'0\') {\r\n        throw \'Recovery operations are supported only for trigger-based actions.\';\r\n    }\r\n\r\n    data.short_description = params.alert_subject;\r\n    data.description = params.alert_message;\r\n    data.comments = params.alert_message;\r\n\r\n    if (typeof params[\'urgency_for_\' + severities[params.event_nseverity].name] !== \'undefined\') {\r\n        data.urgency = params[\'urgency_for_\' + severities[params.event_nseverity].name];\r\n    }\r\n\r\n    ServiceNow.setParams(servicenow);\r\n    ServiceNow.setProxy(params.HTTPProxy);\r\n    ServiceNow.setFields(data, fields);\r\n\r\n    if (params.event_source === \'0\' && (params.event_value === \'0\' || params.event_update_status === \'1\')) {\r\n        process_tags = false;\r\n        method = \'put\';\r\n        delete data.description;\r\n        delete data.urgency;\r\n        ServiceNow.params.url += \'/\' + params.servicenow_sys_id;\r\n    }\r\n\r\n    var response = ServiceNow.request(method, data);\r\n\r\n    if (process_tags) {\r\n        result.tags.__zbx_servicenow_sys_id = response.sys_id;\r\n        result.tags.__zbx_servicenow_link = params.servicenow_url +\r\n            (params.servicenow_url.endsWith(\'/\') ? \'\' : \'/\') + \'incident.do?sys_id=\' + response.sys_id;\r\n        result.tags.__zbx_servicenow_number = response.number;\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ ServiceNow Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_servicenow_link}','ServiceNow: {EVENT.TAGS.__zbx_servicenow_number}','','0'),
('93','4','SIGNL4','','','','','','','','25','0','0','0','0','1','3','10s','1','// SIGNL4 Webhook\r\ntry {\r\n    var response,\r\n        payload,\r\n        params = JSON.parse(value),\r\n        endpoint = \'https://connect.signl4.com/webhook/\',\r\n        request = new HttpRequest();\r\n\r\n    if (typeof params.HTTPProxy === \'string\' && params.HTTPProxy.trim() !== \'\') {\r\n        request.setProxy(params.HTTPProxy);\r\n    }\r\n\r\n    if (typeof params.teamsecret === \'string\' && params.teamsecret.trim() !== \'\') {\r\n        endpoint += params.teamsecret;\r\n        delete params.teamsecret;\r\n    }\r\n    else {\r\n        throw \'The team secret of your SIGNL4 team cannot be empty.\';\r\n    }\r\n\r\n    if (typeof params.Severity === \'string\' && params.Severity === \'{EVENT.SEVERITY}\') {\r\n        params.Severity = \'Not classified\';\r\n    }\r\n\r\n	if (typeof params.User === \'string\' && params.User === \'{USER.FULLNAME}\') {\r\n        params.User = \'\';\r\n    }\r\n\r\n	if (typeof params.Event_Update_Action === \'string\' && params.Event_Update_Action === \'{EVENT.UPDATE.ACTION}\') {\r\n        params.Event_Update_Action = \'\';\r\n    }\r\n\r\n	// Assemble X-S4-ExternalID for two-way integration\r\n	// Format: "ZabbixEventID: 222 ZabbixURL: https://your-zabbix-server/zabbix/"\r\n	params[\'X-S4-ExternalID\'] = \'ZabbixEventID: \' + params.Event_ID;\r\n	if (typeof params.Zabbix_URL === \'string\' && params.Zabbix_URL.indexOf(\'http\') == 0) {\r\n		// Make sure the URL ends with \'/\'\r\n		if (params.Zabbix_URL.charAt(params.Zabbix_URL.length - 1) != \'/\') {\r\n			params.Zabbix_URL = params.Zabbix_URL + \'/\';\r\n		}\r\n\r\n		params[\'X-S4-ExternalID\'] = params[\'X-S4-ExternalID\'] + \' ZabbixURL: \' +  params.Zabbix_URL;\r\n\r\n		// Add Link parameter\r\n		params[\'Link\'] = params.Zabbix_URL + "tr_events.php?triggerid="+params.Trigger_ID + "&eventid=" + params.Event_ID;\r\n	}\r\n\r\n	// Check if this is a new problem or a recovery\r\n	if (params.Trigger_Status == \'OK\') {\r\n		params[\'X-S4-Status\'] = \'resolved\';\r\n	}\r\n	else {\r\n		params[\'X-S4-Status\'] = \'new\';\r\n		params[\'X-S4-SourceSystem\'] = \'Zabbix\';\r\n	}\r\n\r\n    payload = JSON.stringify(params);\r\n    Zabbix.log(4, \'[ SIGNL4 Webhook ] Sending request: \' + payload);\r\n\r\n    request.addHeader(\'Content-Type: application/json\');\r\n    response = request.post(endpoint, \'payload=\' + payload);\r\n\r\n    Zabbix.log(4, \'[ SIGNL4 Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response\r\n    );\r\n\r\n    if (request.getStatus() !== 201) {\r\n        throw \'Request failed with status code \' + request.getStatus() +\r\n                \'. Check debug log for more information.\';\r\n    }\r\n\r\n    return \'OK\';\r\n}\r\ncatch (error) {\r\n    Zabbix.log(4, \'[ SIGNL4 Webhook ] ERROR: \' + error);\r\n\r\n    throw \'Sending failed: \' + error;\r\n}','30s','0','0','','','SIGNL4 is a mobile alert notification app for powerful alerting, alert management and mobile assignment of work items. It offers alerting via app push, SMS and voice calls including escalations, tracking, and duty scheduling.\r\n\r\nGet the app at https://www.signl4.com.\r\n\r\nFind out more including an integration video here: https://www.signl4.com/blog/portfolio_item/zabbix-mobile-alert-notification-duty-schedule-escalation/','0'),
('94','4','Slack','','','','','','','','25','0','0','0','0','1','1','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nvar serviceLogName = \'Slack Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	Slack = CWebhook;\r\n\r\nSlack.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({\r\n		alert_subject: { type: \'string\' },\r\n		alert_message: { type: \'string\' },\r\n		bot_token: { type: \'string\' },\r\n		zabbix_url: { type: \'string\', url: true },\r\n		channel: { type: \'string\', macro: \'ALERT.SENDTO\' },\r\n		slack_mode: { type: \'string\', array: [\'alarm\', \'event\'], }\r\n	}, this.params);\r\n\r\n	if (this.params.event_source === \'0\') {\r\n		CParamValidator.validate({\r\n			event_id: { type: \'integer\' },\r\n			trigger_id: { type: \'integer\' }\r\n		}, this.params);\r\n	}\r\n\r\n	if (CParamValidator.inArray(this.params.event_source, [\'0\', \'3\', \'4\'])) {\r\n		CParamValidator.validate({\r\n			event_tags: { type: \'array\', macro: \'EVENT.TAGSJSON\', tags: true, default: {} }\r\n		}, this.params);\r\n	}\r\n\r\n	if (this.params.event_value != \'0\' && CParamValidator.isDefined(this.params.event_tags[\'__channel_id_\' + this.params.channel])) {\r\n		this.params.event_update_status = \'1\';\r\n	}\r\n\r\n	this.severity_colors = [\r\n		\'#97AAB3\',\r\n		\'#7499FF\',\r\n		\'#FFC859\',\r\n		\'#FFA059\',\r\n		\'#E97659\',\r\n		\'#E45959\'\r\n	];\r\n\r\n	this.resolve_color = \'#009900\';\r\n	this.slack_endpoint = \'https://slack.com/api/\';\r\n\r\n	this.problem_url = CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id);\r\n\r\n	this.data = {\r\n		channel: this.params.channel,\r\n		attachments: [\r\n			{\r\n				fallback: this.params.alert_subject,\r\n				title: this.params.alert_subject,\r\n				color: this.severity_colors[this.params.event_nseverity],\r\n				title_link: this.problem_url,\r\n				text: this.params.alert_message,\r\n				actions: [\r\n					{\r\n						type: \'button\',\r\n						text: \'Open in Zabbix\',\r\n						url: this.problem_url\r\n					}\r\n				]\r\n			}\r\n		]\r\n	};\r\n\r\n	this.reply = {\r\n		channel: this.params.channel,\r\n		thread_ts: \'\',\r\n		blocks: [\r\n			{\r\n				type: \'context\',\r\n				elements: [\r\n					{\r\n						type: \'plain_text\',\r\n						text: \'Event update message\'\r\n					}\r\n				]\r\n			},\r\n			{\r\n				type: \'rich_text\',\r\n				elements: [\r\n					{\r\n						type: \'rich_text_section\',\r\n						elements: [\r\n							{\r\n								type: \'text\',\r\n								text: \'\',\r\n								style: {\r\n									italic: true\r\n								}\r\n							}\r\n						]\r\n					}\r\n				]\r\n			}\r\n		]\r\n	};\r\n};\r\n\r\nSlack.prototype.sendRequest = function (route, data, tags) {\r\n	this.request.clearHeader();\r\n	this.request.addHeaders({\r\n		\'Content-Type\': \'application/json; charset=utf-8;\',\r\n		\'Authorization\': \'Bearer \' + this.params.bot_token\r\n	});\r\n\r\n	var response = this.request.jsonRequest(\'POST\', this.slack_endpoint + route, data);\r\n\r\n	if (this.request.getStatus() !== 200 || !CParamValidator.isType(response.ok, \'boolean\') || response.ok !== true) {\r\n		Logger.log(Logger.INFO, \'HTTP code: \' + this.request.getStatus());\r\n		if (CParamValidator.isType(response.error, \'string\')) {\r\n			throw \'Endpoint response:\' + response.error;\r\n		}\r\n		else {\r\n			throw \'Unknown error. Check debug log for more information.\';\r\n		}\r\n	}\r\n\r\n	if (tags) {\r\n		return {\r\n			tags: {\r\n				[\'__message_ts_\' + this.params.channel]: response.ts,\r\n				[\'__channel_id_\' + this.params.channel]: response.channel,\r\n				[\'__message_link_\' + this.params.channel]: this.getPermalink(response.channel, response.ts),\r\n			}\r\n		};\r\n\r\n	}\r\n	else {\r\n		return { tags: {} };\r\n	}\r\n};\r\n\r\nSlack.prototype.getPermalink = function (channel, message_ts) {\r\n	var response = this.request.jsonRequest(\'GET\', this.slack_endpoint + \'chat.getPermalink\' + \'?channel=\' + channel + \'&message_ts=\' + message_ts);\r\n\r\n	if (this.request.getStatus() !== 200 || !CParamValidator.isType(response.ok, \'boolean\') || response.ok !== true) {\r\n		Logger.log(Logger.INFO, \'HTTP code: \' + this.request.getStatus());\r\n		if (CParamValidator.isType(response.error, \'string\')) {\r\n			throw \'Endpoint response:\' + response.error;\r\n		}\r\n		else {\r\n			throw \'Unknown error. Check debug log for more information.\';\r\n		}\r\n	}\r\n\r\n	if (!CParamValidator.isDefined(response.permalink)) {\r\n		throw \'Permalink is missed from the JSON response\';\r\n	}\r\n\r\n	return response.permalink;\r\n};\r\n\r\nSlack.prototype.onProblem = function (properties) {\r\n	Logger.log(Logger.INFO, \'Source: \' + properties.source + \'; Event: \' + properties.event);\r\n\r\n	if (this.params.slack_mode === "alarm") {\r\n		return this.sendRequest(\'chat.postMessage\', this.data, true);\r\n	} else {\r\n		return this.sendRequest(\'chat.postMessage\', this.data, false);\r\n	}\r\n};\r\n\r\nSlack.prototype.onUpdate = function (properties) {\r\n	Logger.log(Logger.INFO, \'Source: \' + properties.source + \'; Event: \' + properties.event);\r\n\r\n	if (this.params.slack_mode === "alarm") {\r\n		this.data.channel = this.params.event_tags[\'__channel_id_\' + this.params.channel];\r\n		this.data.ts = this.params.event_tags[\'__message_ts_\' + this.params.channel];\r\n\r\n		if (CParamValidator.isMacroSet(this.params.event_update_message, \'EVENT.UPDATE.MESSAGE\') && !CParamValidator.isEmpty(this.params.event_update_message)) {\r\n			this.reply.thread_ts = this.data.ts;\r\n			this.reply.blocks[1].elements[0].elements[0].text = this.params.event_update_message;\r\n			this.sendRequest(\'chat.postMessage\', this.reply, false);\r\n		}\r\n\r\n		if (/\\backnowledged/.test(this.params.event_update_action)) {\r\n			this.sendRequest(\'reactions.add\', { channel: this.data.channel, timestamp: this.data.ts, name: \'white_check_mark\' }, false);\r\n		}\r\n\r\n		if (/\\bunacknowledged/.test(this.params.event_update_action)) {\r\n			this.sendRequest(\'reactions.remove\', { channel: this.data.channel, timestamp: this.data.ts, name: \'white_check_mark\' }, false);\r\n		}\r\n\r\n		if (/\\bclosed/.test(this.params.event_update_action)) {\r\n			return { tags: {} };\r\n		}\r\n		else {\r\n			return this.sendRequest(\'chat.update\', this.data, false);\r\n		}\r\n	} else {\r\n		return this.sendRequest(\'chat.postMessage\', this.data, false);\r\n	}\r\n};\r\n\r\nSlack.prototype.onResolve = function (properties) {\r\n	Logger.log(Logger.INFO, \'Source: \' + properties.source + \'; Event: \' + properties.event);\r\n	this.data.attachments[0].color = this.resolve_color;\r\n\r\n	if (this.params.slack_mode === "alarm") {\r\n		this.data.channel = this.params.event_tags[\'__channel_id_\' + this.params.channel];\r\n		this.data.ts = this.params.event_tags[\'__message_ts_\' + this.params.channel];\r\n\r\n		return this.sendRequest(\'chat.update\', this.data, false);\r\n	} else {\r\n		return this.sendRequest(\'chat.postMessage\', this.data, false);\r\n	}\r\n};\r\n\r\nSlack.prototype.onDiscovery = function (properties) {\r\n	return this.onProblem(properties);\r\n};\r\n\r\nSlack.prototype.onAutoreg = function (properties) {\r\n	return this.onProblem(properties);\r\n};\r\n\r\ntry {\r\n	var hook = new Slack(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'Notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','0','','','Preparing slack for a Zabbix media type:\r\n1. On the page Your Apps (https://api.slack.com/apps) press \'Create an App\', select \'From scratch\' and specify its name and workspace.\r\n2. In the \'Add features and functionality\' section, select \'Bots\' and press \'Review Scopes to Add\'.\r\n3. In the \'Scopes\' section, find \'Bot Token Scopes\', press \'Add an OAuth Scope\' and add \'chat:write\', \'im:write\', \'groups:write\' and \'reactions:write\' scopes.\r\n4. In the \'Settings\' section on the left side of the page press \'Install App\' and then \'Install to Workspace\'.\r\n5. Press \'Allow\' and copy \'Bot User OAuth Access Token\', which will be used to set up webhook.\r\n\r\nIn Zabbix:\r\n1. Set global macro {$ZABBIX.URL}\r\n2. Set user media for slack using channel name or member ID\r\n3. Set media param \'bot_token\' to the previously created token\r\n\r\nFor a detailed instructions please read full README file https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/slack/README.md','0'),
('95','4','SolarWinds Service Desk','','','','','','','','25','0','0','0','0','1','3','10s','1','var SolarWinds = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        SolarWinds.params = params;\r\n        SolarWinds.params.endpoint = \'https://api.samanage.com/\';\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        SolarWinds.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    addCustomFields: function (data, fields) {\r\n        if (typeof data.incident === \'object\' && typeof fields === \'object\' && Object.keys(fields).length) {\r\n            if (typeof fields.sw_fields === \'object\' && Object.keys(fields.sw_fields).length) {\r\n                Object.keys(fields.sw_fields)\r\n                    .forEach(function(field) {\r\n                        try {\r\n                            data.incident[field] = JSON.parse(fields.sw_fields[field]);\r\n                        }\r\n                        catch (error) {\r\n                            data.incident[field] = fields.sw_fields[field];\r\n                        }\r\n                    });\r\n            }\r\n\r\n            if (typeof fields.sw_customfields === \'object\' && Object.keys(fields.sw_customfields).length) {\r\n                data.incident.custom_fields_values = {custom_fields_value: []};\r\n                Object.keys(fields.sw_customfields)\r\n                    .forEach(function(field) {\r\n                        data.incident.custom_fields_values.custom_fields_value.push({\r\n                            name: field,\r\n                            value: fields.sw_customfields[field]\r\n                        });\r\n                    });\r\n            }\r\n        }\r\n\r\n        return data;\r\n    },\r\n\r\n    request: function (method, query, data) {\r\n        [\'token\'].forEach(function (field) {\r\n            if (typeof SolarWinds.params !== \'object\' || typeof SolarWinds.params[field] === \'undefined\'\r\n                || SolarWinds.params[field] === \'\' ) {\r\n                throw \'Required SolarWinds param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = SolarWinds.params.endpoint + query,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'X-Samanage-Authorization: Bearer \' + SolarWinds.params.token);\r\n        request.addHeader(\'Accept: application/vnd.samanage.v2.1+json\');\r\n\r\n        if (typeof SolarWinds.HTTPProxy !== \'undefined\' && SolarWinds.HTTPProxy !== \'\') {\r\n            request.setProxy(SolarWinds.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ SolarWinds SD Webhook ] Sending request: \' + url + ((typeof data === \'string\')\r\n            ? (\'\\n\' + data)\r\n            : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ SolarWinds SD Webhook ] Received response with status code \' + request.getStatus() +\r\n            \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ SolarWinds SD Webhook ] Failed to parse response received from SolarWinds\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null && typeof response.error !== \'undefined\'\r\n                && Object.keys(response.error).length > 0) {\r\n                message += \': \' + JSON.stringify(response.error);\r\n            }\r\n            else if (response !== null && typeof response === \'object\'\r\n                && Object.keys(response).length > 0) {\r\n                Object.keys(response)\r\n                    .forEach(function(field) {\r\n                        message += \'\\n\' + field + \': \' + response[field][0];\r\n                    });\r\n            }\r\n\r\n            throw message + \' Check debug log for more information.\';\r\n        }\r\n\r\n        return {\r\n            status: request.getStatus(),\r\n            response: response\r\n        };\r\n    },\r\n\r\n    createIncident: function(name, description, fields) {\r\n        var data = {\r\n            incident: {\r\n                name: name,\r\n                description: description,\r\n                priority: SolarWinds.params.priority\r\n            }\r\n        };\r\n\r\n        var result = SolarWinds.request(\'post\', \'incidents.json\', SolarWinds.addCustomFields(data, fields));\r\n\r\n        if (typeof result.response !== \'object\' || typeof result.response.id === \'undefined\') {\r\n            throw \'Cannot create SolarWinds incident. Check debug log for more information.\';\r\n        }\r\n\r\n        return result.response.id;\r\n    },\r\n\r\n    updateIncident: function(name, fields, message) {\r\n        var data = {\r\n            incident: {\r\n                name: name,\r\n                priority: SolarWinds.params.priority\r\n            }\r\n        };\r\n\r\n        SolarWinds.request(\r\n            \'put\',\r\n            \'incidents/\' + SolarWinds.params.incident_id + \'.json\',\r\n            SolarWinds.addCustomFields(data, fields));\r\n\r\n        SolarWinds.commenIncident(message);\r\n    },\r\n\r\n    commenIncident: function(message) {\r\n        var data = {\r\n            comment: {\r\n                body: message\r\n            }\r\n        };\r\n\r\n        SolarWinds.request(\'post\', \'incidents/\' + SolarWinds.params.incident_id + \'/comments.json\', data);\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        fields = {},\r\n        samanage = {},\r\n        result = {tags: {}},\r\n        required_params = [\'alert_subject\', \'event_recovery_value\', \'event_source\', \'event_value\', \'priority_default\'],\r\n        severities = [\r\n            {name: \'not_classified\'},\r\n            {name: \'information\'},\r\n            {name: \'warning\'},\r\n            {name: \'average\'},\r\n            {name: \'high\'},\r\n            {name: \'disaster\'},\r\n            {name: \'resolved\'},\r\n            {name: \'default\'}\r\n        ];\r\n\r\n    fields.sw_fields = {};\r\n    fields.sw_customfields = {};\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'samanage_\')) {\r\n                samanage[key.substring(9)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'sw_field_\')) {\r\n                fields.sw_fields[key.substring(9)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'sw_customfield_\')) {\r\n                fields.sw_customfields[key.substring(15)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key] === \'\') {\r\n                throw \'Parameter "\' + key + \'" can\\\'t be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_recovery_value === \'0\') {\r\n        throw \'Recovery operations are supported only for trigger-based actions.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    samanage.priority = params[\'priority_\' + severities[params.event_nseverity].name] || params.priority_default;\r\n\r\n    SolarWinds.setParams(samanage);\r\n    SolarWinds.setProxy(params.HTTPProxy);\r\n\r\n    // Create incident for non trigger-based events.\r\n    if (params.event_source !== \'0\' && params.event_recovery_value !== \'0\') {\r\n        SolarWinds.createIncident(params.alert_subject, params.alert_message);\r\n    }\r\n    // Create incident for trigger-based events.\r\n    else if (params.event_value === \'1\' && params.event_update_status === \'0\'\r\n            && (samanage.incident_id === \'{EVENT.TAGS.__zbx_solarwinds_inc_id}\' || samanage.incident_id === \'*UNKNOWN*\')) {\r\n        var key = SolarWinds.createIncident(params.alert_subject, params.alert_message, fields);\r\n\r\n\r\n        result.tags.__zbx_solarwinds_inc_id = key;\r\n        result.tags.__zbx_solarwinds_inc_link = params.samanage_url +\r\n            (params.samanage_url.endsWith(\'/\') ? \'\' : \'/\') + \'incidents/\' + key;\r\n    }\r\n    // Update created incident for trigger-based event.\r\n    else {\r\n        if (samanage.incident_id === \'{EVENT.TAGS.__zbx_solarwinds_inc_id}\' || samanage.incident_id === \'\' || samanage.incident_id === \'*UNKNOWN*\') {\r\n            throw \'Incorrect incident key given: \' + samanage.incident_id;\r\n        }\r\n        if (!params.alert_message) {\r\n            throw \'Parameter "alert_message" can\\\'t be empty.\';\r\n        }\r\n        SolarWinds.updateIncident(params.alert_subject, fields, params.alert_message);\r\n    }\r\n\r\n    if (params.event_source === \'0\') {\r\n        return JSON.stringify(result);\r\n    }\r\n    else {\r\n        return \'OK\';\r\n    }\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ SolarWinds SD Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_solarwinds_inc_link}','SolarWinds incident ID: {EVENT.TAGS.__zbx_solarwinds_inc_id}','','0'),
('96','4','SysAid','','','','','','','','25','0','0','0','0','1','3','10s','1','var SysAid = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        var required = [\'url\', \'auth_user\', \'auth_password\', \'category_level_1\', \'category_level_2\',\r\n            \'category_level_3\', \'incident_id\', \'template_id\', \'urgency_id\', \'incident_state\',\r\n            \'default_priority_id\'\r\n        ];\r\n\r\n        required.forEach(function (field) {\r\n            if (typeof params !== \'object\' || typeof params[field] === \'undefined\' || params[field] === \'\') {\r\n                throw \'Required param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        SysAid.params = params;\r\n        if (typeof SysAid.params.url === \'string\' && !SysAid.params.url.endsWith(\'/\')) {\r\n            SysAid.params.url += \'/\';\r\n        }\r\n    },\r\n\r\n    login: function () {\r\n        var result = SysAid.request(\'post\', \'api/v1/login\', {\r\n            user_name: SysAid.params.auth_user,\r\n            password: SysAid.params.auth_password\r\n        });\r\n\r\n        return result.response.user.id;\r\n    },\r\n\r\n    request: function (method, query, data) {\r\n        var response,\r\n            request = SysAid.req || (SysAid.req = new HttpRequest()),\r\n            url = SysAid.params.url + query;\r\n\r\n        if (typeof SysAid.HTTPProxy !== \'undefined\' && SysAid.HTTPProxy.trim() !== \'\') {\r\n            request.setProxy(SysAid.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ SysAid Webhook ] Sending request: \' +\r\n            url + ((typeof data === \'string\') ? (\' \' + data) : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ SysAid Webhook ] Received response with status code \' + request.getStatus() + \': \' + response);\r\n\r\n        if (request.getStatus() !== 200) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            message += \': \' + response;\r\n            throw message + \' Check debug log for more information.\';\r\n        }\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ SysAid Webhook ] Failed to parse response received from SysAid\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (response === null || (typeof response.Error !== \'undefined\' && Object.keys(response.Error).length > 0)) {\r\n            throw \'Request failed: \' + JSON.stringify(response.Error);\r\n        }\r\n\r\n        return {\r\n            status: request.getStatus(),\r\n            response: response\r\n        };\r\n    },\r\n\r\n    createIncident: function(subject, message, priority) {\r\n        var result = SysAid.request(\'post\', \'api/v1/sr/?template=\' + encodeURIComponent(SysAid.params.template_id), {\r\n            info: [\r\n                {\r\n                    key: \'problem_type\',\r\n                    value: [\r\n                        SysAid.params.category_level_1,\r\n                        SysAid.params.category_level_2,\r\n                        SysAid.params.category_level_3\r\n                    ].join(\'_\')\r\n                },\r\n                {\r\n                    key: \'title\',\r\n                    value: subject\r\n                },\r\n                {\r\n                    key: \'description\',\r\n                    value: message\r\n                },\r\n                {\r\n                    key: \'status\',\r\n                    value: \'1\'\r\n                },\r\n                {\r\n                    key: \'urgency\',\r\n                    value: SysAid.params.urgency_id\r\n                },\r\n                {\r\n                    key: \'priority\',\r\n                    value: priority || SysAid.params.default_priority_id,\r\n                }\r\n            ]\r\n        });\r\n\r\n        if (result.response.id === \'undefined\') {\r\n            throw \'Cannot create SysAid incident. Check debug log for more information.\';\r\n        }\r\n\r\n        return result.response.id;\r\n    },\r\n\r\n    updateTicket: function(note) {\r\n        var date = new Date().getTime();\r\n\r\n        SysAid.request(\'put\', \'api/v1/sr/\' + encodeURIComponent(SysAid.params.incident_id), {\r\n            id: SysAid.params.incident_id,\r\n            info: [\r\n                {\r\n                    key: \'update_time\',\r\n                    value: date\r\n                },\r\n                {\r\n                    key: \'notes\',\r\n                    value: [\r\n                        {\r\n                            userName: \'Zabbix\',\r\n                            createDate: date,\r\n                            text: note\r\n                        }\r\n                    ]\r\n                }\r\n            ]\r\n        });\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        params_sysaid = {},\r\n        params_update = {},\r\n        result = {tags: {}},\r\n        required_params = [\'alert_subject\', \'event_source\', \'event_value\',  \'event_update_status\'],\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'resolved\', color: \'#009900\'},\r\n            {name: null, color: \'#000000\'}\r\n        ],\r\n        priority;\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'sysaid_\')) {\r\n                params_sysaid[key.substring(7)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'event_update_\')) {\r\n                params_update[key.substring(13)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key].trim() === \'\') {\r\n                throw \'Parameter "\' + key + \'" cannot be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_source === \'0\' && params.event_update_status !== \'0\' && params.event_update_status !== \'1\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_value === \'0\') {\r\n        throw \'Recovery operations are supported only for trigger-based actions.\';\r\n    }\r\n\r\n    if (params.event_source === \'0\' && ((params.event_value === \'1\' && params.event_update_status === \'1\')\r\n            || (params.event_value === \'0\' && (params.event_update_status === \'0\' || params.event_update_status === \'1\')))\r\n            && (isNaN(parseInt(params.sysaid_incident_id)) || parseInt(params.sysaid_incident_id) < 1 )) {\r\n        throw \'Incorrect "sysaid_incident_id" parameter given: \' + params.sysaid_incident_id + \'\\nMust be positive integer.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    priority = params[\'severity_\' + severities[params.event_nseverity].name];\r\n    priority = priority && priority.trim() || severities[7].name;\r\n\r\n    SysAid.setParams(params_sysaid);\r\n    SysAid.HTTPProxy = params.HTTPProxy;\r\n    SysAid.login();\r\n\r\n    if (params.event_source !== \'0\' && params.event_value !== \'0\') {\r\n        // Create ticket for non trigger-based events.\r\n        SysAid.createIncident(params.alert_subject, params.alert_message, priority);\r\n    }\r\n    else if (params.event_value === \'1\' && params_update.status === \'0\') {\r\n        // Create ticket for trigger-based events.\r\n        var incident_id = SysAid.createIncident(params.alert_subject, params.alert_subject + \'\\n\' + params.alert_message +\r\n                \'\\n\' + params.zabbix_url + (params.zabbix_url.endsWith(\'/\') ? \'\' : \'/\') + \'tr_events.php?triggerid=\' +\r\n                params.trigger_id + \'&eventid=\' + params.event_id + \'\\n\', priority\r\n        );\r\n\r\n        result.tags.__zbx_sysaid_incident_id = incident_id;\r\n        result.tags.__zbx_sysaid_incidentlink = params.sysaid_url +\r\n            (params.sysaid_url.endsWith(\'/\') ? \'\' : \'/\') + \'SREdit.jsp?id=\' + incident_id + \'&fromId=IncidentsList\';\r\n    }\r\n    else {\r\n        // Update created ticket for trigger-based event.\r\n        SysAid.updateTicket(params.alert_subject + \'\\n\' + params.alert_message);\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ SysAid Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_sysaid_incidentlink}','SysAid: incident #{EVENT.TAGS.__zbx_sysaid_incident_id}','','0'),
('97','4','Telegram','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nvar serviceLogName = \'Telegram Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	Telegram = CWebhook;\r\n\r\nfunction escapeMarkup(str, mode) {\r\n	switch (mode) {\r\n		case \'markdown\':\r\n			return str.replace(/([_*\\[`])/g, \'\\\\$&\');\r\n		case \'markdownv2\':\r\n			return str.replace(/([_*\\[\\]()~`>#+\\-=|{}.!])/g, \'\\\\$&\');\r\n		case \'html\':\r\n			return str.replace(/<(\\s|[^a-z\\/])/g, \'&lt;$1\');\r\n		default:\r\n			return str;\r\n	}\r\n}\r\n\r\nTelegram.prototype.getMessageID = function (chat_id, message_thread_id) {\r\n	const tag_key = \'__telegram_msg_id_\' + chat_id + (message_thread_id ? \'_\' + message_thread_id : \'\');\r\n	if (CParamValidator.isDefined(this.params.event_tags[tag_key])) {\r\n		return this.params.event_tags[tag_key];\r\n	}\r\n	return null;\r\n}\r\n\r\nTelegram.prototype.onCheckParams = function () {\r\n	CParamValidator.validate(\r\n		{\r\n			api_token: {type: \'string\'},\r\n			api_chat_id: {type: \'string\'},\r\n			alert_message: {type: \'string\'}\r\n		},\r\n		this.params\r\n	);\r\n\r\n	if (CParamValidator.inArray(this.params.event_source, [\'0\', \'3\', \'4\'])) {\r\n		CParamValidator.validate({\r\n			event_tags: {type: \'array\', macro: \'EVENT.TAGSJSON\', tags: true, default: {}}\r\n		}, this.params);\r\n	}\r\n\r\n	this.params.url = \'https://api.telegram.org/bot\';\r\n	this.data = {\r\n		disable_web_page_preview: true,\r\n		disable_notification: false\r\n	};\r\n	const match = this.params.api_chat_id.match(/^(-?\\d+|@[a-zA-Z0-9_]+)(?::(\\d+))?$/);\r\n	if (!match) {\r\n		throw \'Invalid format for api_chat_id: "\' + this.params.api_chat_id + \'". Must be a numeric group ID or @GroupName, optionally followed by :message_thread_id.\';\r\n	}\r\n	this.data[\'chat_id\'] = match[1];\r\n	if (CParamValidator.isDefined(match[2])) {\r\n		this.data[\'message_thread_id\'] = match[2];\r\n	}\r\n	this.data[\'text\'] = ((this.params.alert_subject !== \'\') ? this.params.alert_subject + \'\\n\' : \'\') + this.params.alert_message;\r\n	if ([\'markdown\', \'html\', \'markdownv2\'].indexOf(this.params.api_parse_mode.toLowerCase()) !== -1) {\r\n		this.data[\'parse_mode\'] = this.params.api_parse_mode.toLowerCase();\r\n		this.data[\'text\'] = escapeMarkup(this.data[\'text\'], this.data[\'parse_mode\']);\r\n	}\r\n	const reply_to_message_id = this.getMessageID(this.data[\'chat_id\'], this.data[\'message_thread_id\']);\r\n	if (reply_to_message_id !== null) {\r\n		this.data[\'reply_to_message_id\'] = reply_to_message_id;\r\n	}\r\n	this.result = {tags: {}};\r\n};\r\n\r\nTelegram.prototype.onEvent = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n	Logger.log(Logger.INFO, \'URL: \' + this.params.url.replace(this.params.api_token, \'<TOKEN>\'));\r\n	var response = this.request.jsonRequest(\'POST\', this.params.url + this.params.api_token + \'/sendMessage\', this.data);\r\n\r\n	if (this.request.getStatus() !== 200 || !CParamValidator.isType(response.ok, \'boolean\') || response.ok !== true) {\r\n		Logger.log(Logger.INFO, \'HTTP code: \' + this.request.getStatus());\r\n		if (CParamValidator.isType(response.description, \'string\')) {\r\n			throw response.description;\r\n		}\r\n		else {\r\n			throw \'Unknown error. Check debug log for more information.\';\r\n		}\r\n	}\r\n\r\n	if (CParamValidator.isDefined(response.result.message_id) && this.getMessageID(this.data[\'chat_id\'], this.data[\'message_thread_id\']) === null) {\r\n		this.result.tags[\'__telegram_msg_id_\' + this.data[\'chat_id\'] + (this.data[\'message_thread_id\'] ? \'_\' + this.data[\'message_thread_id\'] : \'\')] = response.result.message_id;\r\n	}\r\n\r\n	return this.result;\r\n};\r\n\r\ntry {\r\n	var hook = new Telegram(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','0','','','This media type integrates your Zabbix installation with Telegram using the Zabbix webhook feature.\r\n\r\nTelegram configuration:\r\n\r\n1. Register a new Telegram bot: send "/newbot" to "@BotFather" and follow the instructions. The token provided by "@BotFather" in the final step will be needed for configuring the Zabbix webhook.\r\n\r\n2. Set up personal or group notifications:\r\n\r\n2.1 Personal notifications:\r\n\r\n2.1.1 Retrieve the chat ID of the user the bot should send messages to. The user should send "/getid" to "@myidbot" in the Telegram messenger.\r\n\r\n2.1.2 The user should also send "/start" to the bot created in step 1. If you skip this step, the Telegram bot won\'t be able to send messages to the user (bots cannot initiate conversations with users).\r\n\r\n2.2 Group notifications:\r\n\r\n2.2.1 Retrieve the group ID of the group that the bot should send messages to. Add "@myidbot" and the bot created in step 1 to your group.\r\n\r\n2.2.2 In the group chat, send: "/getgroupid@myidbot".\r\n\r\n2.2.3 If the bot is added to a supergroup and you want the bot to send messages to a specific topic instead of the default "General" channel, right-click any message in that topic and click "Copy Message Link". The copied link will have the following format: "https://t.me/c/<short_group_id>/<topic_id>/<message_id>", for example: "https://t.me/c/1234567890/2/1". In this example, the topic ID is "2".\r\n\r\nNote:\r\n- The group ID is a negative number, for example: "-1234567890".\r\n- The supergroup ID is a negative number prefixed with "-100", for example: "-1001234567890"\r\n- The public group or supergroup ID can also be specified in media type properties as a name prefixed by "@", for example: "@MyGroupName".\r\n\r\n3. Depending on where you want to send notifications, copy and save the bot token, personal chat ID or group ID, and topic ID (if you want to send messages to a specific supergroup topic), as you will need these later to set up the media type in Zabbix.\r\n\r\nZabbix configuration:\r\n\r\n1. Set the following webhook parameters:\r\n- "api_parse_mode" - the formatting mode applied for messages (possible values: "markdown", "html", "markdownv2")\r\n- "api_token" - the token of the bot used to send messages\r\n\r\nLearn more about message formatting options in Telegram Bot API documentation:\r\n- Markdown: https://core.telegram.org/bots/api#markdown-style\r\n- HTML: https://core.telegram.org/bots/api#html-style\r\n- MarkdownV2: https://core.telegram.org/bots/api#markdownv2-style\r\n\r\nNote: Your Telegram-related actions should be separated from other notification types (e.g., SMS); otherwise, if you use Markdown or HTML in the alert subject or body, you may receive plain-text alerts with raw tags.\r\n\r\n2. Click the "Enabled" checkbox to enable the media type and click the "Update" button to save the webhook settings.\r\n\r\n3. Create a Zabbix user and add media:\r\n- To create a new user, go to the "Users" → "Users" section, click the "Create user" button in the top right corner. In the "User" tab, fill in all required fields (marked with red asterisks).\r\n- Make sure this user has access to all hosts for which you would like problem notifications to be sent to Telegram.\r\n- In the "Media" tab, click "Add" and select the type "Telegram" from the drop-down list.\r\n- In the "Send to" field, specify the Telegram user chat ID or group ID that you retrieved during Telegram setup. To send notifications to a specific topic within a supergroup, specify the topic ID after the semicolon delimiter in the format "<group_id>:<topic_id>", for example: "-1001234567890:2", "@MyGroupName:2".\r\n\r\n4. Done! You can now start using this media type in actions and create tickets.\r\n\r\nYou can find the latest version of this media and additional information in the official Zabbix repository:\r\nhttps://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/telegram','0'),
('98','4','TOPdesk','','','','','','','','25','0','0','0','0','1','3','10s','1','var Media = {\r\n    params: {},\r\n    name: \'\',\r\n    labels: [],\r\n    HTTPProxy: \'\',\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        Media.params = params;\r\n        Media.params.api += Media.params.api.endsWith(\'/\') ? \'\' : \'/\';\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        if (typeof HTTPProxy !== \'undefined\' && HTTPProxy.trim() !== \'\') {\r\n            Media.HTTPProxy = HTTPProxy;\r\n        }\r\n    },\r\n\r\n    request: function (method, query, data) {\r\n        [\'api\', \'token\'].forEach(function (field) {\r\n            if (typeof Media.params !== \'object\' || typeof Media.params[field] === \'undefined\'\r\n                    || Media.params[field] === \'\') {\r\n                throw \'Required \' + Media.name + \' param is not set: "\' + field + \'".\';\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = Media.params.api + query,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'Accept: application/json\');\r\n        request.addHeader(\'Authorization: \' + Media.params.token);\r\n        request.setProxy(Media.HTTPProxy);\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Sending request: \' +\r\n            url + ((typeof data === \'string\') ? (\'\\n\' + data) : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Failed to parse response.\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null) {\r\n                if (typeof response.errors === \'object\' && Object.keys(response.errors).length > 0) {\r\n                    message += \': \' + JSON.stringify(response.errors);\r\n                }\r\n                else if (typeof response.errorMessages === \'object\' && Object.keys(response.errorMessages).length > 0) {\r\n                    message += \': \' + JSON.stringify(response.errorMessages);\r\n                }\r\n                else if (typeof response.message === \'string\') {\r\n                    message += \': \' + response.message;\r\n                }\r\n            }\r\n\r\n            throw message + \' Check debug log for more information.\';\r\n        }\r\n\r\n        return {\r\n            status: request.getStatus(),\r\n            response: response\r\n        };\r\n    }\r\n};\r\n\r\ntry {\r\n    var result = {tags: {}},\r\n        params = JSON.parse(value),\r\n        media = {},\r\n        fields = {},\r\n        resp = {},\r\n        required_params = [\r\n            \'alert_subject\',\r\n            \'alert_message\',\r\n            \'event_id\',\r\n            \'event_source\',\r\n            \'event_value\',\r\n            \'event_update_status\',\r\n            \'topdesk_api\',\r\n            \'topdesk_user\',\r\n            \'topdesk_password\'\r\n        ],\r\n        severities = [\r\n            \'not_classified\',\r\n            \'information\',\r\n            \'warning\',\r\n            \'average\',\r\n            \'high\',\r\n            \'disaster\',\r\n            \'resolved\',\r\n            \'default\'\r\n        ],\r\n        priority;\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (required_params.indexOf(key) !== -1 && params[key].trim() === \'\') {\r\n                throw \'Parameter "\' + key + \'" cannot be empty.\';\r\n            }\r\n            if (key.startsWith(\'topdesk_\')) {\r\n                media[key.substring(8)] = params[key];\r\n            }\r\n        });\r\n\r\n    // Possible values of event_source:\r\n    // 0 - Trigger, 1 - Discovery, 2 - Autoregistration, 3 - Internal.\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: "\' + params.event_source + \'".\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check event_value for trigger-based and internal events.\r\n    // Possible values: 1 for problem, 0 for recovering\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check event_update_status only for trigger-based events.\r\n    // Possible values: 0 - Webhook was called because of problem/recovery event, 1 - Update operation.\r\n    if (params.event_source === \'0\' && params.event_update_status !== \'0\' && params.event_update_status !== \'1\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check event_id for a numeric value.\r\n    if (isNaN(parseInt(params.event_id)) || params.event_id < 1) {\r\n        throw \'Incorrect "event_id" parameter given: \' + params.event_id + \'\\nMust be a positive number.\';\r\n    }\r\n\r\n    if ((params.event_source === \'1\' || params.event_source === \'2\')  && params.event_value === \'0\') {\r\n        throw \'Recovery operations are supported only for Trigger and Internal actions.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    priority = params[\'severity_\' + severities[params.event_nseverity]];\r\n    params.zbxurl = params.zbxurl + (params.zbxurl.endsWith(\'/\') ? \'\' : \'/\');\r\n\r\n    Media.name = \'TOPdesk\';\r\n    Media.setParams(media);\r\n    Media.params.token = \'Basic \' + btoa(Media.params.user + \':\' + Media.params.password);\r\n    Media.setProxy(params.HTTPProxy);\r\n\r\n    // Create an issue.\r\n    // Numeric value of the event that triggered an action (1 for problem, 0 for recovering).\r\n    // Numeric value of the problem update status. Possible values:\r\n    // 0 - Webhook was called because of problem/recovery event, 1 - Update operation.\r\n    if ((params.event_source == 0 && params.event_value == 1 && params.event_update_status == 0)\r\n            || (params.event_source == 3 && params.event_value == 1)\r\n            || params.event_source == 1 || params.event_source == 2) {\r\n        Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Request of the ticket creating.\');\r\n        fields.caller = {dynamicName: \'Zabbix\'};\r\n        fields.briefDescription = params.alert_subject;\r\n        fields.request = params.alert_message.replace(/\\n/g, \'<br>\');\r\n        fields.priority = {name: priority};\r\n        fields.processingStatus = {name: Media.params.status};\r\n        fields.externalNumber = params.event_id;\r\n        fields.request += \'<br>\' + params.zbxurl;\r\n\r\n        if (params.event_source === \'0\') {\r\n            fields.request += \'tr_events.php?triggerid=\' + params.trigger_id + \'&eventid=\' + params.event_id;\r\n        }\r\n\r\n        resp = Media.request(\'post\', \'tas/api/incidents\', fields);\r\n        if (typeof resp.response !== \'object\' || typeof resp.response.id === \'undefined\') {\r\n            throw \'Cannot create \' + Media.name + \' issue. Check debug log for more information.\';\r\n        }\r\n\r\n        if (params.event_source == 0 && params.event_value == 1 && params.event_update_status == 0) {\r\n            result.tags.__zbx_tpd_issuekey = resp.response.number;\r\n            result.tags.__zbx_tpd_issuelink = Media.params.api +\r\n                \'tas/secure/incident?action=show&unid=\' + resp.response.id;\r\n        }\r\n    }\r\n    // Update a created issue.\r\n    else {\r\n        if (params.event_source == 3 && params.event_value == 0) {\r\n            throw \'Internal event recovery actions are not supported.\';\r\n        }\r\n\r\n        Zabbix.log(4, \'[ \' + Media.name + \' Webhook ] Request of the ticket updating.\');\r\n        fields.action = params.alert_message.replace(/\\n/g, \'<br>\');\r\n\r\n        resp = Media.request(\'put\', \'tas/api/incidents/number/\' + Media.params.issue_key, fields);\r\n        if (typeof resp.response !== \'object\' || typeof resp.response.id === \'undefined\'\r\n                || resp.response.number !== Media.params.issue_key) {\r\n            throw \'Cannot update \' + Media.name + \' issue. Check debug log for more information.\';\r\n        }\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ \' + Media.name + \' Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_tpd_issuelink}','TOPdesk: {EVENT.TAGS.__zbx_tpd_issuekey}','Please refer to https://developers.topdesk.com/documentation/index.html and https://www.zabbix.com/documentation/7.4/manual/config/notifications/media/webhook#example_scripts.\r\n  \r\nSet global macro {$ZABBIX.URL} with your Zabbix server URL.\r\nAdd a dedicated user with the media type "TOPdesk".\r\nChange the values of the variables topdesk_api (URL), topdesk_password, topdesk_user. The topdesk_status is the default status for creating a new TOPdesk ticket.','0'),
('99','4','VictorOps','','','','','','','','25','0','0','0','0','1','3','10s','1','var VictorOps = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        VictorOps.params = params;\r\n        if (VictorOps.params.endpoint) {\r\n            if (!VictorOps.params.endpoint.endsWith(\'/\')) {\r\n                VictorOps.params.endpoint += \'/\';\r\n            }\r\n\r\n            if (typeof VictorOps.params.routing_key !== \'undefined\'\r\n                    && VictorOps.params.routing_key !== \'{ALERT.SENDTO}\'\r\n                    && VictorOps.params.routing_key !== \'Default\') {\r\n                VictorOps.params.endpoint += VictorOps.params.routing_key;\r\n            }\r\n        }\r\n    },\r\n\r\n    setProxy: function (HTTPProxy) {\r\n        VictorOps.HTTPProxy = HTTPProxy;\r\n    },\r\n\r\n    addFields: function (fields) {\r\n        var data = {};\r\n\r\n        if (typeof fields === \'object\') {\r\n            Object.keys(fields)\r\n                .forEach(function(field) {\r\n                    if (fields[field] === \'\') {\r\n                        Zabbix.log(4, \'[ VictorOps Webhook ] Field "\' + field +\r\n                            \'" can\\\'t be empty. The field ignored.\');\r\n                    }\r\n                    else {\r\n                        try {\r\n                            var parts = field.split(\':\'),\r\n                                prefix = parts[0].split(\'_\');\r\n\r\n                            if (typeof prefix[1] === \'undefined\'\r\n                                    || (prefix[1] === \'p\' && params.event_value === \'1\'\r\n                                        && (params.event_update_status === \'0\'\r\n                                            || params.event_update_status === \'{EVENT.UPDATE.STATUS}\'))\r\n                                    || (prefix[1] === \'r\' && params.event_value === \'0\'\r\n                                        && (params.event_update_status === \'0\'\r\n                                            || params.event_update_status === \'{EVENT.UPDATE.STATUS}\'))\r\n                                    || (prefix[1] === \'u\' && params.event_update_status === \'1\')) {\r\n                                data[field.substring(field.indexOf(\':\') + 1)] = fields[field];\r\n                            }\r\n                        }\r\n                        catch (error) {\r\n                            Zabbix.log(4, \'[ VictorOps Webhook ] Can\\\'t parse field "\' + field +\r\n                                \'". The field ignored.\');\r\n                        }\r\n                    }\r\n                });\r\n        }\r\n\r\n        return data;\r\n    },\r\n\r\n    request: function (data) {\r\n        if (typeof VictorOps.params !== \'object\' || typeof VictorOps.params.endpoint === \'undefined\'\r\n                || VictorOps.params.endpoint === \'\' ) {\r\n            throw \'Required parameter is not set: "vops_endpoint".\';\r\n        }\r\n\r\n        var response,\r\n            url = VictorOps.params.endpoint,\r\n            request = new HttpRequest();\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n\r\n        if (typeof VictorOps.HTTPProxy !== \'undefined\' && VictorOps.HTTPProxy !== \'\') {\r\n            request.setProxy(VictorOps.HTTPProxy);\r\n        }\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[ VictorOps Webhook ] Sending request: \' + url +\r\n            ((typeof data === \'string\') ? (\'\\n\' + data) : \'\'));\r\n\r\n        response = request.post(url, data);\r\n\r\n        Zabbix.log(4, \'[ VictorOps Webhook ] Received response with status code \' +\r\n            request.getStatus() + \'\\n\' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[ VictorOps Webhook ] Failed to parse response received from VictorOps\');\r\n                response = null;\r\n            }\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null && typeof response.messages !== \'undefined\') {\r\n                message += \': \' + JSON.stringify(response.messages);\r\n            }\r\n\r\n            throw message + \'. Check debug log for more information.\';\r\n        }\r\n\r\n        return response;\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        fields = {},\r\n        vops = {},\r\n        required_params = [\'event_source\', \'event_value\', \'priority_update\'],\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'resolved\', color: \'#009900\'},\r\n            {name: \'default\', color: \'#000000\'}\r\n        ];\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'vops_\')) {\r\n                vops[key.substring(5)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'field\')) {\r\n                fields[key.substring(5)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key] === \'\') {\r\n                throw \'Parameter "\' + key + \'" can\\\'t be empty.\';\r\n            }\r\n        });\r\n\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n            && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    if (params.event_update_status !== \'0\' && params.event_update_status !== \'1\' && params.event_source === \'0\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    if (params.event_update_status === \'1\') {\r\n        fields[\':message_type\'] = params.priority_update;\r\n    }\r\n    else {\r\n        fields[\':message_type\'] = params[\'priority_\' + severities[params.event_nseverity].name]\r\n            || \'INFO\';\r\n    }\r\n\r\n    if (params.event_info && params.event_source === \'0\') {\r\n        fields[\':event_info\'] = params.event_info;\r\n    }\r\n\r\n    VictorOps.setParams(vops);\r\n    VictorOps.setProxy(params.HTTPProxy);\r\n    VictorOps.request(VictorOps.addFields(fields));\r\n\r\n    return \'OK\';\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[ VictorOps Webhook ] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','0','0','','','','0'),
('100','4','Zammad','','','','','','','','25','0','0','0','0','1','3','10s','1','const CLogger = function(serviceName) {\r\n	this.serviceName = serviceName;\r\n	this.INFO = 4\r\n	this.WARN = 3\r\n	this.ERROR = 2\r\n	this.log = function(level, msg) {\r\n		Zabbix.log(level, \'[\' + this.serviceName + \'] \' + msg);\r\n	}\r\n}\r\n\r\nconst CWebhook = function(value) {\r\n	try {\r\n		params = JSON.parse(value);\r\n\r\n		if ([\'0\', \'1\', \'2\', \'3\', \'4\'].indexOf(params.event_source) === -1) {\r\n			throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'.\\nMust be 0-4.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1 && [\'0\', \'1\'].indexOf(params.event_value) === -1) {\r\n			throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0 or 1.\';\r\n		}\r\n\r\n		if ([\'0\', \'3\', \'4\'].indexOf(params.event_source) !== -1) {\r\n			if (params.event_source === \'1\' && [\'0\', \'1\', \'2\', \'3\'].indexOf(params.event_value) === -1) {\r\n				throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'.\\nMust be 0-3.\';\r\n			}\r\n\r\n			if (params.event_source === \'0\' && [\'0\', \'1\'].indexOf(params.event_update_status) === -1) {\r\n				throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'.\\nMust be 0 or 1.\';\r\n			}\r\n\r\n			if (params.event_source === \'4\') {\r\n				if ([\'0\', \'1\', \'2\', \'3\', \'4\', \'5\'].indexOf(params.event_update_nseverity) !== -1 && params.event_update_nseverity != params.event_nseverity) {\r\n					params.event_nseverity = params.event_update_nseverity;\r\n					params.event_severity = params.event_update_severity;\r\n					params.event_update_status = \'1\';\r\n				}\r\n			}\r\n		}\r\n\r\n		this.runCallback = function(name, params) {\r\n			if (typeof this[name] === \'function\') {\r\n				return this[name].apply(this, [params]);\r\n			}\r\n		}\r\n\r\n		this.handleEvent = function(source, event) {\r\n			const alert = { source: source, event: event };\r\n			return [\r\n				this.runCallback(\'on\' + source + event, alert),\r\n				this.runCallback(\'on\' + event, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.handleEventless = function(source) {\r\n			const alert = { source: source, event: null };\r\n			return [\r\n				this.runCallback(\'on\' + source, alert),\r\n				this.runCallback(\'onEvent\', alert)\r\n			];\r\n		}\r\n\r\n		this.run = function() {\r\n			var results = [];\r\n			if (typeof this.httpProxy === \'string\' && this.httpProxy.trim() !== \'\') {\r\n				this.request.setProxy(this.httpProxy);\r\n			}\r\n			const types = { \'0\': \'Trigger\', \'1\': \'Discovery\', \'2\': \'Autoreg\', \'3\': \'Internal\', \'4\': \'Service\' };\r\n\r\n			if ([\'0\', \'3\', \'4\'].indexOf(this.params.event_source) !== -1) {\r\n				var event = (this.params.event_update_status === \'1\')\r\n					? \'Update\'\r\n					: ((this.params.event_value === \'1\') ? \'Problem\' : \'Resolve\');\r\n\r\n				results = this.handleEvent(types[this.params.event_source], event);\r\n			}\r\n			else if (typeof types[this.params.event_source] !== \'undefined\') {\r\n				results = this.handleEventless(types[this.params.event_source]);\r\n			}\r\n			else {\r\n				throw \'Unexpected "event_source": \' + this.params.event_source;\r\n			}\r\n\r\n			for (idx in results) {\r\n				if (typeof results[idx] !== \'undefined\') {\r\n					return JSON.stringify(results[idx]);\r\n				}\r\n			}\r\n		}\r\n		this.httpProxy = params.http_proxy;\r\n		this.params = params;\r\n		this.runCallback(\'onCheckParams\', {});\r\n	} catch (error) {\r\n		throw \'Webhook processing failed: \' + error;\r\n	}\r\n}\r\n\r\nconst CParamValidator = {\r\n\r\n	isType: function(value, type) {\r\n		if (type === \'array\') {\r\n			return Array.isArray(value);\r\n		}\r\n		if (type === \'integer\') {\r\n			return CParamValidator.isInteger(value);\r\n		}\r\n		if (type === \'float\') {\r\n			return CParamValidator.isFloat(value);\r\n		}\r\n\r\n		return (typeof value === type);\r\n	},\r\n\r\n	isInteger: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseInt(value));\r\n	},\r\n\r\n	isFloat: function(value) {\r\n		if (!CParamValidator.ifMatch(value, /^-?\\d+\\.\\d+$/)) {\r\n			return false;\r\n		}\r\n\r\n		return !isNaN(parseFloat(value));\r\n	},\r\n\r\n	isDefined: function(value) {\r\n		return !CParamValidator.isType(value, \'undefined\');\r\n	},\r\n\r\n	isEmpty: function(value) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be checked for emptiness.\';\r\n		}\r\n\r\n		return (value.trim() === \'\');\r\n	},\r\n\r\n	isMacroSet: function(value, macro) {\r\n		if (CParamValidator.isDefined(macro)) {\r\n			return !(CParamValidator.ifMatch(value, \'^\\{\' + macro + \'\\}$\'))\r\n		}\r\n\r\n		return !(CParamValidator.ifMatch(value, \'^\\{[$#]{0,1}[A-Z_\\.]+[\\:]{0,1}["]{0,1}.*["]{0,1}\\}$\') || value === \'*UNKNOWN*\')\r\n	},\r\n\r\n	withinRange: function(value, min, max) {\r\n		if (!CParamValidator.isType(value, \'number\')) {\r\n			throw \'Value "\' + value + \'" must be a number to be checked for range.\';\r\n		}\r\n		if (value < ((CParamValidator.isDefined(min)) ? min : value)\r\n			|| value > ((CParamValidator.isDefined(max)) ? max : value)) {\r\n			return false;\r\n		}\r\n\r\n		return true;\r\n	},\r\n\r\n	inArray: function(value, array) {\r\n		if (!CParamValidator.isType(array, \'array\')) {\r\n			throw \'The array must be an array to check the value for existing in it.\';\r\n		}\r\n\r\n		return (array.indexOf((typeof value === \'string\') ? value.toLowerCase() : value) !== -1);\r\n	},\r\n\r\n	ifMatch: function(value, regex) {\r\n		return (new RegExp(regex)).test(value);\r\n	},\r\n\r\n	match: function(value, regex) {\r\n		if (!CParamValidator.isType(value, \'string\')) {\r\n			throw \'Value "\' + value + \'" must be a string to be matched with the regular expression.\';\r\n		}\r\n\r\n		return value.match(new RegExp(regex));\r\n	},\r\n\r\n	checkURL: function(value) {\r\n		if (CParamValidator.isEmpty(value)) {\r\n			throw \'URL value "\' + value + \'" must be a non-empty string.\';\r\n		}\r\n		if (!CParamValidator.ifMatch(value, \'^(http|https):\\/\\/.+\')) {\r\n			throw \'URL value "\' + value + \'" must contain a schema.\';\r\n		}\r\n\r\n		return value.endsWith(\'/\') ? value.slice(0, -1) : value;\r\n	},\r\n\r\n	check: function(key, rule, params) {\r\n		if (!CParamValidator.isDefined(rule.type)) {\r\n			throw \'Mandatory attribute "type" has not been defined for parameter "\' + key + \'".\';\r\n		}\r\n		if (!CParamValidator.isDefined(params[key])) {\r\n			throw \'Checked parameter "\' + key + \'" was not found in the list of input parameters.\';\r\n		}\r\n		var value = params[key],\r\n			error_message = null;\r\n		switch (rule.type) {\r\n			case \'string\':\r\n				if (!CParamValidator.isType(value, \'string\')) {\r\n					throw \'Value "\' + key + \'" must be a string.\';\r\n				}\r\n				if (CParamValidator.isEmpty(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a non-empty string\';\r\n					break;\r\n				}\r\n				if (CParamValidator.isDefined(rule.len) && value.length < rule.len) {\r\n					error_message = \'Value "\' + key + \'" must be a string with a length > \' + rule.len;\r\n				}\r\n				if (CParamValidator.isDefined(rule.regex) && !CParamValidator.ifMatch(value, rule.regex)) {\r\n					error_message = \'Value "\' + key + \'" must match the regular expression "\' + rule.regex + \'"\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.url) && rule.url === true) {\r\n					value = CParamValidator.checkURL(value);\r\n				}\r\n				break;\r\n			case \'integer\':\r\n				if (!CParamValidator.isInteger(value)) {\r\n					error_message = \'Value "\' + key + \'" must be an integer\';\r\n					break;\r\n				}\r\n				value = parseInt(value);\r\n				break;\r\n			case \'float\':\r\n				if (!CParamValidator.isFloat(value)) {\r\n					error_message = \'Value "\' + key + \'" must be a floating-point number\';\r\n					break;\r\n				}\r\n				value = parseFloat(value);\r\n				break;\r\n			case \'boolean\':\r\n				if (CParamValidator.inArray(value, [\'1\', \'true\', \'yes\', \'on\'])) {\r\n					value = true;\r\n				}\r\n				else if (CParamValidator.inArray(value, [\'0\', \'false\', \'no\', \'off\'])) {\r\n					value = false;\r\n				}\r\n				else {\r\n					error_message = \'Value "\' + key + \'" must be a boolean-like.\';\r\n				}\r\n				break;\r\n			case \'array\':\r\n				try {\r\n					value = JSON.parse(value);\r\n				} catch (error) {\r\n					throw \'Value "\' + key + \'" contains invalid JSON.\';\r\n				}\r\n				if (!CParamValidator.isType(value, \'array\')) {\r\n					error_message = \'Value "\' + key + \'" must be an array.\';\r\n				}\r\n				if (CParamValidator.isDefined(rule.tags) && rule.tags === true) {\r\n					value = value.reduce(function(acc, obj) {\r\n						acc[obj.tag] = obj.value || null;\r\n						return acc;\r\n					}, {});\r\n				}\r\n				break;\r\n			case \'object\':\r\n				value = JSON.parse(value);\r\n				if (!CParamValidator.isType(value, \'object\')) {\r\n					error_message = \'Value "\' + key + \'" must be an object.\';\r\n				}\r\n				break;\r\n			default:\r\n				throw \'Unexpected attribute type "\' + rule.type + \'" for value "\' + key + \'". Available: \' +\r\n				[\'integer\', \'float\', \'string\', \'boolean\', \'array\', \'object\'].join(\', \');\r\n		}\r\n		params[key] = value;\r\n		if (CParamValidator.inArray(rule.type, [\'integer\', \'float\']) && error_message === null && (CParamValidator.isDefined(rule.min)\r\n			|| CParamValidator.isDefined(rule.max)) && !CParamValidator.withinRange(value, rule.min, rule.max)) {\r\n			error_message = \'Value "\' + key + \'" must be a number \' + ((CParamValidator.isDefined(rule.min) && CParamValidator.isDefined(rule.max))\r\n				? (rule.min + \'..\' + rule.max) : ((CParamValidator.isDefined(rule.min)) ? \'>\' + rule.min : \'<\' + rule.max));\r\n		}\r\n		else if (CParamValidator.isDefined(rule.array) && !CParamValidator.inArray(value, rule.array)) {\r\n			error_message = \'Value "\' + key + \'" must be in the array \' + JSON.stringify(rule.array);\r\n		}\r\n		else if (CParamValidator.isDefined(rule.macro) && !CParamValidator.isMacroSet(value.toString(), rule.macro)) {\r\n			error_message = \'The macro \' + ((CParamValidator.isDefined(rule.macro)) ? \'{\' + rule.macro + \'} \' : \' \') + \'is not set\';\r\n		}\r\n		if (error_message !== null) {\r\n			if (CParamValidator.isDefined(rule.default) && CParamValidator.isType(rule.default, rule.type)) {\r\n				params[key] = rule.default;\r\n			}\r\n			else {\r\n				Zabbix.log(4, \'Default value for "\' + key + \'" must be a \' + rule.type + \'. Skipped.\');\r\n				throw \'Incorrect value for variable "\' + key + \'". \' + error_message;\r\n			}\r\n		}\r\n\r\n		return this;\r\n	},\r\n\r\n	validate: function(rules, params) {\r\n		if (!CParamValidator.isType(params, \'object\') || CParamValidator.isType(params, \'array\')) {\r\n			throw \'Incorrect parameters value. The value must be an object.\';\r\n		}\r\n		for (var key in rules) {\r\n			CParamValidator.check(key, rules[key], params);\r\n		}\r\n	}\r\n}\r\n\r\nconst CHttpRequest = function(logger) {\r\n	this.request = new HttpRequest();\r\n	if (typeof logger !== \'object\' || logger === null) {\r\n		this.logger = Zabbix;\r\n	}\r\n	else {\r\n		this.logger = logger;\r\n	}\r\n\r\n	this.clearHeader = function() {\r\n		this.request.clearHeader();\r\n	}\r\n\r\n	this.addHeaders = function(value) {\r\n		var headers = [];\r\n\r\n		if (typeof value === \'object\' && value !== null) {\r\n			if (!Array.isArray(value)) {\r\n				Object.keys(value).forEach(function(key) {\r\n					headers.push(key + \': \' + value[key]);\r\n				});\r\n			}\r\n			else {\r\n				headers = value;\r\n			}\r\n		}\r\n		else if (typeof value === \'string\') {\r\n			value.split(\'\\r\\n\').forEach(function(header) {\r\n				headers.push(header);\r\n			});\r\n		}\r\n\r\n		for (var idx in headers) {\r\n			this.request.addHeader(headers[idx]);\r\n		}\r\n	}\r\n\r\n	this.setProxy = function(proxy) {\r\n		this.request.setProxy(proxy);\r\n	}\r\n\r\n	this.plainRequest = function(method, url, data) {\r\n		var resp = null;\r\n		method = method.toLowerCase();\r\n		this.logger.log(4, \'Sending \' + method + \' request:\' + JSON.stringify(data));\r\n		if ([\'get\', \'post\', \'put\', \'patch\', \'delete\', \'trace\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url, data);\r\n		}\r\n		else if ([\'connect\', \'head\', \'options\'].indexOf(method) !== -1) {\r\n			resp = this.request[method](url);\r\n		}\r\n		else {\r\n			throw \'Unexpected method. Method \' + method + \' is not supported.\';\r\n		}\r\n		this.logger.log(4, \'Response has been received: \' + resp);\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.jsonRequest = function(method, url, data) {\r\n		this.addHeaders(\'Content-Type: application/json\');\r\n		var resp = this.plainRequest(method, url, JSON.stringify(data));\r\n		try {\r\n			resp = JSON.parse(resp);\r\n		}\r\n		catch (error) {\r\n			throw \'Failed to parse response: not well-formed JSON was received\';\r\n		}\r\n\r\n		return resp;\r\n	}\r\n\r\n	this.getStatus = function() {\r\n		return this.request.getStatus();\r\n	}\r\n}\r\n\r\nconst CWebhookHelper = {\r\n\r\n	createProblemURL: function(event_source, zabbix_url, trigger_id, event_id) {\r\n		if (event_source === \'0\') {\r\n			return zabbix_url + \'/tr_events.php?triggerid=\' + trigger_id + \'&eventid=\' + event_id;\r\n		} else if (event_source === \'4\') {\r\n			return zabbix_url + \'/zabbix.php?action=service.list\';\r\n		}\r\n\r\n		return zabbix_url;\r\n	},\r\n\r\n};\r\n\r\nvar ZABBIX_SEVERITY_MAP = ["not_classified", "information", "warning", "average", "high", "disaster"],\r\n	serviceLogName = \'Zammad Webhook\',\r\n	Logger = new CLogger(serviceLogName),\r\n	Zammad = CWebhook;\r\n\r\nZammad.prototype.onCheckParams = function () {\r\n	CParamValidator.validate({\r\n		alert_message: {type: \'string\'},\r\n		alert_subject: {type: \'string\'},\r\n		zammad_url: {type: \'string\', url: true},\r\n		zammad_customer: {type: \'string\'},\r\n		zammad_access_token: {type: \'string\'},\r\n		zammad_group: {type: \'string\'},\r\n		zammad_enable_tags: {type: \'boolean\', default: false},\r\n		event_nseverity: {type: \'integer\', default: -1},\r\n		zabbix_url: {type: \'string\', url: true}\r\n	}, this.params);\r\n\r\n	if (CParamValidator.inArray(this.params.event_source, [\'0\', \'3\', \'4\'])) {\r\n		CParamValidator.validate({\r\n			event_tags: {type: \'array\', macro: \'EVENT.TAGSJSON\', tags: true, default: {}}\r\n		}, this.params);\r\n	}\r\n\r\n	var priority;\r\n\r\n	if (this.params.event_nseverity >= 0 && this.params.event_nseverity < ZABBIX_SEVERITY_MAP.length) {\r\n		priority = this.params[\'severity_\' + ZABBIX_SEVERITY_MAP[this.params.event_nseverity]];\r\n	}\r\n	this.priority = (CParamValidator.isDefined(priority)) ? priority.trim() : null;\r\n\r\n	this.result = {tags: {}};\r\n};\r\n\r\nZammad.prototype.onProblem = function (alert) {\r\n	if (CParamValidator.isDefined(this.params.event_tags[\'__zbx_zammad_ticket_id\'])) {\r\n		return this.onUpdate(alert);\r\n	}\r\n\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n\r\n	this.request.addHeaders(\'Authorization: Token token=\' + this.params.zammad_access_token);\r\n\r\n	var payload_data = {\r\n		title: this.params.alert_subject,\r\n		group: this.params.zammad_group,\r\n		article: {\r\n			subject: this.params.alert_subject,\r\n			body: this.params.alert_message + \'\\n\' + CWebhookHelper.createProblemURL(this.params.event_source, this.params.zabbix_url, this.params.trigger_id, this.params.event_id),\r\n			type: \'note\',\r\n			internal: false\r\n		},\r\n		customer: this.params.zammad_customer\r\n	};\r\n\r\n	if (this.priority) {\r\n		payload_data.priority_id = this.priority;\r\n	}\r\n\r\n	const response = this.request.jsonRequest(\'POST\', this.params.zammad_url + \'/api/v1/tickets\', payload_data);\r\n\r\n	if (this.request.getStatus() != 201 || !CParamValidator.isDefined(response.id)) {\r\n		var message = \'Cannot create Zammad ticket. Request failed with status code \' + this.request.getStatus();\r\n\r\n		if (CParamValidator.isDefined(response.error) && Object.keys(response.error).length > 0) {\r\n			message += \': \' + response.error;\r\n		}\r\n\r\n		throw message + \' Check debug log for more information.\';\r\n	}\r\n\r\n	this.result.tags = {\r\n		__zbx_zammad_ticket_id: response.id,\r\n		__zbx_zammad_ticketlink: this.params.zammad_url + \'/#ticket/zoom/\' + response.id\r\n	};\r\n\r\n	if (this.params.zammad_enable_tags && Object.keys(this.params.event_tags).length > 0 && CParamValidator.inArray(this.params.event_source, [\'0\', \'3\', \'4\'])) {\r\n		this.request.clearHeader();\r\n		this.request.addHeaders({\r\n			"Content-Type": "application/json",\r\n			"Authorization": "Token token=" + this.params.zammad_access_token\r\n		});\r\n\r\n		payload_data = {\r\n			item: \'\',\r\n			object: \'Ticket\',\r\n			o_id: response.id\r\n		};\r\n\r\n		try {\r\n			for (var tag in this.params.event_tags) {\r\n				payload_data.item = tag;\r\n\r\n				if (this.params.event_tags[tag]) {\r\n					payload_data.item += ": " + this.params.event_tags[tag];\r\n				}\r\n\r\n				this.request.plainRequest(\'POST\', this.params.zammad_url + \'/api/v1/tags/add\', JSON.stringify(payload_data));\r\n\r\n				if (this.request.getStatus() != 201) {\r\n					Logger.log(Logger.INFO, \'Failed to set tag: \' + tag);\r\n				}\r\n			}\r\n		}\r\n		catch (error) {\r\n			Logger.log(Logger.INFO, \'Failed to add ticket tags: \' + error);\r\n		}\r\n	}\r\n\r\n	return this.result;\r\n}\r\n\r\nZammad.prototype.onUpdate = function (alert) {\r\n	Logger.log(Logger.INFO, \'Source: \' + alert.source + \'; Event: \' + alert.event);\r\n\r\n	if (!CParamValidator.isDefined(this.params.event_tags[\'__zbx_zammad_ticket_id\'])) {\r\n		throw "Failed to update the existing ticket: no ticket ID was received."\r\n	}\r\n\r\n\r\n	this.request.addHeaders(\'Authorization: Token token=\' + this.params.zammad_access_token);\r\n\r\n	const payload_data = {\r\n		ticket_id: this.params.event_tags[\'__zbx_zammad_ticket_id\'],\r\n		subject: this.params.alert_subject,\r\n		body: this.params.alert_message,\r\n		type: \'note\',\r\n		internal: false\r\n	};\r\n\r\n	const response = this.request.jsonRequest(\'POST\', this.params.zammad_url + \'/api/v1/ticket_articles\', payload_data);\r\n\r\n	if (this.request.getStatus() != 201 || !CParamValidator.isDefined(response.id)) {\r\n		var message = \'Cannot update Zammad ticket. Request failed with status code \' + this.request.getStatus();\r\n\r\n		if (CParamValidator.isDefined(response.error) && Object.keys(response.error).length > 0) {\r\n			message += \': \' + response.error;\r\n		}\r\n\r\n		throw message + \' Check debug log for more information.\';\r\n	}\r\n\r\n	return this.result;\r\n}\r\n\r\nZammad.prototype.onResolve = function (alert) {\r\n	return this.onUpdate(alert);\r\n}\r\n\r\nZammad.prototype.onDiscovery = function (alert) {\r\n	return this.onProblem(alert);\r\n}\r\n\r\nZammad.prototype.onAutoreg = function (alert) {\r\n	return this.onProblem(alert);\r\n}\r\n\r\ntry {\r\n	var hook = new Zammad(value);\r\n	hook.request = new CHttpRequest(Logger);\r\n	return hook.run();\r\n}\r\ncatch (error) {\r\n	Logger.log(Logger.WARN, \'notification failed: \' + error);\r\n	throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_zammad_ticketlink}','Zammad: Ticket #{EVENT.TAGS.__zbx_zammad_ticket_id}','This media type integrates your Zabbix installation with your Zammad installation using the Zabbix webhook feature.\r\n\r\nZammad configuration:\r\n\r\n1. Check that API Token Access is enabled in "Settings" → "System" → "API".\r\n2. Open the profile settings of the customer user and create a new Personal User Token.\r\n3. Set the "ticket.agent" permission for the token and press Create.\r\n4. Copy and save the created token somewhere, as it will be shown only once for security reasons.\r\n\r\nZabbix configuration:\r\n\r\n1. Before you can start using Zammad webhook, set up the global macro "{$ZABBIX.URL}":\r\n- In the Zabbix web interface, go to "Administration" → "Macros" section in the dropdown menu in the top left corner.\r\n- Set up the global macro "{$ZABBIX.URL}" which will contain the URL to the Zabbix frontend. The URL should be either an IP address, a fully qualified domain name, or localhost.\r\n- Specifying a protocol is mandatory, whereas the port is optional. Depending on the web server configuration you might also need to append "/zabbix" to the end of URL. Good examples:\r\n  - http://zabbix.com\r\n  - https://zabbix.lan/zabbix\r\n  - http://server.zabbix.lan/\r\n  - http://localhost\r\n  - http://127.0.0.1:8080\r\n- Bad examples:\r\n  - zabbix.com\r\n  - http://zabbix/\r\n\r\n2. Set the following webhook parameters:\r\n- zammad_access_token - the access token that you created during Zammad configuration\r\n- zammad_url - the frontend URL of your Zammad installation\r\n- zammad_customer - the Zammad user email\r\n- zammad_enable_tags - if you want to add the Zabbix event tags to the Zammad tickets that are created, you can set it to one of the following values: "1", "true", "yes", "on" (note, that if the tag support is enabled, each tag is sent via separate HTTP request and created tags will also remain in the Zammad when tickets are closed/deleted)\r\n- zammad_group - if needed, you can change the Zammad user group\r\n\r\n3. If you want to prioritize issues according to the severity values in Zabbix, you can define mapping parameters (create them as additional webhook parameters):\r\n- severity_<name> - the Zammad priority ID (<name> in the parameter name can be one of the following values: "not_classified", "information", "warning", "average", "high", "disaster")\r\n\r\n4. Create a Zabbix user and add media:\r\n- If you want to create a new user, go to the "Users" → "Users" section, click the "Create user" button in the top right corner. In the "User" tab, fill in all required fields (marked with red asterisks).\r\n- In the "Media" tab, add a new media and select "Zammad" type from the drop-down list. Add any value to the "Send to" field: it is required to be filled, but it is not used.\r\n- Make sure this user has access to all hosts for which you would like problem notifications to be sent to Zammad.\r\n\r\n5. Great! You can now start using this media type in actions and create tickets!\r\n\r\nYou can find the latest version of this media and additional information in the official Zabbix repository:\r\nhttps://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/zammad','0'),
('101','4','Zendesk','','','','','','','','25','0','0','0','0','1','3','10s','1','var Zendesk = {\r\n    params: {},\r\n\r\n    setParams: function (params) {\r\n        if (typeof params !== \'object\') {\r\n            return;\r\n        }\r\n\r\n        Zendesk.params = params;\r\n        if (typeof Zendesk.params.url === \'string\') {\r\n            if (!Zendesk.params.url.endsWith(\'/\')) {\r\n                Zendesk.params.url += \'/\';\r\n            }\r\n            Zendesk.params.url += \'api/v2/\';\r\n        }\r\n    },\r\n\r\n    addCustomFields: function (data, fields) {\r\n        if (typeof fields === \'object\' && Object.keys(fields).length) {\r\n            var schema = Zendesk.getSchema(),\r\n                arr = [],\r\n                i,\r\n                n;\r\n\r\n            if (schema) {\r\n                Object.keys(fields)\r\n                    .forEach(function(field) {\r\n                        for (i = 0, n = schema.ticket_fields.length; i < n; i++) {\r\n                            if (schema.ticket_fields[i].id == field\r\n                                && [\'text\', \'integer\', \'date\'].indexOf(schema.ticket_fields[i].type) !== -1){\r\n\r\n                                switch (schema.ticket_fields[i].type) {\r\n                                    case \'integer\':\r\n                                        fields[field] = parseInt(fields[field]);\r\n                                        break;\r\n                                    case \'date\':\r\n                                        if (fields[field].match(/^\\d{4}[.-]\\d{2}[.-]\\d{2}$/) !== null) {\r\n                                            fields[field] = fields[field].replace(/\\./g, \'-\');\r\n                                        }\r\n                                        else {\r\n                                            fields[field] = \'\';\r\n                                        }\r\n                                        break;\r\n                                }\r\n\r\n                                arr.push({id: field, value: fields[field]});\r\n                                break;\r\n                            }\r\n                        }\r\n                    });\r\n\r\n                if (arr.length) {\r\n                    data.ticket[\'custom_fields\'] = arr;\r\n                }\r\n            }\r\n            else {\r\n                Zabbix.log(4, \'[Zendesk Webhook] Failed to retrieve field schema.\');\r\n            }\r\n        }\r\n\r\n        return data;\r\n    },\r\n\r\n    request: function (method, query, data) {\r\n        [\'url\', \'token\', \'type\'].forEach(function (field) {\r\n            if (typeof Zendesk.params !== \'object\' || typeof Zendesk.params[field] === \'undefined\') {\r\n                throw \'Required Zendesk param is not set: \' + field + \'\\n\' + Zendesk.params[field];\r\n            }\r\n        });\r\n\r\n        var response,\r\n            url = Zendesk.params.url + query,\r\n            request = new HttpRequest();\r\n\r\n        if (typeof Zendesk.HTTPProxy === \'string\' && Zendesk.HTTPProxy.trim() !== \'\') {\r\n            request.setProxy(Zendesk.HTTPProxy);\r\n        }\r\n\r\n        request.addHeader(\'Content-Type: application/json\');\r\n        request.addHeader(\'Authorization: Basic \' + btoa(Zendesk.params.token));\r\n\r\n        if (typeof data !== \'undefined\') {\r\n            data = JSON.stringify(data);\r\n        }\r\n\r\n        Zabbix.log(4, \'[Zendesk Webhook] Sending request: \' + url + ((typeof data === \'string\') ? (\' \' + data) : \'\'));\r\n\r\n        switch (method) {\r\n            case \'get\':\r\n                response = request.get(url, data);\r\n                break;\r\n\r\n            case \'post\':\r\n                response = request.post(url, data);\r\n                break;\r\n\r\n            case \'put\':\r\n                response = request.put(url, data);\r\n                break;\r\n\r\n            default:\r\n                throw \'Unsupported HTTP request method: \' + method;\r\n        }\r\n\r\n        Zabbix.log(4, \'[Zendesk Webhook] Received response with status code \' + request.getStatus() + \'. \' + response);\r\n\r\n        if (response !== null) {\r\n            try {\r\n                response = JSON.parse(response);\r\n            }\r\n            catch (error) {\r\n                Zabbix.log(4, \'[Zendesk Webhook] Failed to parse response received from Zendesk.\');\r\n            }\r\n        }\r\n\r\n        if (request.getStatus() < 200 || request.getStatus() >= 300) {\r\n            var message = \'Request failed with status code \' + request.getStatus();\r\n\r\n            if (response !== null && typeof response.error !== \'undefined\'\r\n                && Object.keys(response.error).length > 0) {\r\n                message += \': \' + JSON.stringify(response.error);\r\n            }\r\n            else if (response !== null && typeof response.description !== \'undefined\'\r\n                && Object.keys(response.description).length > 0) {\r\n                message += \': \' + JSON.stringify(response.description);\r\n            }\r\n            else {\r\n                message += \'. \' + response;\r\n            }\r\n            throw message + \'. Check debug log for more information.\';\r\n        }\r\n\r\n        return {\r\n            status: request.getStatus(),\r\n            response: response\r\n        };\r\n    },\r\n\r\n    getSchema: function() {\r\n        var result = Zendesk.request(\'get\', \'ticket_fields.json\');\r\n\r\n        return result.response;\r\n    },\r\n\r\n    createIssue: function(data, fields) {\r\n        var result = Zendesk.request(\'post\', \'tickets.json\', Zendesk.addCustomFields(data, fields));\r\n\r\n        if (typeof result.response !== \'object\' || typeof result.response.ticket.id === \'undefined\'\r\n            || result.status != 201) {\r\n            throw \'Cannot create Zendesk issue. Check debug log for more information.\';\r\n        }\r\n\r\n        return result.response.ticket.id;\r\n    },\r\n\r\n    updateIssue: function(data, fields) {\r\n        Zendesk.request(\'put\', \'tickets/\' + Zendesk.params.issue_key + \'.json\', Zendesk.addCustomFields(data, fields));\r\n    }\r\n};\r\n\r\ntry {\r\n    var params = JSON.parse(value),\r\n        fields = {},\r\n        zendesk = {},\r\n        update = {},\r\n        data = {},\r\n        result = {tags: {}},\r\n        required_params = [\r\n            \'alert_subject\',\r\n            \'alert_message\',\r\n            \'event_id\',\r\n            \'event_source\',\r\n            \'event_value\',\r\n            \'event_update_status\'\r\n        ],\r\n        severities = [\r\n            {name: \'not_classified\', color: \'#97AAB3\'},\r\n            {name: \'information\', color: \'#7499FF\'},\r\n            {name: \'warning\', color: \'#FFC859\'},\r\n            {name: \'average\', color: \'#FFA059\'},\r\n            {name: \'high\', color: \'#E97659\'},\r\n            {name: \'disaster\', color: \'#E45959\'},\r\n            {name: \'resolved\', color: \'#009900\'},\r\n            {name: \'default\', color: \'#000000\'}\r\n        ],\r\n        priority;\r\n\r\n    Object.keys(params)\r\n        .forEach(function (key) {\r\n            if (key.startsWith(\'zendesk_\')) {\r\n                zendesk[key.substring(8)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'customfield_\')) {\r\n                fields[key.substring(12)] = params[key];\r\n            }\r\n            else if (key.startsWith(\'event_update_\')) {\r\n                update[key.substring(13)] = params[key];\r\n            }\r\n            else if (required_params.indexOf(key) !== -1 && params[key].trim() === \'\') {\r\n                throw \'Parameter \' + key + \' cannot be empty.\';\r\n            }\r\n        });\r\n\r\n    // Possible values: question, incident, problems, task\r\n    if ([\'question\', \'incident\', \'problem\', \'task\'].indexOf(params.zendesk_type) === -1) {\r\n        throw \'Incorrect "zendesk_type" parameter given: \' + params.zendesk_type +\r\n            \'\\nMust be one of question, incident, problem, task.\';\r\n    }\r\n\r\n    // Possible values: 0 - Trigger, 1 - Discovery, 2 - Autoregistration, 3 - Internal.\r\n    if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {\r\n        throw \'Incorrect "event_source" parameter given: \' + params.event_source + \'\\nMust be 0-3.\';\r\n    }\r\n\r\n    // Check {EVENT.VALUE} for trigger-based and internal events.\r\n    // Possible values: 1 for problem, 0 for recovering\r\n    if (params.event_value !== \'0\' && params.event_value !== \'1\'\r\n        && (params.event_source === \'0\' || params.event_source === \'3\')) {\r\n        throw \'Incorrect "event_value" parameter given: \' + params.event_value + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    // Check {EVENT.UPDATE.STATUS} only for trigger-based events.\r\n    // Possible values: 0 - Webhook was called because of problem/recovery event, 1 - Update operation.\r\n    if (params.event_source === \'0\' && params.event_update_status !== \'0\' && params.event_update_status !== \'1\') {\r\n        throw \'Incorrect "event_update_status" parameter given: \' + params.event_update_status + \'\\nMust be 0 or 1.\';\r\n    }\r\n\r\n    if (params.event_source !== \'0\' && params.event_value === \'0\') {\r\n        throw \'Recovery operations are supported only for trigger-based actions.\';\r\n    }\r\n\r\n    // Zendesk_issue_key must be a positive integer if an update action is being performed.\r\n    if (params.event_source === \'0\' && ((params.event_value === \'1\' && params.event_update_status === \'1\')\r\n        || (params.event_value === \'0\' && (params.event_update_status === \'0\' || params.event_update_status === \'1\')))\r\n        && (isNaN(parseInt(params.zendesk_issue_key)) || parseInt(params.zendesk_issue_key) < 1 )) {\r\n        throw \'Incorrect "zendesk_issue_key" parameter given: \' + params.zendesk_issue_key +\r\n            \'\\nMust be positive integer.\';\r\n    }\r\n\r\n    if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {\r\n        params.event_nseverity = \'7\';\r\n    }\r\n\r\n    if (params.event_value === \'0\') {\r\n        params.event_nseverity = \'6\';\r\n    }\r\n\r\n    priority = params[\'severity_\' + severities[params.event_nseverity].name] || severities[7].name;\r\n\r\n    Zendesk.setParams(zendesk);\r\n    Zendesk.HTTPProxy = params.HTTPProxy;\r\n\r\n    // Create issue for non trigger-based events.\r\n    if (params.event_source !== \'0\' && params.event_value !== \'0\') {\r\n        data = {\r\n            ticket: {\r\n                external_id: params.event_id,\r\n                type: Zendesk.params.type,\r\n                status: \'new\',\r\n                subject: params.alert_subject,\r\n                comment: {\r\n                    body: params.alert_message,\r\n                    public: \'false\'\r\n                },\r\n                priority: priority,\r\n                tags: params.event_tags\r\n            }\r\n        };\r\n\r\n        Zendesk.createIssue(data, fields);\r\n    }\r\n    // Create issue for trigger-based events.\r\n    else if (params.event_value === \'1\' && update.status === \'0\') {\r\n        data = {\r\n            ticket: {\r\n                external_id: params.event_id,\r\n                type: Zendesk.params.type,\r\n                status: \'new\',\r\n                subject: params.alert_subject,\r\n                comment: {\r\n                    body: params.zbxurl + (params.zbxurl.endsWith(\'/\') ? \'\' : \'/\') + \'tr_events.php?triggerid=\' +\r\n                        params.trigger_id + \'&eventid=\' + params.event_id + \'\\n\' + params.alert_message,\r\n                    public: \'false\'\r\n                },\r\n                priority: priority,\r\n                tags: params.event_tags\r\n            }\r\n        };\r\n        var key = Zendesk.createIssue(data, fields);\r\n\r\n        result.tags.__zbx_zdk_issuekey = key;\r\n        result.tags.__zbx_zdk_issuelink = params.zendesk_url +\r\n            (params.zendesk_url.endsWith(\'/\') ? \'\' : \'/\') + \'agent/tickets/\' + key;\r\n    }\r\n    // Update created issue for trigger-based event.\r\n    else {\r\n        data = {\r\n            ticket: {\r\n                type: Zendesk.params.type,\r\n                subject: params.alert_subject,\r\n                comment: {\r\n                    body: params.alert_message,\r\n                    public: \'false\'\r\n                }\r\n            }\r\n        };\r\n\r\n        Zendesk.updateIssue(data, fields);\r\n    }\r\n\r\n    return JSON.stringify(result);\r\n}\r\ncatch (error) {\r\n    Zabbix.log(3, \'[Zendesk Webhook] ERROR: \' + error);\r\n    throw \'Sending failed: \' + error;\r\n}','30s','1','1','{EVENT.TAGS.__zbx_zdk_issuelink}','Zendesk: {EVENT.TAGS.__zbx_zdk_issuekey}','','0');
