1<?php
2
3//Pandora FMS- http://pandorafms.com
4// ==================================================
5// Copyright (c) 2005-2009 Artica Soluciones Tecnologicas
6// Please see http://pandorafms.org for full contribution list
7
8// This program is free software; you can redistribute it and/or
9// modify it under the terms of the  GNU Lesser General Public License
10// as published by the Free Software Foundation; version 2
11
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15// GNU General Public License for more details.
16
17global $config;
18
19//Set character encoding to UTF-8 - fixes a lot of multibyte character headaches
20
21require_once('functions_agents.php');
22require_once('functions_modules.php');
23include_once($config['homedir'] . "/include/functions_profile.php");
24include_once($config['homedir'] . "/include/functions.php");
25include_once($config['homedir'] . "/include/functions_ui.php");
26include_once($config['homedir'] . "/include/functions_graph.php");
27include_once($config['homedir'] . "/include/functions_events.php");
28include_once($config['homedir'] . "/include/functions_groups.php");
29include_once($config['homedir'] . "/include/functions_network_components.php");
30include_once($config['homedir'] . "/include/functions_netflow.php");
31include_once($config['homedir'] . "/include/functions_servers.php");
32include_once($config['homedir'] . "/include/functions_planned_downtimes.php");
33enterprise_include_once ('include/functions_local_components.php');
34enterprise_include_once ('include/functions_events.php');
35enterprise_include_once ('include/functions_agents.php');
36enterprise_include_once ('include/functions_modules.php');
37
38/**
39 * Parse the "other" parameter.
40 *
41 * @param string $other
42 * @param mixed $otherType
43 * @return mixed
44 */
45function parseOtherParameter($other, $otherType) {
46
47	switch ($otherType) {
48		case 'url_encode':
49			$returnVar = array('type' => 'string', 'data' => urldecode($other));
50			break;
51		default:
52			if (strpos($otherType, 'url_encode_separator_') !== false) {
53				$separator = str_replace('url_encode_separator_', '', $otherType);
54				$returnVar = array('type' => 'array', 'data' => explode($separator, $other));
55				foreach ($returnVar['data'] as $index => $element)
56					$returnVar['data'][$index] = urldecode($element);
57			}
58			else {
59				$returnVar = array('type' => 'string', 'data' => urldecode($other));
60			}
61			break;
62	}
63
64	return $returnVar;
65}
66
67/**
68 *
69 * @param $typeError
70 * @param $returnType
71 * @return unknown_type
72 */
73function returnError($typeError, $returnType = 'string') {
74	switch ($typeError) {
75		case 'no_set_no_get_no_help':
76			returnData($returnType,
77				array('type' => 'string', 'data' => __('No set or get or help operation.')));
78			break;
79		case 'no_exist_operation':
80			returnData($returnType,
81				array('type' => 'string', 'data' => __('This operation does not exist.')));
82			break;
83		case 'id_not_found':
84			returnData($returnType,
85				array('type' => 'string', 'data' => __('Id does not exist in BD.')));
86			break;
87		default:
88			returnData("string",
89				array('type' => 'string', 'data' => __($returnType)));
90			break;
91	}
92}
93
94/**
95 *
96 * @param $returnType
97 * @param $data
98 * @param $separator
99 *
100 * @return
101 */
102function returnData($returnType, $data, $separator = ';') {
103	switch ($returnType) {
104		case 'string':
105			if ($data['type'] == 'string') {
106				echo $data['data'];
107			}
108			else {
109				//TODO
110			}
111			break;
112		case 'csv':
113		case 'csv_head':
114			switch ($data['type']) {
115				case 'array':
116					if (array_key_exists('list_index', $data))
117					{
118						if ($returnType == 'csv_head') {
119							foreach($data['list_index'] as $index) {
120								echo $index;
121								if (end($data['list_index']) == $index)
122									echo "\n";
123								else
124									echo $separator;
125							}
126						}
127						foreach($data['data'] as $dataContent) {
128							foreach($data['list_index'] as $index) {
129								if (array_key_exists($index, $dataContent))
130									echo str_replace("\n", " ", $dataContent[$index]);
131								if (end($data['list_index']) == $index)
132									echo "\n";
133								else
134									echo $separator;
135							}
136						}
137					}
138					else {
139						if (!empty($data['data'])) {
140
141							foreach ($data['data'] as $dataContent) {
142
143								$clean = array_map("array_apply_io_safe_output", $dataContent);
144
145								foreach ($clean as $k => $v) {
146									$clean[$k] = str_replace("\r", "\n", $clean[$k]);
147									$clean[$k] = str_replace("\n", " ", $clean[$k]);
148									$clean[$k] = strip_tags($clean[$k]);
149									$clean[$k] = str_replace(';',' ',$clean[$k]);
150								}
151								$row = implode($separator, $clean);
152
153								echo $row . "\n";
154							}
155						}
156					}
157					break;
158				case 'string':
159					echo $data['data'];
160					break;
161			}
162			break;
163		case 'json':
164			$data = array_apply_io_safe_output($data);
165			header('Content-type: application/json');
166			echo json_encode ($data);
167			break;
168	}
169}
170
171function array_apply_io_safe_output($item) {
172	return io_safe_output($item);
173}
174
175/**
176 *
177 * @param $ip
178 * @return unknown_type
179 */
180function isInACL($ip) {
181	global $config;
182
183	if (in_array($ip, $config['list_ACL_IPs_for_API']))
184		return true;
185
186	// If the IP is not in the list, we check one by one, all the wildcard registers
187	foreach($config['list_ACL_IPs_for_API'] as $acl_ip) {
188		if (preg_match('/\*/', $acl_ip)) {
189
190			// Scape for protection
191			$acl_ip = str_replace('.','\.',$acl_ip);
192
193			// Replace wilcard by .* to do efective in regular expression
194			$acl_ip = str_replace('*','.*',$acl_ip);
195
196			// If the string match with the beginning of the IP give it access
197			if (preg_match('/'.$acl_ip.'/', $ip)) {
198				return true;
199			}
200		}
201	}
202
203	return false;
204}
205
206// Return string OK,[version],[build]
207function api_get_test() {
208	global $pandora_version;
209	global $build_version;
210
211	echo "OK,$pandora_version,$build_version";
212
213	if (defined ('METACONSOLE')) {
214		echo ",meta";
215	}
216}
217
218//Return OK if agent cache is activated
219function api_get_test_agent_cache(){
220	if (defined ('METACONSOLE')) {
221		return;
222	}
223
224	$status = enterprise_hook('test_agent_cache', array());
225	if ($status === ENTERPRISE_NOT_HOOK) {
226		echo 'ERR';
227		return;
228	}
229	echo $status;
230
231}
232
233// Returs the string OK if a connection to the event replication DB can be established.
234function api_get_test_event_replication_db() {
235	if (defined ('METACONSOLE')) {
236		return;
237	}
238
239	$status = enterprise_hook('events_test_replication_db', array());
240	if ($status === ENTERPRISE_NOT_HOOK) {
241		echo 'ERR';
242		return;
243	}
244	echo $status;
245}
246
247//-------------------------DEFINED OPERATIONS FUNCTIONS-----------------
248function api_get_groups($thrash1, $thrash2, $other, $returnType, $user_in_db) {
249	if (defined ('METACONSOLE')) {
250		return;
251	}
252
253	if ($other['type'] == 'string') {
254		if ($other['data'] != '') {
255			returnError('error_parameter', 'Error in the parameters.');
256			return;
257		}
258		else {//Default values
259			$separator = ';';
260		}
261	}
262	else if ($other['type'] == 'array') {
263		$separator = $other['data'][0];
264	}
265
266	$groups = users_get_groups ($user_in_db, "IR");
267
268	$data_groups = array();
269	foreach ($groups as $id => $group) {
270		$data_groups[] = array($id, $group);
271	}
272
273	$data['type'] = 'array';
274	$data['data'] = $data_groups;
275
276	returnData($returnType, $data, $separator);
277}
278
279function api_get_agent_module_name_last_value($agentName, $moduleName, $other = ';', $returnType)
280{
281	global $config;
282
283	$idAgent = agents_get_agent_id($agentName);
284	switch ($config["dbtype"]) {
285		case "mysql":
286			$sql = sprintf('SELECT id_agente_modulo
287				FROM tagente_modulo
288				WHERE id_agente = %d AND nombre LIKE "%s"', $idAgent, $moduleName);
289			break;
290		case "postgresql":
291		case "oracle":
292			$sql = sprintf('SELECT id_agente_modulo
293				FROM tagente_modulo
294				WHERE id_agente = %d AND nombre LIKE \'%s\'', $idAgent, $moduleName);
295			break;
296	}
297
298	$idModuleAgent = db_get_value_sql($sql);
299
300	if ($idModuleAgent === false) {
301		switch ($other['type']) {
302			case 'string':
303				switch ($other['data']) {
304					case 'error_message':
305					default:
306						returnError('id_not_found', $returnType);
307					break;
308				}
309				break;
310			case 'array':
311				switch ($other['data'][0]) {
312					case 'error_value':
313						returnData($returnType, array('type' => 'string', 'data' => $other['data'][1]));
314						break;
315				}
316				break;
317		}
318	}
319	else {
320		api_get_module_last_value($idModuleAgent, null, $other, $returnType);
321	}
322}
323
324function api_get_module_last_value($idAgentModule, $trash1, $other = ';', $returnType) {
325	if (defined ('METACONSOLE')) {
326		return;
327	}
328
329	$sql = sprintf('SELECT datos
330		FROM tagente_estado
331		WHERE id_agente_modulo = %d', $idAgentModule);
332	$value = db_get_value_sql($sql);
333	if ($value === false) {
334		switch ($other['type']) {
335			case 'string':
336				switch ($other['data']) {
337					case 'error_message':
338					default:
339						returnError('id_not_found', $returnType);
340					break;
341				}
342				break;
343			case 'array':
344				switch ($other['data'][0]) {
345					case 'error_value':
346						returnData($returnType, array('type' => 'string', 'data' => $other['data'][1]));
347						break;
348				}
349				break;
350		}
351	}
352	else {
353		$data = array('type' => 'string', 'data' => $value);
354		returnData($returnType, $data);
355	}
356}
357
358/*** DB column mapping table used by tree_agents (and get module_properties) ***/
359
360/* agent related field mappings (output field => column designation for 'tagente') */
361$agent_field_column_mapping = array(
362	/* agent_id is not in this list (because it is mandatory) */
363	/* agent_id_group is not in this list  */
364	'agent_name' => 'nombre as agent_name',
365	'agent_direction' => 'direccion as agent_direction',
366	'agent_comentary' => 'comentarios as agent_comentary',
367	'agent_last_contant' => 'ultimo_contacto as agent_last_contant',
368	'agent_mode' => 'modo as agent_mode',
369	'agent_interval' => 'intervalo as agent_interval',
370	'agent_id_os' => 'id_os as agent_id_os',
371	'agent_os_version' => 'os_version as agent_os_version',
372	'agent_version' => 'agent_version as agent_version',
373	'agent_last_remote_contact' => 'ultimo_contacto_remoto as agent_last_remote_contact',
374	'agent_disabled' => 'disabled as agent_disabled',
375	'agent_id_parent' => 'id_parent as agent_id_parent',
376	'agent_custom_id' => 'custom_id as agent_custom_id',
377	'agent_server_name' => 'server_name as agent_server_name',
378	'agent_cascade_protection' => 'cascade_protection as agent_cascade_protection');
379
380/* module related field mappings 1/2 (output field => column for 'tagente_modulo') */
381$module_field_column_mampping = array(
382	/* module_id_agent_modulo  is not in this list */
383	'module_id_agent' => 'id_agente as module_id_agent',
384	'module_id_module_type' => 'id_tipo_modulo as module_id_module_type',
385	'module_description' => 'descripcion as module_description',
386	'module_name' => 'nombre as module_name',
387	'module_max' => 'max as module_max',
388	'module_min' => 'min as module_min',
389	'module_interval' => 'module_interval',
390	'module_tcp_port' => 'tcp_port as module_tcp_port',
391	'module_tcp_send' => 'tcp_send as module_tcp_send',
392	'module_tcp_rcv' => 'tcp_rcv as module_tcp_rcv',
393	'module_snmp_community' => 'snmp_community as module_snmp_community',
394	'module_snmp_oid' => 'snmp_oid as module_snmp_oid',
395	'module_ip_target' => 'ip_target as module_ip_target',
396	'module_id_module_group' => 'id_module_group as module_id_module_group',
397	'module_flag' => 'flag as module_flag',
398	'module_id_module' => 'id_modulo as module_id_module',
399	'module_disabled' => 'disabled as module_disabled',
400	'module_id_export' => 'id_export as module_id_export',
401	'module_plugin_user' => 'plugin_user as module_plugin_user',
402	'module_plugin_pass' => 'plugin_pass as module_plugin_pass',
403	'module_plugin_parameter' => 'plugin_parameter as module_plugin_parameter',
404	'module_id_plugin' => 'id_plugin as module_id_plugin',
405	'module_post_process' => 'post_process as module_post_process',
406	'module_prediction_module' => 'prediction_module as module_prediction_module',
407	'module_max_timeout' => 'max_timeout as module_max_timeout',
408	'module_max_retries' => 'max_retries as module_max_retries',
409	'module_custom_id' => 'custom_id as module_custom_id',
410	'module_history_data' => 'history_data as module_history_data',
411	'module_min_warning' => 'min_warning as module_min_warning',
412	'module_max_warning' => 'max_warning as module_max_warning',
413	'module_str_warning' => 'str_warning as module_str_warning',
414	'module_min_critical' => 'min_critical as module_min_critical',
415	'module_max_critical' => 'max_critical as module_max_critical',
416	'module_str_critical' => 'str_critical as module_str_critical',
417	'module_min_ff_event' => 'min_ff_event as module_min_ff_event',
418	'module_delete_pending' => 'delete_pending as module_delete_pending',
419	'module_plugin_macros' => 'macros as module_plugin_macros',
420	'module_macros' => 'module_macros as module_macros');
421
422/* module related field mappings 2/2 (output field => column for 'tagente_estado') */
423$estado_fields_to_columns_mapping = array(
424	/* module_id_agent_modulo  is not in this list */
425	'module_id_agent_state' => 'id_agente_estado as module_id_agent_state',
426	'module_data' => 'datos as module_data',
427	'module_timestamp' => 'timestamp as module_timestamp',
428	'module_state' => 'estado as module_state',
429	'module_last_try' => 'last_try as module_last_try',
430	'module_utimestamp' => 'utimestamp as module_utimestamp',
431	'module_current_interval' => 'current_interval as module_current_interval',
432	'module_running_by' => 'running_by as module_running_by',
433	'module_last_execution_try' => 'last_execution_try as module_last_execution_try',
434	'module_status_changes' => 'status_changes as module_status_changes',
435	'module_last_status' => 'last_status as module_last_status');
436
437/*** end of DB column mapping table ***/
438
439/**
440 *
441 * @param $trash1
442 * @param $trahs2
443 * @param mixed $other If $other is string is only the separator,
444 *  but if it's array, $other as param is <separator>;<replace_return>;(<field_1>,<field_2>...<field_n>) in this order
445 *  and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_<separator>)
446 *  example:
447 *
448 *  return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " "
449 *  api.php?op=get&op2=tree_agents&return_type=csv&other=;| |type_row,group_id,agent_name&other_mode=url_encode_separator_|
450 *
451 *
452 * @param $returnType
453 * @return unknown_type
454 */
455function api_get_tree_agents($trash1, $trahs2, $other, $returnType) {
456	if (defined ('METACONSOLE')) {
457		return;
458	}
459
460	if ($other['type'] == 'array') {
461		$separator = $other['data'][0];
462		$returnReplace = $other['data'][1];
463		if (trim($other['data'][2]) == '')
464			$fields = false;
465		else {
466			$fields = explode(',', $other['data'][2]);
467			foreach($fields as $index => $field)
468				$fields[$index] = trim($field);
469		}
470
471	}
472	else {
473		if (strlen($other['data']) == 0)
474			$separator = ';'; //by default
475		else
476			$separator = $other['data'];
477		$returnReplace = ' ';
478		$fields = false;
479	}
480
481	/** NOTE: if you want to add an output field, you have to add it to;
482		1. $master_fields (field name)
483		2. one of following field_column_mapping array (a pair of field name and corresponding column designation)
484
485		e.g. To add a new field named 'agent_NEWFIELD' that comes from tagente's COLUMN_X , you have to add;
486		1. "agent_NEW_FIELD"  to $master_fields
487		2. "'agent_NEW_FIELD' => 'agent_NEWFIELD as COLUMN_X'"  to $agent_field_column_mapping
488		**/
489
490	/* all of output field names */
491	$master_fields = array(
492		'type_row',
493
494		'group_id',
495		'group_name',
496		'group_parent',
497		'disabled',
498		'custom_id',
499		'group_description',
500		'group_contact',
501		'group_other',
502
503		'agent_id',
504		'agent_name',
505		'agent_direction',
506		'agent_comentary',
507		'agent_id_group',
508		'agent_last_contant',
509		'agent_mode',
510		'agent_interval',
511		'agent_id_os',
512		'agent_os_version',
513		'agent_version',
514		'agent_last_remote_contact',
515		'agent_disabled',
516		'agent_id_parent',
517		'agent_custom_id',
518		'agent_server_name',
519		'agent_cascade_protection',
520
521		'module_id_agent_modulo',
522		'module_id_agent',
523		'module_id_module_type',
524		'module_description',
525		'module_name',
526		'module_max',
527		'module_min',
528		'module_interval',
529		'module_tcp_port',
530		'module_tcp_send',
531		'module_tcp_rcv',
532		'module_snmp_community',
533		'module_snmp_oid',
534		'module_ip_target',
535		'module_id_module_group',
536		'module_flag',
537		'module_id_module',
538		'module_disabled',
539		'module_id_export',
540		'module_plugin_user',
541		'module_plugin_pass',
542		'module_plugin_parameter',
543		'module_id_plugin',
544		'module_post_process',
545		'module_prediction_module',
546		'module_max_timeout',
547		'module_max_retries',
548		'module_custom_id',
549		'module_history_data',
550		'module_min_warning',
551		'module_max_warning',
552		'module_str_warning',
553		'module_min_critical',
554		'module_max_critical',
555		'module_str_critical',
556		'module_min_ff_event',
557		'module_delete_pending',
558		'module_id_agent_state',
559		'module_data',
560		'module_timestamp',
561		'module_state',
562		'module_last_try',
563		'module_utimestamp',
564		'module_current_interval',
565		'module_running_by',
566		'module_last_execution_try',
567		'module_status_changes',
568		'module_last_status',
569		'module_plugin_macros',
570		'module_macros',
571
572		'alert_id_agent_module',
573		'alert_id_alert_template',
574		'alert_internal_counter',
575		'alert_last_fired',
576		'alert_last_reference',
577		'alert_times_fired',
578		'alert_disabled',
579		'alert_force_execution',
580		'alert_id_alert_action',
581		'alert_type',
582		'alert_value',
583		'alert_matches_value',
584		'alert_max_value',
585		'alert_min_value',
586		'alert_time_threshold',
587		'alert_max_alerts',
588		'alert_min_alerts',
589		'alert_time_from',
590		'alert_time_to',
591		'alert_monday',
592		'alert_tuesday',
593		'alert_wednesday',
594		'alert_thursday',
595		'alert_friday',
596		'alert_saturday',
597		'alert_sunday',
598		'alert_recovery_notify',
599		'alert_field2_recovery',
600		'alert_field3_recovery',
601		'alert_id_alert_template_module',
602		'alert_fires_min',
603		'alert_fires_max',
604		'alert_id_alert_command',
605		'alert_command',
606		'alert_internal',
607		'alert_template_modules_id',
608		'alert_templates_id',
609		'alert_template_module_actions_id',
610		'alert_actions_id',
611		'alert_commands_id',
612		'alert_templates_name',
613		'alert_actions_name',
614		'alert_commands_name',
615		'alert_templates_description',
616		'alert_commands_description',
617		'alert_template_modules_priority',
618		'alert_templates_priority',
619		'alert_templates_field1',
620		'alert_actions_field1',
621		'alert_templates_field2',
622		'alert_actions_field2',
623		'alert_templates_field3',
624		'alert_actions_field3',
625		'alert_templates_id_group',
626		'alert_actions_id_group');
627
628	/* agent related field mappings (output field => column designation for 'tagente') */
629
630	global $agent_field_column_mapping;
631
632	/* module related field mappings 1/2 (output field => column for 'tagente_modulo') */
633
634	global $module_field_column_mampping;
635
636	/* module related field mappings 2/2 (output field => column for 'tagente_estado') */
637
638	global	$estado_fields_to_columns_mapping;
639
640	/* alert related field mappings (output field => column for 'talert_template_modules', ... ) */
641
642	$alert_fields_to_columns_mapping = array(
643		/*** 'alert_id_agent_module (id_agent_module) is not in this list ***/
644		'alert_template_modules_id'  => 't1.id as alert_template_modules_id',
645		'alert_id_alert_template' => 't1.id_alert_template as alert_id_alert_template',
646		'alert_internal_counter' => 't1.internal_counter as alert_internal_counter',
647		'alert_last_fired' => 't1.last_fired as alert_last_fired',
648		'alert_last_reference' => 't1.last_reference as alert_last_reference',
649		'alert_times_fired' => 't1.times_fired as alert_times_fired',
650		'alert_disabled' => 't1.disabled as alert_disabled',
651		'alert_force_execution' => 't1.force_execution as alert_force_execution',
652		'alert_template_modules_priority' => 't1.priority as alert_template_modules_priority',
653
654		'alert_templates_id'  => 't2.id as alert_templates_id',
655		'alert_type' => 't2.type as alert_type',
656		'alert_value' => 't2.value as alert_value',
657		'alert_matches_value' => 't2.matches_value as alert_matches_value',
658		'alert_max_value' => 't2.max_value as alert_max_value',
659		'alert_min_value' => 't2.min_value as alert_min_value',
660		'alert_time_threshold' => 't2.time_threshold as alert_time_threshold',
661		'alert_max_alerts' => 't2.max_alerts as alert_max_alerts',
662		'alert_min_alerts' => 't2.min_alerts as alert_min_alerts',
663		'alert_time_from' => 't2.time_from as alert_time_from',
664		'alert_time_to' => 't2.time_to as alert_time_to',
665		'alert_monday' => 't2.monday as alert_monday',
666		'alert_tuesday' => 't2.tuesday as alert_tuesday',
667		'alert_wednesday' => 't2.wednesday as alert_wednesday',
668		'alert_thursday' => 't2.thursday as alert_thursday',
669		'alert_friday' => 't2.friday as alert_friday',
670		'alert_saturday' => 't2.saturday as alert_saturday',
671		'alert_sunday' => 't2.sunday as alert_sunday',
672		'alert_templates_name' => 't2.name as alert_templates_name',
673		'alert_templates_description' => 't2.description as alert_templates_description',
674		'alert_templates_priority' => 't2.priority as alert_templates_priority',
675		'alert_templates_id_group' => 't2.id_group as alert_templates_id_group',
676		'alert_recovery_notify' => 't2.recovery_notify as alert_recovery_notify',
677		'alert_field2_recovery' => 't2.field2_recovery as alert_field2_recovery',
678		'alert_field3_recovery' => 't2.field3_recovery as alert_field3_recovery',
679		'alert_templates_field1' => 't2.field1 as alert_templates_field1',
680		'alert_templates_field2' => 't2.field2 as alert_templates_field2',
681		'alert_templates_field3' => 't2.field3 as alert_templates_field3',
682
683		'alert_template_module_actions_id' => 't3.id as alert_template_module_actions_id',
684		'alert_id_alert_action' => 't3.id_alert_action as alert_id_alert_action',
685		'alert_id_alert_template_module' => 't3.id_alert_template_module as alert_id_alert_template_module',
686		'alert_fires_min' => 't3.fires_min as alert_fires_min',
687		'alert_fires_max' => 't3.fires_max as alert_fires_max',
688
689		'alert_actions_id'  => 't4.id as alert_actions_id',
690		'alert_actions_name' => 't4.name as alert_actions_name',
691		'alert_id_alert_command' => 't4.id_alert_command as alert_id_alert_command',
692		'alert_actions_id_group' => 't4.id_group as alert_actions_id_group',
693		'alert_actions_field1' => 't4.field1 as alert_actions_field1',
694		'alert_actions_field2' => 't4.field2 as alert_actions_field2',
695		'alert_actions_field3' => 't4.field3 as alert_actions_field3',
696
697		'alert_command'  => 't5.command as alert_command',
698		'alert_internal' => 't5.internal as alert_internal',
699		'alert_commands_id'  => 't5.id as alert_commands_id',
700		'alert_commands_name'	=> 't5.name as alert_commands_name',
701		'alert_commands_description'  => 't5.description as alert_commands_description');
702
703	if ($fields == false) {
704		$fields = $master_fields;
705	}
706
707	/** construct column list to query for tagente, tagente_modulo, tagente_estado and alert-related tables **/
708	{
709		$agent_additional_columns  = "";
710		$module_additional_columns = "";
711		$estado_additional_columns = "";
712		$alert_additional_columns  = "";
713
714		foreach ($fields as $fld ) {
715			if (array_key_exists ($fld, $agent_field_column_mapping ) ) {
716				$agent_additional_columns  .= (", " . $agent_field_column_mapping[$fld] );
717			}
718			if (array_key_exists ($fld, $module_field_column_mampping ) ) {
719				$module_additional_columns .= (", " . $module_field_column_mampping[$fld]);
720			}
721			if (array_key_exists ($fld, $estado_fields_to_columns_mapping ) ) {
722				$estado_additional_columns .= (", " . $estado_fields_to_columns_mapping[$fld]);
723			}
724			if (array_key_exists ($fld, $alert_fields_to_columns_mapping ) ) {
725				$alert_additional_columns .= (", " . $alert_fields_to_columns_mapping[$fld]);
726			}
727		}
728	}
729
730	$returnVar = array();
731
732	$groups = db_get_all_rows_sql('SELECT id_grupo as group_id, ' .
733			'nombre as group_name, parent as group_parent, disabled, custom_id, ' .
734			'description as group_description, contact as group_contact, ' .
735			'other as group_other FROM tgrupo');
736	if ($groups === false) $groups = array();
737	$groups = str_replace('\n', $returnReplace, $groups);
738
739	$agents = db_get_all_rows_sql('
740		SELECT id_agente AS agent_id, id_grupo AS agent_id_group ' . $agent_additional_columns . ' FROM tagente');
741	if ($agents === false) $agents = array();
742	$agents = str_replace('\n', $returnReplace, $agents);
743
744	foreach ($groups as &$group) {
745		$group['type_row'] = 'group';
746		$returnVar[] = $group;
747
748		foreach ($agents as $index => &$agent) {
749			if ($agent['agent_id_group'] == $group['group_id']) {
750
751				$agent['type_row']  = 'agent';
752				$returnVar[] = $agent;
753
754				if ( strlen($module_additional_columns) <= 0
755					&& strlen($estado_additional_columns) <= 0
756					&& strlen($alert_additional_columns) <= 0 ) {
757					continue; /** SKIP collecting MODULES and ALERTS **/
758				}
759
760				$modules = db_get_all_rows_sql('SELECT *
761					FROM (SELECT id_agente_modulo as module_id_agent_modulo ' .  $module_additional_columns . '
762							FROM tagente_modulo
763							WHERE id_agente = ' . $agent['agent_id'] . ') t1
764						INNER JOIN (SELECT id_agente_modulo as module_id_agent_modulo ' .  $estado_additional_columns . '
765							FROM tagente_estado
766							WHERE id_agente = ' . $agent['agent_id'] . ') t2
767						ON t1.module_id_agent_modulo = t2.module_id_agent_modulo');
768
769				if ($modules === false) $modules = array();
770				$modules = str_replace('\n', $returnReplace, $modules);
771
772				foreach ($modules as &$module) {
773					$module['type_row']  = 'module';
774
775					if( $module['module_macros'] ) {
776						$module['module_macros'] = base64_decode( $module['module_macros']);
777					}
778
779					$returnVar[] = $module;
780
781					if ( strlen($alert_additional_columns) <= 0 ) {
782						continue;	/** SKIP collecting ALERTS info **/
783					}
784
785					$alerts = db_get_all_rows_sql('SELECT t1.id_agent_module as alert_id_agent_module ' .  $alert_additional_columns . '
786						FROM (SELECT * FROM talert_template_modules
787							WHERE id_agent_module = ' . $module['module_id_agent_modulo'] . ') t1
788						INNER JOIN talert_templates t2
789							ON t1.id_alert_template = t2.id
790						LEFT JOIN talert_template_module_actions t3
791							ON t1.id = t3.id_alert_template_module
792						LEFT JOIN talert_actions t4
793							ON t3.id_alert_action = t4.id
794						LEFT JOIN talert_commands t5
795							ON t4.id_alert_command = t5.id');
796
797					if ($alerts === false) $alerts = array();
798					$alerts = str_replace('\n', $returnReplace, $alerts);
799
800					foreach ($alerts as &$alert) {
801						$alert['type_row'] = 'alert';
802						$returnVar[] = $alert;
803					}
804				}
805				unset($agents[$index]);
806			}
807		}
808	}
809	$data = array('type' => 'array', 'data' => $returnVar);
810
811	$data['list_index'] = $fields;
812
813	returnData($returnType, $data, $separator);
814}
815
816/**
817 *
818 * @param $id_module
819 * @param $trahs2
820 * @param mixed $other If $other is string is only the separator,
821 *  but if it's array, $other as param is <separator>;<replace_return>;(<field_1>,<field_2>...<field_n>) in this order
822 *  and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_<separator>)
823 *  example:
824 *
825 *  return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " "
826 *  api.php?op=get&op2=module_properties&id=1116&return_type=csv&other=;| |module_id_agent,module_name,module_description,module_last_try,module_data&other_mode=url_encode_separator_|
827 *
828 * @param $returnType
829 * @return unknown_type
830 */
831function api_get_module_properties($id_module, $trahs2, $other, $returnType)
832{
833	if ($other['type'] == 'array') {
834		$separator = $other['data'][0];
835		$returnReplace = $other['data'][1];
836		if (trim($other['data'][2]) == '')
837			$fields = false;
838		else {
839			$fields = explode(',', $other['data'][2]);
840			foreach($fields as $index => $field)
841				$fields[$index] = trim($field);
842		}
843
844	}
845	else {
846		if (strlen($other['data']) == 0)
847			$separator = ';'; //by default
848		else
849			$separator = $other['data'];
850		$returnReplace = ' ';
851		$fields = false;
852	}
853	get_module_properties($id_module, $fields, $separator, $returnType, $returnReplace);
854}
855/**
856 *
857 * @param $agent_name
858 * @param $module_name
859 * @param mixed $other If $other is string is only the separator,
860 *  but if it's array, $other as param is <separator>;<replace_return>;(<field_1>,<field_2>...<field_n>) in this order
861 *  and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_<separator>)
862 *  example:
863 *
864 *  return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " "
865 *  api.php?op=get&op2=module_properties_by_name&id=sample_agent&id2=sample_module&return_type=csv&other=;| |module_id_agent,module_name,module_str_critical,module_str_warning&other_mode=url_encode_separator_|
866 *
867 * @param $returnType
868 * @return unknown_type
869 */
870function api_get_module_properties_by_name($agent_name, $module_name, $other, $returnType)
871{
872	if ($other['type'] == 'array') {
873		$separator = $other['data'][0];
874		$returnReplace = $other['data'][1];
875		if (trim($other['data'][2]) == '')
876			$fields = false;
877		else {
878			$fields = explode(',', $other['data'][2]);
879			foreach($fields as $index => $field)
880				$fields[$index] = trim($field);
881		}
882
883	}
884	else {
885		if (strlen($other['data']) == 0)
886			$separator = ';'; //by default
887		else
888			$separator = $other['data'];
889		$returnReplace = ' ';
890		$fields = false;
891	}
892
893	$agent_id = agents_get_agent_id($agent_name);
894	$tagente_modulo = modules_get_agentmodule_id ($module_name, $agent_id);
895	$module_id = $tagente_modulo['id_agente_modulo'];
896
897	if( $agent_id > 0 && $module_id > 0 ) {
898		get_module_properties($module_id, $fields, $separator, $returnType, $returnReplace);
899	}
900	else {
901		if( ! $agent_id || $agent_id < 0 ) {
902			returnError('error_get_module_properties_by_name', __('Does not exist agent with this name.'));
903		} else {
904			returnError('error_get_module_properties_by_name', __('Does not exist module with this name.'));
905		}
906	}
907}
908
909/*
910 * subroutine for api_get_module_properties() and api_get_module_properties_by_name().
911 */
912function get_module_properties($id_module, $fields, $separator, $returnType, $returnReplace)
913{
914	/** NOTE: if you want to add an output field, you have to add it to;
915	    1. $module_properties_master_fields (field name in order)
916	    2. Update field_column_mapping array (arraies are shared with get_tree_agents()).
917	       Each entry is  (DB coloum name => query fragment)
918	 **/
919
920	/* all of output field names */
921	$module_properties_master_fields = array(
922		'module_id_agent_modulo',
923		'module_id_agent',
924		'module_id_module_type',
925		'module_description',
926		'module_name',
927		'module_max',
928		'module_min',
929		'module_interval',
930		'module_tcp_port',
931		'module_tcp_send',
932		'module_tcp_rcv',
933		'module_snmp_community',
934		'module_snmp_oid',
935		'module_ip_target',
936		'module_id_module_group',
937		'module_flag',
938		'module_id_module',
939		'module_disabled',
940		'module_id_export',
941		'module_plugin_user',
942		'module_plugin_pass',
943		'module_plugin_parameter',
944		'module_id_plugin',
945		'module_post_process',
946		'module_prediction_module',
947		'module_max_timeout',
948		'module_max_retries',
949		'module_custom_id',
950		'module_history_data',
951		'module_min_warning',
952		'module_max_warning',
953		'module_str_warning',
954		'module_min_critical',
955		'module_max_critical',
956		'module_str_critical',
957		'module_min_ff_event',
958		'module_delete_pending',
959		'module_id_agent_state',
960		'module_data',
961		'module_timestamp',
962		'module_state',
963		'module_last_try',
964		'module_utimestamp',
965		'module_current_interval',
966		'module_running_by',
967		'module_last_execution_try',
968		'module_status_changes',
969		'module_last_status',
970		'module_plugin_macros',
971		'module_macros' );
972
973	/* module related field mappings 1/2 (output field => column for 'tagente_modulo') */
974
975	global $module_field_column_mampping;
976
977	/* module related field mappings 2/2 (output field => column for 'tagente_estado') */
978
979	global $estado_fields_to_columns_mapping;
980
981	if ($fields == false) {
982		$fields = $module_properties_master_fields;
983	}
984
985	/* construct column list to query for tagente, tagente_modulo, tagente_estado and alert-related tables */
986	$module_additional_columns = "";
987	$estado_additional_columns = "";
988	foreach ($fields as $fld ) {
989		if (array_key_exists ($fld, $module_field_column_mampping ) ) {
990			$module_additional_columns .= (", " . $module_field_column_mampping[$fld]);
991		}
992		if (array_key_exists ($fld, $estado_fields_to_columns_mapping ) ) {
993			$estado_additional_columns .= (", " . $estado_fields_to_columns_mapping[$fld]);
994		}
995	}
996
997	/* query to the DB */
998	$returnVar = array();
999	$modules = db_get_all_rows_sql('SELECT *
1000		FROM (SELECT id_agente_modulo as module_id_agent_modulo ' .  $module_additional_columns . '
1001				FROM tagente_modulo
1002				WHERE id_agente_modulo = ' . $id_module . ') t1
1003			INNER JOIN (SELECT id_agente_modulo as module_id_agent_modulo ' .  $estado_additional_columns . '
1004				FROM tagente_estado
1005				WHERE id_agente_modulo = ' . $id_module . ') t2
1006			ON t1.module_id_agent_modulo = t2.module_id_agent_modulo');
1007
1008	if ($modules === false) $modules = array();
1009	$modules = str_replace('\n', $returnReplace, $modules);
1010
1011	foreach ($modules as &$module) {
1012		$module['type_row']  = 'module';
1013
1014		if( $module['module_macros'] ) {
1015			$module['module_macros'] = base64_decode( $module['module_macros']);
1016		}
1017
1018		$returnVar[] = $module;
1019
1020	}
1021
1022	$data = array('type' => 'array', 'data' => $returnVar);
1023
1024	$data['list_index'] = $fields;
1025
1026	returnData($returnType, $data, $separator);
1027}
1028
1029function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) {
1030	global $config;
1031
1032	if (defined ('METACONSOLE')) {
1033		return;
1034	}
1035
1036		//html_debug_print($other);
1037	$name = $other['data'][0];
1038	$ip = $other['data'][1];
1039	$idParent = $other['data'][2];
1040	$idGroup = $other['data'][3];
1041	$cascadeProtection = $other['data'][4];
1042	$intervalSeconds = $other['data'][5];
1043	$idOS = $other['data'][6];
1044	$nameServer = $other['data'][7];
1045	$customId = $other['data'][8];
1046	$learningMode = $other['data'][9];
1047	$disabled = $other['data'][10];
1048	$description = $other['data'][11];
1049
1050	$return = db_process_sql_update('tagente',
1051		array('nombre' => $name,
1052			'direccion' => $ip,
1053			'id_grupo' => $idGroup,
1054			'intervalo' => $intervalSeconds,
1055			'comentarios' => $description,
1056			'modo' => $learningMode,
1057			'id_os' => $idOS,
1058			'disabled' => $disabled,
1059			'cascade_protection' => $cascadeProtection,
1060			'server_name' => $nameServer,
1061			'id_parent' => $idParent,
1062			'custom_id' => $customId),
1063		array('id_agente' => $id_agent));
1064
1065	returnData('string',
1066		array('type' => 'string', 'data' => (int)((bool)$return)));
1067}
1068
1069/**
1070 * Create a new agent, and print the id for new agent.
1071 *
1072 * @param $thrash1 Don't use.
1073 * @param $thrash2 Don't use.
1074 * @param array $other it's array, $other as param is <agent_name>;<ip>;<id_parent>;<id_group>;
1075 *  <cascade_protection>;<interval_sec>;<id_os>;<id_server>;<custom_id>;<learning_mode>;<disabled>;<description> in this order
1076 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1077 *  example:
1078 *
1079 *  api.php?op=set&op2=new_agent&other=pepito|1.1.1.1|0|4|0|30|8|10||0|0|nose%20nose&other_mode=url_encode_separator_|
1080 *
1081 * @param $thrash3 Don't use.
1082 */
1083function api_set_new_agent($thrash1, $thrash2, $other, $thrash3) {
1084	global $config;
1085
1086	if (defined ('METACONSOLE')) {
1087		return;
1088	}
1089
1090	$name = $other['data'][0];
1091	$ip = $other['data'][1];
1092	$idParent = $other['data'][2];
1093	$idGroup = $other['data'][3];
1094	$cascadeProtection = $other['data'][4];
1095	$intervalSeconds = $other['data'][5];
1096	$idOS = $other['data'][6];
1097	//$idServer = $other['data'][7];
1098	$nameServer = $other['data'][7];
1099	$customId = $other['data'][8];
1100	$learningMode = $other['data'][9];
1101	$disabled = $other['data'][10];
1102	$description = $other['data'][11];
1103
1104	switch ($config["dbtype"]) {
1105		case "mysql":
1106			$sql1 = 'SELECT name
1107				FROM tserver WHERE name LIKE "' . $nameServer . '"';
1108			break;
1109		case "postgresql":
1110		case "oracle":
1111			$sql1 = 'SELECT name
1112				FROM tserver WHERE name LIKE \'' . $nameServer . '\'';
1113			break;
1114	}
1115
1116	$nameServer = db_get_value_sql($sql1);
1117
1118	if (agents_get_agent_id ($name)) {
1119		returnError('agent_name_exist', 'The name of agent yet exist in DB.');
1120	}
1121	else if (($idParent != 0) &&
1122		(db_get_value_sql('SELECT id_agente
1123			FROM tagente
1124			WHERE id_agente = ' . $idParent) === false)) {
1125
1126		returnError('parent_agent_not_exist', 'The agent parent don`t exist.');
1127	}
1128	else if (db_get_value_sql('SELECT id_grupo
1129		FROM tgrupo
1130		WHERE id_grupo = ' . $idGroup) === false) {
1131
1132		returnError('id_grupo_not_exist', 'The group don`t exist.');
1133	}
1134	else if (db_get_value_sql('SELECT id_os
1135		FROM tconfig_os
1136		WHERE id_os = ' . $idOS) === false) {
1137
1138		returnError('id_os_not_exist', 'The OS don`t exist.');
1139	}
1140	else if (db_get_value_sql($sql1) === false) {
1141		returnError('server_not_exist', 'The Pandora Server don`t exist.');
1142	}
1143	else {
1144		$idAgente = db_process_sql_insert ('tagente',
1145			array ('nombre' => $name,
1146				'direccion' => $ip,
1147				'id_grupo' => $idGroup,
1148				'intervalo' => $intervalSeconds,
1149				'comentarios' => $description,
1150				'modo' => $learningMode,
1151				'id_os' => $idOS,
1152				'disabled' => $disabled,
1153				'cascade_protection' => $cascadeProtection,
1154				'server_name' => $nameServer,
1155				'id_parent' => $idParent,
1156				'custom_id' => $customId));
1157
1158		returnData('string',
1159			array('type' => 'string', 'data' => $idAgente));
1160	}
1161}
1162
1163/**
1164 *
1165 * Creates a custom field
1166 *
1167 * @param string $name Custom field name
1168 * @param boolean $display_front Flag to display custom field in agent's operation view
1169 */
1170function api_set_create_custom_field($t1, $t2, $other, $returnType) {
1171	if (defined ('METACONSOLE')) {
1172		return;
1173	}
1174
1175	if ($other['type'] == 'string') {
1176		returnError('error_parameter', 'Error in the parameters.');
1177		return;
1178	}
1179	else if ($other['type'] == 'array') {
1180
1181		$name = "";
1182
1183		if ($other['data'][0] != '') {
1184			$name = $other['data'][0];
1185		}
1186		else {
1187			returnError('error_parameter', 'Custom field name required');
1188			return;
1189		}
1190
1191		$display_front = 0;
1192
1193		if ($other['data'][1] != '') {
1194			$display_front = $other['data'][1];
1195		}
1196		else {
1197			returnError('error_parameter', 'Custom field display flag required');
1198			return;
1199		}
1200
1201		$result = db_process_sql_insert('tagent_custom_fields',
1202			array('name' => $name, 'display_on_front' => $display_front));
1203
1204		$data['type'] = "string";
1205		$data["data"] = $result;
1206
1207		returnData("string", $data);
1208	}
1209}
1210
1211/**
1212 *
1213 * Returns ID of custom field zero if not exists
1214 *
1215 * @param string $name Custom field name
1216 */
1217function api_get_custom_field_id($t1, $t2, $other, $returnType) {
1218	if (defined ('METACONSOLE')) {
1219		return;
1220	}
1221
1222	$name = $other["data"][0];
1223	$id = db_get_value ('id_field', 'tagent_custom_fields', 'name', $name);
1224
1225	$data['type'] = "string";
1226	$data["data"] = $id;
1227	returnData("string", $data);
1228}
1229
1230/**
1231 * Delete a agent with the name pass as parameter.
1232 *
1233 * @param string $id Name of agent to delete.
1234 * @param $thrash1 Don't use.
1235 * @param $thrast2 Don't use.
1236 * @param $thrash3 Don't use.
1237 */
1238function api_set_delete_agent($id, $thrash1, $thrast2, $thrash3) {
1239
1240	if (is_metaconsole()) {
1241		$servers = db_get_all_rows_sql ("SELECT *
1242			FROM tmetaconsole_setup
1243				WHERE disabled = 0");
1244
1245		if ($servers === false)
1246			$servers = array();
1247
1248
1249		foreach($servers as $server) {
1250			if (metaconsole_connect($server) == NOERR) {
1251				$idAgent[0] = agents_get_agent_id($id,true);
1252				if ($idAgent[0]) {
1253					$result = agents_delete_agent ($idAgent, true);
1254				}
1255			}
1256		}
1257	}
1258	else {
1259		$agentName = $id;
1260		$idAgent[0] = agents_get_agent_id($agentName);
1261		if ($idAgent[0])
1262			$result = agents_delete_agent ($idAgent, true);
1263		else
1264			$result = false;
1265	}
1266	if (!$result)
1267		returnError('error_delete', 'Error in delete operation.');
1268	else
1269		returnData('string', array('type' => 'string', 'data' => __('Correct Delete')));
1270}
1271
1272/**
1273 * Get all agents, and print all the result like a csv or other type for example json.
1274 *
1275 * @param $thrash1 Don't use.
1276 * @param $thrash2 Don't use.
1277 * @param array $other it's array, $other as param are the filters available <filter_so>;<filter_group>;<filter_modules_states>;<filter_name>;<filter_policy>;<csv_separator> in this order
1278 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1279 *  example for CSV:
1280 *
1281 *  api.php?op=get&op2=all_agents&return_type=csv&other=1|2|warning|j|2|~&other_mode=url_encode_separator_|
1282 *
1283 *  example for JSON:
1284 *
1285 * 	api.php?op=get&op2=all_agents&return_type=json&other=1|2|warning|j|2|~&other_mode=url_encode_separator_|
1286 *
1287 * @param $returnType.
1288 */
1289function api_get_all_agents($thrash1, $thrash2, $other, $returnType) {
1290	if (defined ('METACONSOLE')) {
1291		return;
1292	}
1293	$where = '';
1294
1295	if (isset($other['data'][0])) {
1296		// Filter by SO
1297		if ($other['data'][0] != "") {
1298			$where .= " AND tconfig_os.id_os = " . $other['data'][0];
1299		}
1300	}
1301	if (isset($other['data'][1])) {
1302		// Filter by group
1303		if ($other['data'][1] != "") {
1304			$where .= " AND id_grupo = " . $other['data'][1];
1305		}
1306	}
1307	if (isset($other['data'][3])) {
1308		// Filter by name
1309		if ($other['data'][3] != "") {
1310			$where .= " AND nombre LIKE ('%" . $other['data'][3] . "%')";
1311		}
1312	}
1313	if (isset($other['data'][4])) {
1314		// Filter by policy
1315		if ($other['data'][4] != "") {
1316			$filter_by_policy = enterprise_hook('policies_get_filter_by_agent', array($other['data'][4]));
1317			if ($filter_by_policy !== ENTERPRISE_NOT_HOOK) {
1318				$where .= $filter_by_policy;
1319			}
1320		}
1321	}
1322
1323	if (!isset($other['data'][5]))
1324		$separator = ';'; //by default
1325	else
1326		$separator = $other['data'][5];
1327
1328	// Initialization of array
1329	$result_agents = array();
1330	// Filter by state
1331	$sql = "SELECT id_agente, nombre, direccion, comentarios,
1332			tconfig_os.name, url_address
1333		FROM tagente, tconfig_os
1334		WHERE tagente.id_os = tconfig_os.id_os
1335			AND disabled = 0 " . $where;
1336
1337	$all_agents = db_get_all_rows_sql($sql);
1338
1339	// Filter by status: unknown, warning, critical, without modules
1340	if (isset($other['data'][2])) {
1341		if ($other['data'][2] != "") {
1342			foreach($all_agents as $agent) {
1343				$filter_modules['id_agente'] = $agent['id_agente'];
1344				$filter_modules['disabled'] = 0;
1345				$filter_modules['delete_pending'] = 0;
1346				$modules = db_get_all_rows_filter('tagente_modulo',
1347					$filter_modules, 'id_agente_modulo');
1348				$result_modules = array();
1349				// Skip non init modules
1350				foreach ($modules as $module) {
1351					if (modules_get_agentmodule_is_init($module['id_agente_modulo'])) {
1352						$result_modules[] = $module;
1353					}
1354				}
1355
1356				// Without modules NO_MODULES
1357				if ($other['data'][2] == 'no_modules') {
1358					if (empty($result_modules) and $other['data'][2] == 'no_modules') {
1359						$result_agents[] = $agent;
1360					}
1361				}
1362				// filter by NORMAL, WARNING, CRITICAL, UNKNOWN, ALERT_FIRED
1363				else {
1364					$status = agents_get_status($agent['id_agente'], true);
1365					// Filter by status
1366					switch ($other['data'][2]) {
1367						case 'warning':
1368							if ($status == 2) {
1369								$result_agents[] = $agent;
1370							}
1371							break;
1372						case 'critical':
1373							if ($status == 1) {
1374								$result_agents[] = $agent;
1375							}
1376							break;
1377						case 'unknown':
1378							if ($status == 3) {
1379								$result_agents[] = $agent;
1380							}
1381							break;
1382						case 'normal':
1383							if ($status == 0) {
1384								$result_agents[] = $agent;
1385							}
1386							break;
1387						case 'alert_fired':
1388							if ($status == 4) {
1389								$result_agents[] = $agent;
1390							}
1391							break;
1392					}
1393				}
1394			}
1395		}
1396		else {
1397			$result_agents = $all_agents;
1398		}
1399	}
1400	else {
1401		$result_agents = $all_agents;
1402	}
1403
1404	if (count($result_agents) > 0 and $result_agents !== false) {
1405		$data = array('type' => 'array', 'data' => $result_agents);
1406
1407		returnData($returnType, $data, $separator);
1408	}
1409	else {
1410		returnError('error_all_agents', 'No agents retrieved.');
1411	}
1412}
1413
1414/**
1415 * Get modules for an agent, and print all the result like a csv.
1416 *
1417 * @param $thrash1 Don't use.
1418 * @param $thrash2 Don't use.
1419 * @param array $other it's array, $other as param are the filters available <id_agent> in this order
1420 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1421 *  example:
1422 *
1423 *  api.php?op=get&op2=agents_modules&return_type=csv&other=14&other_mode=url_encode_separator_|
1424 *
1425 * @param $thrash3 Don't use.
1426 */
1427function api_get_agent_modules($thrash1, $thrash2, $other, $thrash3) {
1428	if (defined ('METACONSOLE')) {
1429		return;
1430	}
1431
1432	$sql = sprintf("SELECT id_agente, id_agente_modulo, nombre
1433		FROM tagente_modulo
1434		WHERE id_agente = %d AND disabled = 0
1435			AND delete_pending = 0", $other['data'][0]);
1436
1437	$all_modules = db_get_all_rows_sql($sql);
1438
1439	if (count($all_modules) > 0 and $all_modules !== false) {
1440		$data = array('type' => 'array', 'data' => $all_modules);
1441
1442		returnData('csv', $data, ';');
1443	}
1444	else {
1445		returnError('error_agent_modules', 'No modules retrieved.');
1446	}
1447}
1448
1449/**
1450 * Get modules for an agent, and print all the result like a csv.
1451 *
1452 * @param $thrash1 Don't use.
1453 * @param $thrash2 Don't use.
1454 * @param array $other it's array, $other as param are the filters available <id_agent> in this order
1455 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1456 *  example:
1457 *
1458 *  api.php?op=get&op2=group_agent&return_type=csv&other=14&other_mode=url_encode_separator_|
1459 *
1460 * @param $thrash3 Don't use.
1461 */
1462function api_get_group_agent($thrash1, $thrash2, $other, $thrash3) {
1463	if (defined ('METACONSOLE')) {
1464		return;
1465	}
1466
1467	$sql = sprintf("SELECT groups.nombre nombre
1468		FROM tagente agents, tgrupo groups
1469		WHERE id_agente = %d AND agents.disabled = 0
1470			AND groups.disabled = 0
1471			AND agents.id_grupo = groups.id_grupo", $other['data'][0]);
1472
1473	$group_names = db_get_all_rows_sql($sql);
1474
1475	if (count($group_names) > 0 and $group_names !== false) {
1476		$data = array('type' => 'array', 'data' => $group_names);
1477
1478		returnData('csv', $data, ';');
1479	}
1480	else {
1481		returnError('error_group_agent', 'No groups retrieved.');
1482	}
1483}
1484
1485/**
1486 * Get name group for an agent, and print all the result like a csv.
1487 *
1488 * @param $thrash1 Don't use.
1489 * @param $thrash2 Don't use.
1490 * @param array $other it's array, $other as param are the filters available <name_agent> in this order
1491 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1492 *  example:
1493 *
1494 *  api.php?op=get&op2=group_agent&return_type=csv&other=Pepito&other_mode=url_encode_separator_|
1495 *
1496 * @param $thrash3 Don't use.
1497 */
1498function api_get_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) {
1499
1500	$group_names =array();
1501
1502	if (is_metaconsole()) {
1503		$servers = db_get_all_rows_sql ("SELECT *
1504			FROM tmetaconsole_setup
1505				WHERE disabled = 0");
1506
1507		if ($servers === false)
1508			$servers = array();
1509
1510
1511		foreach($servers as $server) {
1512			if (metaconsole_connect($server) == NOERR) {
1513				$agent_id = agents_get_agent_id($other['data'][0],true);
1514
1515				if ($agent_id) {
1516					$sql = sprintf("SELECT groups.nombre nombre
1517						FROM tagente agents, tgrupo groups
1518						WHERE id_agente = %d
1519							AND agents.id_grupo = groups.id_grupo",$agent_id);
1520					$group_server_names = db_get_all_rows_sql($sql);
1521
1522					if ($group_server_names) {
1523						foreach($group_server_names as $group_server_name) {
1524							$group_names[] = $group_server_name;
1525						}
1526					}
1527				}
1528			}
1529			metaconsole_restore_db();
1530		}
1531	}
1532	else {
1533		$agent_id = agents_get_agent_id($other['data'][0],true);
1534
1535		$sql = sprintf("SELECT groups.nombre nombre
1536			FROM tagente agents, tgrupo groups
1537			WHERE id_agente = %d
1538				AND agents.id_grupo = groups.id_grupo",$agent_id);
1539		$group_names = db_get_all_rows_sql($sql);
1540	}
1541
1542	if (count($group_names) > 0 and $group_names !== false) {
1543		$data = array('type' => 'array', 'data' => $group_names);
1544
1545		returnData('csv', $data, ';');
1546	}
1547	else {
1548		returnError('error_group_agent', 'No groups retrieved.');
1549	}
1550}
1551
1552/**
1553 * Get id server whare agent is located, and print all the result like a csv.
1554 *
1555 * @param $id name of agent.
1556 * @param $thrash1 Don't use.
1557 * @param $thrash2 Don't use.
1558 *  example:
1559 *
1560 *  api.php?op=get&op2=locate_agent&return_type=csv&id=Pepito&other_mode=url_encode_separator_|
1561 *
1562 * @param $thrash3 Don't use.
1563 */
1564
1565function api_get_locate_agent($id, $thrash1, $thrash2, $thrash3) {
1566	if (!is_metaconsole())
1567		return;
1568
1569	$servers = db_get_all_rows_sql ("SELECT *
1570		FROM tmetaconsole_setup
1571			WHERE disabled = 0");
1572
1573	if ($servers === false)
1574		$servers = array();
1575
1576	foreach($servers as $server) {
1577		$id_server = $server['id'];
1578		if (metaconsole_connect($server) == NOERR) {
1579			$agent_id = agents_get_agent_id($id,true);
1580
1581			if ($agent_id) {
1582				$group_servers[]['server'] = $id_server;
1583			}
1584		}
1585		metaconsole_restore_db();
1586	}
1587
1588	if (count($group_servers) > 0 and $group_servers !== false) {
1589		$data = array('type' => 'array', 'data' => $group_servers);
1590
1591		returnData('csv', $data, ';');
1592	}
1593	else {
1594		returnError('error_locate_agents', 'No agents located.');
1595	}
1596}
1597
1598
1599/**
1600 * Get id group for an agent, and print all the result like a csv.
1601 *
1602 * @param $thrash1 Don't use.
1603 * @param $thrash2 Don't use.
1604 * @param array $other it's array, $other as param are the filters available <name_agent> in this order
1605 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1606 *  example:
1607 *
1608 *  api.php?op=get&op2=id_group_agent_by_name&return_type=csv&other=Pepito&other_mode=url_encode_separator_|
1609 *
1610 * @param $thrash3 Don't use.
1611 */
1612function api_get_id_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) {
1613
1614	$group_names =array();
1615
1616	if (is_metaconsole()) {
1617		$servers = db_get_all_rows_sql ("SELECT *
1618			FROM tmetaconsole_setup
1619				WHERE disabled = 0");
1620
1621		if ($servers === false)
1622			$servers = array();
1623
1624
1625		foreach($servers as $server) {
1626			if (metaconsole_connect($server) == NOERR) {
1627				$agent_id = agents_get_agent_id($other['data'][0],true);
1628
1629				if ($agent_id) {
1630					$sql = sprintf("SELECT groups.id_grupo id_group
1631						FROM tagente agents, tgrupo groups
1632						WHERE id_agente = %d
1633							AND agents.id_grupo = groups.id_grupo",$agent_id);
1634					$group_server_names = db_get_all_rows_sql($sql);
1635
1636					if ($group_server_names) {
1637						foreach($group_server_names as $group_server_name) {
1638							$group_names[] = $group_server_name;
1639						}
1640					}
1641				}
1642			}
1643			metaconsole_restore_db();
1644		}
1645	}
1646	else {
1647		$agent_id = agents_get_agent_id($other['data'][0],true);
1648
1649		$sql = sprintf("SELECT groups.id_grupo id_group
1650			FROM tagente agents, tgrupo groups
1651			WHERE id_agente = %d
1652				AND agents.id_grupo = groups.id_grupo",$agent_id);
1653		$group_names = db_get_all_rows_sql($sql);
1654	}
1655
1656	if (count($group_names) > 0 and $group_names !== false) {
1657		$data = array('type' => 'array', 'data' => $group_names);
1658
1659		returnData('csv', $data);
1660	}
1661	else {
1662		returnError('error_group_agent', 'No groups retrieved.');
1663	}
1664}
1665
1666/**
1667 * Get all policies, possible filtered by agent, and print all the result like a csv.
1668 *
1669 * @param $thrash1 Don't use.
1670 * @param $thrash2 Don't use.
1671 * @param array $other it's array, $other as param are the filters available <id_agent> in this order
1672 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1673 *  example:
1674 *
1675 *  api.php?op=get&op2=policies&return_type=csv&other=&other_mode=url_encode_separator_|
1676 *
1677 * @param $thrash3 Don't use.
1678 */
1679function api_get_policies($thrash1, $thrash2, $other, $thrash3) {
1680	if (defined ('METACONSOLE')) {
1681		return;
1682	}
1683
1684	$where = '';
1685
1686	if ($other['data'][0] != "") {
1687		$where .= ' AND pol_agents.id_agent = ' . $other['data'][0];
1688
1689		$sql = sprintf("SELECT policy.id, name, id_agent
1690			FROM tpolicies AS policy, tpolicy_agents AS pol_agents
1691			WHERE policy.id = pol_agents.id_policy %s", $where);
1692	}
1693	else {
1694		$sql = "SELECT id, name FROM tpolicies AS policy";
1695	}
1696
1697	$policies = db_get_all_rows_sql($sql);
1698
1699	if (count($policies) > 0 and $policies !== false) {
1700		$data = array('type' => 'array', 'data' => $policies);
1701
1702		returnData('csv', $data, ';');
1703	}
1704	else {
1705		returnError('error_get_policies', 'No policies retrieved.');
1706	}
1707}
1708
1709/**
1710 * Get policy modules, possible filtered by agent, and print all the result like a csv.
1711 *
1712 * @param $thrash1 Don't use.
1713 * @param $thrash2 Don't use.
1714 * @param array $other it's array, $other as param are the filters available <id_agent> in this order
1715 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1716 *  example:
1717 *
1718 *  api.php?op=get&op2=policy_modules&return_type=csv&other=2&other_mode=url_encode_separator_|
1719 *
1720 * @param $thrash3 Don't use.
1721 */
1722function api_get_policy_modules($thrash1, $thrash2, $other, $thrash3) {
1723	if (defined ('METACONSOLE')) {
1724		return;
1725	}
1726
1727	$where = '';
1728
1729	if ($other['data'][0] == "") {
1730		returnError('error_policy_modules', 'Error retrieving policy modules. Id_policy cannot be left blank.');
1731		return;
1732	}
1733
1734	$policies = enterprise_hook('policies_get_modules_api',
1735		array($other['data'][0], $other['data'][1]));
1736
1737	if ($policies === ENTERPRISE_NOT_HOOK) {
1738		returnError('error_policy_modules', 'Error retrieving policy modules.');
1739		return;
1740	}
1741
1742	if (count($policies) > 0 and $policies !== false) {
1743		$data = array('type' => 'array', 'data' => $policies);
1744
1745		returnData('csv', $data, ';');
1746	}
1747	else {
1748		returnError('error_policy_modules', 'No policy modules retrieved.');
1749	}
1750}
1751
1752
1753/**
1754 * Create a network module in agent. And return the id_agent_module of new module.
1755 *
1756 * @param string $id Name of agent to add the module.
1757 * @param $thrash1 Don't use.
1758 * @param array $other it's array, $other as param is <name_module>;<disabled>;<id_module_type>;
1759 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
1760 *  <history_data>;<ip_target>;<module_port>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
1761 *  <min>;<max>;<custom_id>;<description>;<disabled_types_event>;<module_macros>;
1762 *  <each_ff>;<ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critical>; in this order
1763 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1764 *  example:
1765 *
1766 *  api.php?op=set&op2=create_network_module&id=pepito&other=prueba|0|7|1|10|15|0|16|18|0|15|0|www.google.es|0||0|180|0|0|0|0|latency%20ping&other_mode=url_encode_separator_|
1767 *
1768 *
1769 * @param $thrash3 Don't use
1770 */
1771function api_set_create_network_module($id, $thrash1, $other, $thrash3) {
1772	if (defined ('METACONSOLE')) {
1773		return;
1774	}
1775
1776	$agentName = $id;
1777
1778	$idAgent = agents_get_agent_id($agentName);
1779
1780	if (!$idAgent) {
1781		returnError('error_create_network_module',
1782			__('Error in creation network module. Agent name doesn\'t exists.'));
1783		return;
1784	}
1785
1786	if ($other['data'][2] < 6 or $other['data'][2] > 18) {
1787		returnError('error_create_network_module',
1788			__('Error in creation network module. Id_module_type is not correct for network modules.'));
1789		return;
1790	}
1791
1792	$name = $other['data'][0];
1793
1794	$disabled_types_event = array();
1795	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][22];
1796	$disabled_types_event = json_encode($disabled_types_event);
1797
1798	$values = array(
1799		'id_agente' => $idAgent,
1800		'disabled' => $other['data'][1],
1801		'id_tipo_modulo' => $other['data'][2],
1802		'id_module_group' => $other['data'][3],
1803		'min_warning' => $other['data'][4],
1804		'max_warning' => $other['data'][5],
1805		'str_warning' => $other['data'][6],
1806		'min_critical' => $other['data'][7],
1807		'max_critical' => $other['data'][8],
1808		'str_critical' => $other['data'][9],
1809		'min_ff_event' => $other['data'][10],
1810		'history_data' => $other['data'][11],
1811		'ip_target' => $other['data'][12],
1812		'tcp_port' => $other['data'][13],
1813		'snmp_community' => $other['data'][14],
1814		'snmp_oid' => $other['data'][15],
1815		'module_interval' => $other['data'][16],
1816		'post_process' => $other['data'][17],
1817		'min' => $other['data'][18],
1818		'max' => $other['data'][19],
1819		'custom_id' => $other['data'][20],
1820		'descripcion' => $other['data'][21],
1821		'id_modulo' => 2,
1822		'disabled_types_event' => $disabled_types_event,
1823		'module_macros' => $other['data'][23],
1824		'each_ff' => $other['data'][24],
1825		'min_ff_event_normal' => $other['data'][25],
1826		'min_ff_event_warning' => $other['data'][26],
1827		'min_ff_event_critical' => $other['data'][27],
1828		'critical_inverse' => $other['data'][28],
1829		'warning_inverse' => $other['data'][29]
1830	);
1831
1832	if ( ! $values['descripcion'] ) {
1833		$values['descripcion'] = '';	// Column 'descripcion' cannot be null
1834	}
1835	if ( ! $values['module_macros'] ) {
1836		$values['module_macros'] = '';	// Column 'module_macros' cannot be null
1837	}
1838
1839	$idModule = modules_create_agent_module($idAgent, $name, $values, true);
1840
1841	if (is_error($idModule)) {
1842		// TODO: Improve the error returning more info
1843		returnError('error_create_network_module', __('Error in creation network module.'));
1844	}
1845	else {
1846		returnData('string', array('type' => 'string', 'data' => $idModule));
1847	}
1848}
1849
1850/**
1851 * Update a network module in agent. And return a message with the result of the operation.
1852 *
1853 * @param string $id Id of the network module to update.
1854 * @param $thrash1 Don't use.
1855 * @param array $other it's array, $other as param is <id_agent>;<disabled>
1856 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
1857 *  <history_data>;<ip_target>;<module_port>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
1858 *  <min>;<max>;<custom_id>;<description>;<disabled_types_event>;<module_macros>;
1859 *  <each_ff>;<ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critidcal>; in this order
1860 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1861 *  example:
1862 *
1863 *  api.php?op=set&op2=update_network_module&id=271&other=156|0|2|10|15||16|18||7|0|127.0.0.1|0||0|300|30.00|0|0|0|latency%20ping%20modified%20by%20the%20Api&other_mode=url_encode_separator_|
1864 *
1865 *
1866 * @param $thrash3 Don't use
1867 */
1868function api_set_update_network_module($id_module, $thrash1, $other, $thrash3) {
1869	if (defined ('METACONSOLE')) {
1870		return;
1871	}
1872
1873
1874	if ($id_module == "") {
1875		returnError('error_update_network_module',
1876			__('Error updating network module. Module name cannot be left blank.'));
1877		return;
1878	}
1879
1880	$check_id_module = db_get_value ('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module);
1881
1882	if (!$check_id_module) {
1883		returnError('error_update_network_module',
1884			__('Error updating network module. Id_module doesn\'t exists.'));
1885		return;
1886	}
1887
1888	// If we want to change the module to a new agent
1889	if ($other['data'][0] != "") {
1890		$id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module);
1891
1892		if ($id_agent_old != $other['data'][0]) {
1893			$id_module_exists = db_get_value_filter ('id_agente_modulo',
1894				'tagente_modulo',
1895				array('nombre' => $module_name, 'id_agente' => $other['data'][0]));
1896
1897			if ($id_module_exists) {
1898				returnError('error_update_network_module',
1899					__('Error updating network module. Id_module exists in the new agent.'));
1900				return;
1901			}
1902		}
1903		// Check if agent exists
1904		$check_id_agent = db_get_value ('id_agente', 'tagente', 'id_agente', $other['data'][0]);
1905		if (!$check_id_agent) {
1906			returnError('error_update_data_module', __('Error updating network module. Id_agent doesn\'t exists.'));
1907			return;
1908		}
1909	}
1910
1911	$network_module_fields = array('id_agente',
1912		'disabled',
1913		'id_module_group',
1914		'min_warning',
1915		'max_warning',
1916		'str_warning',
1917		'min_critical',
1918		'max_critical',
1919		'str_critical',
1920		'min_ff_event',
1921		'history_data',
1922		'ip_target',
1923		'tcp_port',
1924		'snmp_community',
1925		'snmp_oid',
1926		'module_interval',
1927		'post_process',
1928		'min',
1929		'max',
1930		'custom_id',
1931		'descripcion',
1932		'disabled_types_event',
1933		'module_macros',
1934		'each_ff',
1935		'min_ff_event_normal',
1936		'min_ff_event_warning',
1937		'min_ff_event_critical',
1938		'critical_inverse',
1939		'warning_inverse');
1940
1941	$values = array();
1942	$cont = 0;
1943	foreach ($network_module_fields as $field) {
1944		if ($other['data'][$cont] != "") {
1945			$values[$field] = $other['data'][$cont];
1946		}
1947
1948		$cont++;
1949	}
1950
1951	$result_update = modules_update_agent_module($id_module, $values);
1952
1953	if ($result_update < 0)
1954		returnError('error_update_network_module', 'Error updating network module.');
1955	else
1956		returnData('string', array('type' => 'string', 'data' => __('Network module updated.')));
1957}
1958
1959/**
1960 * Create a plugin module in agent. And return the id_agent_module of new module.
1961 *
1962 * @param string $id Name of agent to add the module.
1963 * @param $thrash1 Don't use.
1964 * @param array $other it's array, $other as param is <name_module>;<disabled>;<id_module_type>;
1965 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
1966 *  <history_data>;<ip_target>;<tcp_port>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
1967 *  <min>;<max>;<custom_id>;<description>;<id_plugin>;<plugin_user>;<plugin_pass>;<plugin_parameter>;
1968 *  <disabled_types_event>;<macros>;<module_macros>;<each_ff>;<ff_threshold_normal>;
1969 *  <ff_threshold_warning>;<ff_threshold_critical> in this order
1970 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
1971 *  example:
1972 *
1973 *  api.php?op=set&op2=create_plugin_module&id=pepito&other=prueba|0|1|2|0|0||0|0||0|0|127.0.0.1|0||0|300|0|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_|
1974 *
1975 * @param $thrash3 Don't use
1976 */
1977function api_set_create_plugin_module($id, $thrash1, $other, $thrash3) {
1978	if (defined ('METACONSOLE')) {
1979		return;
1980	}
1981
1982	$agentName = $id;
1983
1984	if ($other['data'][22] == "") {
1985		returnError('error_create_plugin_module', __('Error in creation plugin module. Id_plugin cannot be left blank.'));
1986		return;
1987	}
1988
1989	$idAgent = agents_get_agent_id($agentName);
1990
1991	if (!$idAgent) {
1992		returnError('error_create_plugin_module', __('Error in creation plugin module. Agent name doesn\'t exists.'));
1993		return;
1994	}
1995
1996	$disabled_types_event = array();
1997	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][26];
1998	$disabled_types_event = json_encode($disabled_types_event);
1999
2000	$name = $other['data'][0];
2001
2002	$values = array(
2003		'id_agente' => $idAgent,
2004		'disabled' => $other['data'][1],
2005		'id_tipo_modulo' => $other['data'][2],
2006		'id_module_group' => $other['data'][3],
2007		'min_warning' => $other['data'][4],
2008		'max_warning' => $other['data'][5],
2009		'str_warning' => $other['data'][6],
2010		'min_critical' => $other['data'][7],
2011		'max_critical' => $other['data'][8],
2012		'str_critical' => $other['data'][9],
2013		'min_ff_event' => $other['data'][10],
2014		'history_data' => $other['data'][11],
2015		'ip_target' => $other['data'][12],
2016		'tcp_port' => $other['data'][13],
2017		'snmp_community' => $other['data'][14],
2018		'snmp_oid' => $other['data'][15],
2019		'module_interval' => $other['data'][16],
2020		'post_process' => $other['data'][17],
2021		'min' => $other['data'][18],
2022		'max' => $other['data'][19],
2023		'custom_id' => $other['data'][20],
2024		'descripcion' => $other['data'][21],
2025		'id_modulo' => 4,
2026		'id_plugin' => $other['data'][22],
2027		'plugin_user' => $other['data'][23],
2028		'plugin_pass' => $other['data'][24],
2029		'plugin_parameter' => $other['data'][25],
2030		'disabled_types_event' => $disabled_types_event,
2031		'macros' => base64_decode ($other['data'][27]),
2032		'module_macros' => $other['data'][28],
2033		'each_ff' => $other['data'][29],
2034		'min_ff_event_normal' => $other['data'][30],
2035		'min_ff_event_warning' => $other['data'][31],
2036		'min_ff_event_critical' => $other['data'][32],
2037		'critical_inverse' => $other['data'][33],
2038		'warning_inverse' => $other['data'][34]
2039	);
2040
2041	if ( ! $values['descripcion'] ) {
2042		$values['descripcion'] = '';	// Column 'descripcion' cannot be null
2043	}
2044	if ( ! $values['module_macros'] ) {
2045		$values['module_macros'] = '';	// Column 'module_macros' cannot be null
2046	}
2047
2048	$idModule = modules_create_agent_module($idAgent, $name, $values, true);
2049
2050	if (is_error($idModule)) {
2051		// TODO: Improve the error returning more info
2052		returnError('error_create_plugin_module', __('Error in creation plugin module.'));
2053	}
2054	else {
2055		returnData('string', array('type' => 'string', 'data' => $idModule));
2056	}
2057}
2058
2059/**
2060 * Update a plugin module in agent. And return the id_agent_module of new module.
2061 * @param string $id Id of the plugin module to update.
2062 * @param $thrash1 Don't use.
2063 * @param array $other it's array, $other as param is <id_agent>;<disabled>;
2064 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
2065 *  <history_data>;<ip_target>;<module_port>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
2066 *  <min>;<max>;<custom_id>;<description>;<id_plugin>;<plugin_user>;<plugin_pass>;<plugin_parameter>;
2067 *  <disabled_types_event>;<macros>;<module_macros>;<each_ff>;<ff_threshold_normal>;
2068 *  <ff_threshold_warning>;<ff_threshold_critical> in this order
2069 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
2070 *  example:
2071 *
2072 *  api.php?op=set&op2=update_plugin_module&id=293&other=156|0|2|0|0||0|0||0|0|127.0.0.1|0||0|300|0|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_|
2073 *
2074 *
2075 * @param $thrash3 Don't use
2076 */
2077function api_set_update_plugin_module($id_module, $thrash1, $other, $thrash3) {
2078	if (defined ('METACONSOLE')) {
2079		return;
2080	}
2081
2082	if ($id_module == "") {
2083		returnError('error_update_plugin_module', __('Error updating plugin module. Id_module cannot be left blank.'));
2084		return;
2085	}
2086
2087	$check_id_module = db_get_value ('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module);
2088
2089	if (!$check_id_module) {
2090		returnError('error_update_plugin_module', __('Error updating plugin module. Id_module doesn\'t exists.'));
2091		return;
2092	}
2093
2094	// If we want to change the module to a new agent
2095	if ($other['data'][0] != "") {
2096		$id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module);
2097
2098		if ($id_agent_old != $other['data'][0]) {
2099			$id_module_exists = db_get_value_filter ('id_agente_modulo', 'tagente_modulo', array('nombre' => $module_name, 'id_agente' => $other['data'][0]));
2100
2101			if ($id_module_exists) {
2102				returnError('error_update_plugin_module', __('Error updating plugin module. Id_module exists in the new agent.'));
2103				return;
2104			}
2105		}
2106		// Check if agent exists
2107		$check_id_agent = db_get_value ('id_agente', 'tagente', 'id_agente', $other['data'][0]);
2108		if (!$check_id_agent) {
2109			returnError('error_update_data_module', __('Error updating plugin module. Id_agent doesn\'t exists.'));
2110			return;
2111		}
2112	}
2113
2114	$plugin_module_fields = array('id_agente',
2115		'disabled',
2116		'id_module_group',
2117		'min_warning',
2118		'max_warning',
2119		'str_warning',
2120		'min_critical',
2121		'max_critical',
2122		'str_critical',
2123		'min_ff_event',
2124		'history_data',
2125		'ip_target',
2126		'tcp_port',
2127		'snmp_community',
2128		'snmp_oid',
2129		'module_interval',
2130		'post_process',
2131		'min',
2132		'max',
2133		'custom_id',
2134		'descripcion',
2135		'id_plugin',
2136		'plugin_user',
2137		'plugin_pass',
2138		'plugin_parameter',
2139		'disabled_types_event',
2140		'macros',
2141		'module_macros',
2142		'each_ff',
2143		'min_ff_event_normal',
2144		'min_ff_event_warning',
2145		'min_ff_event_critical',
2146		'critical_inverse',
2147		'warning_inverse');
2148
2149	$values = array();
2150	$cont = 0;
2151	foreach ($plugin_module_fields as $field) {
2152		if ($other['data'][$cont] != "") {
2153			$values[$field] = $other['data'][$cont];
2154
2155			if( $field === 'macros' ) {
2156				$values[$field] = base64_decode($values[$field]);
2157			}
2158		}
2159
2160		$cont++;
2161	}
2162
2163	$result_update = modules_update_agent_module($id_module, $values);
2164
2165	if ($result_update < 0)
2166		returnError('error_update_plugin_module', 'Error updating plugin module.');
2167	else
2168		returnData('string', array('type' => 'string', 'data' => __('Plugin module updated.')));
2169}
2170
2171/**
2172 * Create a data module in agent. And return the id_agent_module of new module.
2173 * Note: Only adds database information, this function doesn't alter config file information.
2174 *
2175 * @param string $id Name of agent to add the module.
2176 * @param $thrash1 Don't use.
2177 * @param array $other it's array, $other as param is <name_module>;<disabled>;<id_module_type>;
2178 * 	<description>;<id_module_group>;<min_value>;<max_value>;<post_process>;<module_interval>;<min_warning>;
2179 * 	<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<history_data>;
2180 * 	<disabled_types_event>;<module_macros>;<ff_threshold>;<each_ff>;
2181 *	<ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critical>; in this order
2182 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
2183 *  example:
2184 *
2185 *  api.php?op=set&op2=create_data_module&id=pepito&other=prueba|0|1|data%20module%20from%20api|1|10|20|10.50|180|10|15||16|20||0&other_mode=url_encode_separator_|
2186 *
2187 * @param $thrash3 Don't use
2188 */
2189function api_set_create_data_module($id, $thrash1, $other, $thrash3) {
2190	if (defined ('METACONSOLE')) {
2191		return;
2192	}
2193
2194	$agentName = $id;
2195
2196	if ($other['data'][0] == "") {
2197		returnError('error_create_data_module', __('Error in creation data module. Module_name cannot be left blank.'));
2198		return;
2199	}
2200
2201	$idAgent = agents_get_agent_id($agentName);
2202
2203	if (!$idAgent) {
2204		returnError('error_create_data_module', __('Error in creation data module. Agent name doesn\'t exists.'));
2205		return;
2206	}
2207
2208	$name = $other['data'][0];
2209
2210	$disabled_types_event = array();
2211	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][16];
2212	$disabled_types_event = json_encode($disabled_types_event);
2213
2214	$values = array(
2215		'id_agente' => $idAgent,
2216		'disabled' => $other['data'][1],
2217		'id_tipo_modulo' => $other['data'][2],
2218		'descripcion' => $other['data'][3],
2219		'id_module_group' => $other['data'][4],
2220		'min' => $other['data'][5],
2221		'max' => $other['data'][6],
2222		'post_process' => $other['data'][7],
2223		'module_interval' => $other['data'][8],
2224		'min_warning' => $other['data'][9],
2225		'max_warning' => $other['data'][10],
2226		'str_warning' => $other['data'][11],
2227		'min_critical' => $other['data'][12],
2228		'max_critical' => $other['data'][13],
2229		'str_critical' => $other['data'][14],
2230		'history_data' => $other['data'][15],
2231		'id_modulo' => 1,
2232		'disabled_types_event' => $disabled_types_event,
2233		'module_macros' => $other['data'][17],
2234		'min_ff_event' => $other['data'][18],
2235		'each_ff' => $other['data'][19],
2236		'min_ff_event_normal' => $other['data'][20],
2237		'min_ff_event_warning' => $other['data'][21],
2238		'min_ff_event_critical' => $other['data'][22],
2239		'ff_timeout' => $other['data'][23],
2240		'critical_inverse' => $other['data'][24],
2241		'warning_inverse' => $other['data'][25]
2242	);
2243
2244	if ( ! $values['descripcion'] ) {
2245		$values['descripcion'] = '';	// Column 'descripcion' cannot be null
2246	}
2247	if ( ! $values['module_macros'] ) {
2248		$values['module_macros'] = '';	// Column 'module_macros' cannot be null
2249	}
2250
2251	$idModule = modules_create_agent_module($idAgent, $name, $values, true);
2252
2253	if (is_error($idModule)) {
2254		// TODO: Improve the error returning more info
2255		returnError('error_create_data_module', __('Error in creation data module.'));
2256	}
2257	else {
2258		returnData('string', array('type' => 'string', 'data' => $idModule));
2259	}
2260}
2261
2262
2263/**
2264 * Create a synthetic module in agent. And return the id_agent_module of new module.
2265 * Note: Only adds database information, this function doesn't alter config file information.
2266 *
2267 * @param string $id Name of agent to add the module.
2268 * @param $thrash1 Don't use.
2269 * @param array $other it's array, $other as param is <name_module><synthetic_type><AgentName;Operation;NameModule> OR <AgentName;NameModule> OR <Operation;Value>in this order
2270 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
2271 *  example:
2272 *
2273 *  api.php?op=set&op2=create_synthetic_module&id=pepito&other=prueba|average|Agent%20Name;AVG;Name%20Module|Agent%20Name2;AVG;Name%20Module2&other_mode=url_encode_separator_|
2274 *
2275 * @param $thrash3 Don't use
2276 */
2277function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) {
2278	if (defined ('METACONSOLE')) {
2279		return;
2280	}
2281
2282	global $config;
2283
2284	$agentName = $id;
2285
2286	io_safe_input_array($other);
2287
2288	if ($other['data'][0] == "") {
2289		returnError('error_create_data_module', __('Error in creation synthetic module. Module_name cannot be left blank.'));
2290		return;
2291	}
2292
2293	$idAgent = agents_get_agent_id(io_safe_output($agentName),true);
2294
2295	if (!$idAgent) {
2296		returnError('error_create_data_module', __('Error in creation synthetic module. Agent name doesn\'t exists.'));
2297		return;
2298	}
2299
2300	$name = io_safe_output($other['data'][0]);
2301	$name = io_safe_input($name);
2302	$id_tipo_modulo = db_get_row_sql ("SELECT id_tipo FROM ttipo_modulo WHERE nombre = 'generic_data'");
2303
2304	$values = array(
2305		'id_agente' => $idAgent,
2306		'id_modulo' => 5,
2307		'custom_integer_1' => 0,
2308		'custom_integer_2' => 0,
2309		'prediction_module' => 3,
2310		'id_tipo_modulo' => $id_tipo_modulo['id_tipo']
2311	);
2312
2313	if ( ! $values['descripcion'] ) {
2314		$values['descripcion'] = '';	// Column 'descripcion' cannot be null
2315	}
2316
2317	$idModule = modules_create_agent_module($idAgent, $name, $values, true);
2318
2319	if (is_error($idModule)) {
2320		// TODO: Improve the error returning more info
2321		returnError('error_create_data_module', __('Error in creation data module.'));
2322	}
2323	else {
2324		$synthetic_type = $other['data'][1];
2325		unset($other['data'][0]);
2326		unset($other['data'][1]);
2327
2328
2329		$filterdata = array();
2330		foreach ($other['data'] as $data) {
2331			$data = str_replace(array('ADD','SUB','MUL','DIV'),array('+','-','*','/'),$data);
2332			$split_data = explode(';',$data);
2333
2334			if ( preg_match("/[x\/+*-]/",$split_data[0]) && strlen($split_data[0]) == 1 ) {
2335				if ( preg_match("/[\/|+|*|-]/",$split_data[0]) && $synthetic_type === 'average' ) {
2336					returnError("","[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n");
2337				}
2338
2339				$operator = strtolower($split_data[0]);
2340				$data_module = array("",$operator,$split_data[1]);
2341
2342				$text_data = implode('_',$data_module);
2343				array_push($filterdata,$text_data);
2344			}
2345			else {
2346				if (count($split_data) == 2) {
2347					$idAgent = agents_get_agent_id(io_safe_output($split_data[0]),true);
2348					$data_module = array($idAgent,'',$split_data[1]);
2349					$text_data = implode('_',$data_module);
2350					array_push($filterdata,$text_data);
2351				}
2352				else {
2353					if (strlen($split_data[1]) > 1 && $synthetic_type != 'average' ) {
2354						returnError("","[ERROR] You can only use +, -, *, / or x, and you use this: @split_data[1] \n\n");
2355						return;
2356					}
2357					if ( preg_match("/[\/|+|*|-]/",$split_data[1]) && $synthetic_type === 'average' ) {
2358						returnError("","[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n");
2359						return;
2360					}
2361
2362					$idAgent = agents_get_agent_id(io_safe_output($split_data[0]),true);
2363					$operator = strtolower($split_data[1]);
2364					$data_module = array($idAgent,$operator,$split_data[2]);
2365					$text_data = implode('_',$data_module);
2366					array_push($filterdata,$text_data);
2367				}
2368			}
2369		}
2370
2371		$serialize_ops = implode(',',$filterdata);
2372
2373		//modules_create_synthetic_operations
2374		$synthetic = enterprise_hook('modules_create_synthetic_operations',
2375			array($idModule, $serialize_ops));
2376
2377		if ($synthetic === ENTERPRISE_NOT_HOOK) {
2378			returnError('error_synthetic_modules', 'Error Synthetic modules.');
2379			db_process_sql_delete ('tagente_modulo',
2380				array ('id_agente_modulo' => $idModule));
2381			return;
2382		}
2383		else {
2384			$status = AGENT_MODULE_STATUS_NO_DATA;
2385			switch ($config["dbtype"]) {
2386				case "mysql":
2387					$result = db_process_sql_insert ('tagente_estado',
2388						array ('id_agente_modulo' => $idModule,
2389							'datos' => 0,
2390							'timestamp' => '01-01-1970 00:00:00',
2391							'estado' => $status,
2392							'id_agente' => (int) $idAgent,
2393							'utimestamp' => 0,
2394							'status_changes' => 0,
2395							'last_status' => $status,
2396							'last_known_status' => $status
2397						));
2398					break;
2399				case "postgresql":
2400					$result = db_process_sql_insert ('tagente_estado',
2401						array ('id_agente_modulo' => $idModule,
2402							'datos' => 0,
2403							'timestamp' => null,
2404							'estado' => $status,
2405							'id_agente' => (int) $idAgent,
2406							'utimestamp' => 0,
2407							'status_changes' => 0,
2408							'last_status' => $status,
2409							'last_known_status' => $status
2410						));
2411					break;
2412				case "oracle":
2413					$result = db_process_sql_insert ('tagente_estado',
2414						array ('id_agente_modulo' => $idModule,
2415							'datos' => 0,
2416							'timestamp' => '#to_date(\'1970-01-01 00:00:00\', \'YYYY-MM-DD HH24:MI:SS\')',
2417							'estado' => $status,
2418							'id_agente' => (int) $idAgent,
2419							'utimestamp' => 0,
2420							'status_changes' => 0,
2421							'last_status' => $status,
2422							'last_known_status' => $status
2423						));
2424					break;
2425			}
2426			if ($result === false) {
2427				db_process_sql_delete ('tagente_modulo',
2428					array ('id_agente_modulo' => $idModule));
2429				returnError('error_synthetic_modules', 'Error Synthetic modules.');
2430			}
2431			else {
2432				db_process_sql ('UPDATE tagente SET total_count=total_count+1, notinit_count=notinit_count+1 WHERE id_agente=' . (int)$idAgent);
2433				returnData('string', array('type' => 'string', 'data' => __('Synthetic module created ID: ' . $idModule)));
2434			}
2435		}
2436	}
2437}
2438
2439/**
2440 * Update a data module in agent. And return a message with the result of the operation.
2441 *
2442 * @param string $id Id of the data module to update.
2443 * @param $thrash1 Don't use.
2444 * @param array $other it's array, $other as param is <id_agent>;<disabled>;<description>;
2445 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
2446 *  <history_data>;<ip_target>;<module_port>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
2447 *  <min>;<max>;<custom_id>;<disabled_types_event>;<module_macros>;<ff_threshold>;
2448 *  <each_ff>;<ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critical>;
2449 *  <ff_timeout> in this order
2450 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
2451 *  example:
2452 *
2453 *  api.php?op=set&op2=update_data_module&id=170&other=44|0|data%20module%20modified%20from%20API|6|0|0|50.00|300|10|15||16|18||0&other_mode=url_encode_separator_|
2454 *
2455 *
2456 * @param $thrash3 Don't use
2457 */
2458function api_set_update_data_module($id_module, $thrash1, $other, $thrash3) {
2459	if (defined ('METACONSOLE')) {
2460		return;
2461	}
2462
2463	if ($id_module == "") {
2464		returnError('error_update_data_module', __('Error updating data module. Id_module cannot be left blank.'));
2465		return;
2466	}
2467
2468	$check_id_module = db_get_value ('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module);
2469
2470	if (!$check_id_module) {
2471		returnError('error_update_data_module', __('Error updating data module. Id_module doesn\'t exists.'));
2472		return;
2473	}
2474
2475	// If we want to change the module to a new agent
2476	if ($other['data'][0] != "") {
2477		$id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module);
2478
2479		if ($id_agent_old != $other['data'][0]) {
2480			$id_module_exists = db_get_value_filter ('id_agente_modulo', 'tagente_modulo', array('nombre' => $module_name, 'id_agente' => $other['data'][0]));
2481
2482			if ($id_module_exists) {
2483				returnError('error_update_data_module', __('Error updating data module. Id_module exists in the new agent.'));
2484				return;
2485			}
2486		}
2487		// Check if agent exists
2488		$check_id_agent = db_get_value ('id_agente', 'tagente', 'id_agente', $other['data'][0]);
2489		if (!$check_id_agent) {
2490			returnError('error_update_data_module', __('Error updating data module. Id_agent doesn\'t exists.'));
2491			return;
2492		}
2493	}
2494
2495	$data_module_fields = array('id_agente',
2496		'disabled',
2497		'descripcion',
2498		'id_module_group',
2499		'min',
2500		'max',
2501		'post_process',
2502		'module_interval',
2503		'min_warning',
2504		'max_warning',
2505		'str_warning',
2506		'min_critical',
2507		'max_critical',
2508		'str_critical',
2509		'history_data',
2510		'disabled_types_event',
2511		'module_macros',
2512		'min_ff_event',
2513		'each_ff',
2514		'min_ff_event_normal',
2515		'min_ff_event_warning',
2516		'min_ff_event_critical',
2517		'ff_timeout',
2518		'critical_inverse',
2519		'warning_inverse');
2520
2521	$values = array();
2522	$cont = 0;
2523	foreach ($data_module_fields as $field) {
2524		if ($other['data'][$cont] != "") {
2525			$values[$field] = $other['data'][$cont];
2526		}
2527
2528		$cont++;
2529	}
2530
2531	$result_update = modules_update_agent_module($id_module, $values);
2532
2533	if ($result_update < 0)
2534		returnError('error_update_data_module', 'Error updating data module.');
2535	else
2536		returnData('string', array('type' => 'string', 'data' => __('Data module updated.')));
2537}
2538
2539
2540/**
2541 * Create a SNMP module in agent. And return the id_agent_module of new module.
2542 *
2543 * @param string $id Name of agent to add the module.
2544 * @param $thrash1 Don't use.
2545 * @param array $other it's array, $other as param is <name_module>;<disabled>;<id_module_type>;
2546 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
2547 *  <history_data>;<ip_target>;<module_port>;<snmp_version>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
2548 *  <min>;<max>;<custom_id>;<description>;<snmp3_priv_method>;<snmp3_priv_pass>;<snmp3_sec_level>;<snmp3_auth_method>;
2549 *  <snmp3_auth_user>;<snmp3_auth_pass>;<disabled_types_event>;<each_ff>;<ff_threshold_normal>;
2550 *  <ff_threshold_warning>;<ff_threshold_critical> in this order
2551 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
2552 *  example:
2553 *
2554 * 	example 1 (snmp v: 3, snmp3_priv_method: AES, passw|authNoPriv|MD5|pepito_user|example_priv_passw)
2555 *
2556 *  api.php?op=set&op2=create_snmp_module&id=pepito&other=prueba|0|15|1|10|15||16|18||15|0|127.0.0.1|60|3|public|.1.3.6.1.2.1.1.1.0|180|0|0|0|0|SNMP%20module%20from%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_|
2557 *
2558 *  example 2 (snmp v: 1)
2559 *
2560 *  api.php?op=set&op2=create_snmp_module&id=pepito1&other=prueba2|0|15|1|10|15||16|18||15|0|127.0.0.1|60|1|public|.1.3.6.1.2.1.1.1.0|180|0|0|0|0|SNMP module from API&other_mode=url_encode_separator_|
2561 *
2562 * @param $thrash3 Don't use
2563 */
2564function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) {
2565
2566	if (defined ('METACONSOLE')) {
2567		return;
2568	}
2569
2570	$agentName = $id;
2571
2572	if ($other['data'][0] == "") {
2573		returnError('error_create_snmp_module', __('Error in creation SNMP module. Module_name cannot be left blank.'));
2574		return;
2575	}
2576
2577	if ($other['data'][2] < 15 or $other['data'][3] > 17) {
2578		returnError('error_create_snmp_module', __('Error in creation SNMP module. Invalid id_module_type for a SNMP module.'));
2579		return;
2580	}
2581
2582	$idAgent = agents_get_agent_id($agentName);
2583
2584	if (!$idAgent) {
2585		returnError('error_create_snmp_module', __('Error in creation SNMP module. Agent name doesn\'t exists.'));
2586		return;
2587	}
2588
2589	$name = $other['data'][0];
2590
2591
2592	$disabled_types_event = array();
2593	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][27];
2594	$disabled_types_event = json_encode($disabled_types_event);
2595
2596	# SNMP version 3
2597	if ($other['data'][14] == "3") {
2598
2599		if ($other['data'][23] != "AES" and $other['data'][23] != "DES") {
2600			returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_priv_method doesn\'t exists. Set it to \'AES\' or \'DES\'. '));
2601			return;
2602		}
2603
2604		if ($other['data'][25] != "authNoPriv" and $other['data'][25] != "authPriv" and $other['data'][25] != "noAuthNoPriv") {
2605			returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_sec_level doesn\'t exists. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. '));
2606			return;
2607		}
2608
2609		if ($other['data'][26] != "MD5" and $other['data'][26] != "SHA") {
2610			returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_auth_method doesn\'t exists. Set it to \'MD5\' or \'SHA\'. '));
2611			return;
2612		}
2613
2614		$values = array(
2615			'id_agente' => $idAgent,
2616			'disabled' => $other['data'][1],
2617			'id_tipo_modulo' => $other['data'][2],
2618			'id_module_group' => $other['data'][3],
2619			'min_warning' => $other['data'][4],
2620			'max_warning' => $other['data'][5],
2621			'str_warning' => $other['data'][6],
2622			'min_critical' => $other['data'][7],
2623			'max_critical' => $other['data'][8],
2624			'str_critical' => $other['data'][9],
2625			'min_ff_event' => $other['data'][10],
2626			'history_data' => $other['data'][11],
2627			'ip_target' => $other['data'][12],
2628			'tcp_port' => $other['data'][13],
2629			'tcp_send' => $other['data'][14],
2630			'snmp_community' => $other['data'][15],
2631			'snmp_oid' => $other['data'][16],
2632			'module_interval' => $other['data'][17],
2633			'post_process' => $other['data'][18],
2634			'min' => $other['data'][19],
2635			'max' => $other['data'][20],
2636			'custom_id' => $other['data'][21],
2637			'descripcion' => $other['data'][22],
2638			'id_modulo' => 2,
2639			'custom_string_1' => $other['data'][23],
2640			'custom_string_2' => $other['data'][24],
2641			'custom_string_3' => $other['data'][25],
2642			'plugin_parameter' => $other['data'][26],
2643			'plugin_user' => $other['data'][27],
2644			'plugin_pass' => $other['data'][28],
2645			'disabled_types_event' => $disabled_types_event,
2646			'each_ff' => $other['data'][30],
2647			'min_ff_event_normal' => $other['data'][31],
2648			'min_ff_event_warning' => $other['data'][32],
2649			'min_ff_event_critical' => $other['data'][33]
2650		);
2651	}
2652	else {
2653		$values = array(
2654			'id_agente' => $idAgent,
2655			'disabled' => $other['data'][1],
2656			'id_tipo_modulo' => $other['data'][2],
2657			'id_module_group' => $other['data'][3],
2658			'min_warning' => $other['data'][4],
2659			'max_warning' => $other['data'][5],
2660			'str_warning' => $other['data'][6],
2661			'min_critical' => $other['data'][7],
2662			'max_critical' => $other['data'][8],
2663			'str_critical' => $other['data'][9],
2664			'min_ff_event' => $other['data'][10],
2665			'history_data' => $other['data'][11],
2666			'ip_target' => $other['data'][12],
2667			'tcp_port' => $other['data'][13],
2668			'tcp_send' => $other['data'][14],
2669			'snmp_community' => $other['data'][15],
2670			'snmp_oid' => $other['data'][16],
2671			'module_interval' => $other['data'][17],
2672			'post_process' => $other['data'][18],
2673			'min' => $other['data'][19],
2674			'max' => $other['data'][20],
2675			'custom_id' => $other['data'][21],
2676			'descripcion' => $other['data'][22],
2677			'id_modulo' => 2,
2678			'disabled_types_event' => $disabled_types_event,
2679			'each_ff' => $other['data'][24],
2680			'min_ff_event_normal' => $other['data'][25],
2681			'min_ff_event_warning' => $other['data'][26],
2682			'min_ff_event_critical' => $other['data'][27]
2683		);
2684	}
2685
2686	if ( ! $values['descripcion'] ) {
2687		$values['descripcion'] = '';	// Column 'descripcion' cannot be null
2688	}
2689
2690	$idModule = modules_create_agent_module($idAgent, $name, $values, true);
2691
2692	if (is_error($idModule)) {
2693		// TODO: Improve the error returning more info
2694		returnError('error_create_snmp_module', __('Error in creation SNMP module.'));
2695	}
2696	else {
2697		returnData('string', array('type' => 'string', 'data' => $idModule));
2698	}
2699}
2700
2701/**
2702 * Update a SNMP module in agent. And return a message with the result of the operation.
2703 *
2704 * @param string $id Id of module to update.
2705 * @param $thrash1 Don't use.
2706 * @param array $other it's array, $other as param is <id_agent>;<disabled>;
2707 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
2708 *  <history_data>;<ip_target>;<module_port>;<snmp_version>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
2709 *  <min>;<max>;<custom_id>;<description>;<snmp3_priv_method>;<snmp3_priv_pass>;<snmp3_sec_level>;<snmp3_auth_method>;
2710 *  <snmp3_auth_user>;<snmp3_auth_pass>;<each_ff>;<ff_threshold_normal>;
2711 *  <ff_threshold_warning>;<ff_threshold_critical> in this order
2712 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
2713 *  example:
2714 *
2715 * 	example (update snmp v: 3, snmp3_priv_method: AES, passw|authNoPriv|MD5|pepito_user|example_priv_passw)
2716 *
2717 *  api.php?op=set&op2=update_snmp_module&id=example_snmp_module_name&other=44|0|6|20|25||26|30||15|1|127.0.0.1|60|3|public|.1.3.6.1.2.1.1.1.0|180|50.00|10|60|0|SNMP%20module%20modified%20by%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_|
2718 *
2719 * @param $thrash3 Don't use
2720 */
2721function api_set_update_snmp_module($id_module, $thrash1, $other, $thrash3) {
2722	if (defined ('METACONSOLE')) {
2723		return;
2724	}
2725
2726	if ($id_module == "") {
2727		returnError('error_update_snmp_module', __('Error updating SNMP module. Id_module cannot be left blank.'));
2728		return;
2729	}
2730
2731	$check_id_module = db_get_value ('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module);
2732
2733	if (!$check_id_module) {
2734		returnError('error_update_snmp_module', __('Error updating SNMP module. Id_module doesn\'t exists.'));
2735		return;
2736	}
2737
2738	// If we want to change the module to a new agent
2739	if ($other['data'][0] != "") {
2740		$id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module);
2741
2742		if ($id_agent_old != $other['data'][0]) {
2743			$id_module_exists = db_get_value_filter ('id_agente_modulo', 'tagente_modulo', array('nombre' => $module_name, 'id_agente' => $other['data'][0]));
2744
2745			if ($id_module_exists) {
2746				returnError('error_update_snmp_module', __('Error updating SNMP module. Id_module exists in the new agent.'));
2747				return;
2748			}
2749		}
2750		// Check if agent exists
2751		$check_id_agent = db_get_value ('id_agente', 'tagente', 'id_agente', $other['data'][0]);
2752		if (!$check_id_agent) {
2753			returnError('error_update_data_module', __('Error updating snmp module. Id_agent doesn\'t exists.'));
2754			return;
2755		}
2756	}
2757
2758	# SNMP version 3
2759	if ($other['data'][13] == "3") {
2760
2761		if ($other['data'][22] != "AES" and $other['data'][22] != "DES") {
2762			returnError('error_create_snmp_module',
2763				__('Error in creation SNMP module. snmp3_priv_method doesn\'t exists. Set it to \'AES\' or \'DES\'. '));
2764			return;
2765		}
2766
2767		if ($other['data'][24] != "authNoPriv"
2768			and $other['data'][24] != "authPriv"
2769			and $other['data'][24] != "noAuthNoPriv") {
2770
2771			returnError('error_create_snmp_module',
2772				__('Error in creation SNMP module. snmp3_sec_level doesn\'t exists. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. '));
2773			return;
2774		}
2775
2776		if ($other['data'][25] != "MD5" and $other['data'][25] != "SHA") {
2777			returnError('error_create_snmp_module',
2778				__('Error in creation SNMP module. snmp3_auth_method doesn\'t exists. Set it to \'MD5\' or \'SHA\'. '));
2779			return;
2780		}
2781
2782		$snmp_module_fields = array(
2783			'id_agente',
2784			'disabled',
2785			'id_module_group',
2786			'min_warning',
2787			'max_warning',
2788			'str_warning',
2789			'min_critical',
2790			'max_critical',
2791			'str_critical',
2792			'min_ff_event',
2793			'history_data',
2794			'ip_target',
2795			'tcp_port',
2796			'tcp_send',
2797			'snmp_community',
2798			'snmp_oid',
2799			'module_interval',
2800			'post_process',
2801			'min',
2802			'max',
2803			'custom_id',
2804			'descripcion',
2805			'custom_string_1',
2806			'custom_string_2',
2807			'custom_string_3',
2808			'plugin_parameter',
2809			'plugin_user',
2810			'plugin_pass',
2811			'disabled_types_event',
2812			'each_ff',
2813			'min_ff_event_normal',
2814			'min_ff_event_warning',
2815			'min_ff_event_critical');
2816	}
2817	else {
2818		$snmp_module_fields = array(
2819			'id_agente',
2820			'disabled',
2821			'id_module_group',
2822			'min_warning',
2823			'max_warning',
2824			'str_warning',
2825			'min_critical',
2826			'max_critical',
2827			'str_critical',
2828			'min_ff_event',
2829			'history_data',
2830			'ip_target',
2831			'tcp_port',
2832			'tcp_send',
2833			'snmp_community',
2834			'snmp_oid',
2835			'module_interval',
2836			'post_process',
2837			'min',
2838			'max',
2839			'custom_id',
2840			'descripcion',
2841			'disabled_types_event',
2842			'each_ff',
2843			'min_ff_event_normal',
2844			'min_ff_event_warning',
2845			'min_ff_event_critical');
2846	}
2847
2848	$values = array();
2849	$cont = 0;
2850	foreach ($snmp_module_fields as $field) {
2851		if ($other['data'][$cont] != "") {
2852			$values[$field] = $other['data'][$cont];
2853		}
2854
2855		$cont++;
2856	}
2857
2858	$result_update = modules_update_agent_module($id_module, $values);
2859
2860	if ($result_update < 0)
2861		returnError('error_update_snmp_module', 'Error updating SNMP module.');
2862	else
2863		returnData('string', array('type' => 'string', 'data' => __('SNMP module updated.')));
2864}
2865
2866/**
2867 * Create new network component.
2868 *
2869 * @param $id string Name of the network component.
2870 * @param $thrash1 Don't use.
2871 * @param array $other it's array, $other as param is <network_component_type>;<description>;
2872 *  <module_interval>;<max_value>;<min_value>;<snmp_community>;<id_module_group>;<max_timeout>;
2873 *  <history_data>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;
2874 *  <ff_threshold>;<post_process>;<network_component_group>;<enable_unknown_events>;<each_ff>;
2875 *  <ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critical>  in this
2876 *  order and separator char (after text ; ) and separator (pass in param
2877 *  othermode as othermode=url_encode_separator_<separator>)
2878 *  example:
2879 *
2880 *  api.php?op=set&op2=new_network_component&id=example_network_component_name&other=7|network%20component%20created%20by%20Api|300|30|10|public|3||1|10|20|str|21|30|str1|10|50.00|12&other_mode=url_encode_separator_|
2881 *
2882 * @param $thrash2 Don't use.
2883
2884 */
2885function api_set_new_network_component($id, $thrash1, $other, $thrash2) {
2886	if (defined ('METACONSOLE')) {
2887		return;
2888	}
2889
2890	if ($id == "") {
2891		returnError('error_set_new_network_component', __('Error creating network component. Network component name cannot be left blank.'));
2892		return;
2893	}
2894
2895	if ($other['data'][0] < 6 or $other['data'][0] > 18) {
2896		returnError('error_set_new_network_component', __('Error creating network component. Incorrect value for Network component type field.'));
2897		return;
2898	}
2899
2900	if ($other['data'][17] == "") {
2901		returnError('error_set_new_network_component', __('Error creating network component. Network component group cannot be left blank.'));
2902		return;
2903	}
2904
2905	$disabled_types_event = array();
2906	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][18];
2907	$disabled_types_event = json_encode($disabled_types_event);
2908
2909	$values = array (
2910		'description' => $other['data'][1],
2911		'module_interval' => $other['data'][2],
2912		'max' => $other['data'][3],
2913		'min' => $other['data'][4],
2914		'snmp_community' => $other['data'][5],
2915		'id_module_group' => $other['data'][6],
2916		'id_modulo' => 2,
2917		'max_timeout' => $other['data'][7],
2918		'history_data' => $other['data'][8],
2919		'min_warning' => $other['data'][9],
2920		'max_warning' => $other['data'][10],
2921		'str_warning' => $other['data'][11],
2922		'min_critical' => $other['data'][12],
2923		'max_critical' => $other['data'][13],
2924		'str_critical' => $other['data'][14],
2925		'min_ff_event' => $other['data'][15],
2926		'post_process' => $other['data'][16],
2927		'id_group' => $other['data'][17],
2928		'disabled_types_event' => $disabled_types_event,
2929		'each_ff' => $other['data'][19],
2930		'min_ff_event_normal' => $other['data'][20],
2931		'min_ff_event_warning' => $other['data'][21],
2932		'min_ff_event_critical' => $other['data'][22]);
2933
2934	$name_check = db_get_value ('name', 'tnetwork_component', 'name', $id);
2935
2936	if ($name_check !== false) {
2937		returnError('error_set_new_network_component', __('Error creating network component. This network component already exists.'));
2938		return;
2939	}
2940
2941	$id = network_components_create_network_component ($id, $other['data'][0], $other['data'][17], $values);
2942
2943	if (!$id)
2944		returnError('error_set_new_network_component', 'Error creating network component.');
2945	else
2946		returnData('string', array('type' => 'string', 'data' => $id));
2947}
2948
2949/**
2950 * Create new plugin component.
2951 *
2952 * @param $id string Name of the plugin component.
2953 * @param $thrash1 Don't use.
2954 * @param array $other it's array, $other as param is <plugin_component_type>;<description>;
2955 *  <module_interval>;<max_value>;<min_value>;<module_port>;<id_module_group>;<id_plugin>;<max_timeout>;
2956 *  <history_data>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;
2957 *  <ff_threshold>;<post_process>;<plugin_component_group>;<enable_unknown_events>;
2958 *  <each_ff>;<ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critical> in this
2959 *  order and separator char (after text ; ) and separator (pass in param
2960 *  othermode as othermode=url_encode_separator_<separator>)
2961 *  example:
2962 *
2963 *  api.php?op=set&op2=new_plugin_component&id=example_plugin_component_name&other=2|plugin%20component%20created%20by%20Api|300|30|10|66|3|2|example_user|example_pass|-p%20max||1|10|20|str|21|30|str1|10|50.00|12&other_mode=url_encode_separator_|
2964 *
2965 * @param $thrash2 Don't use.
2966
2967 */
2968function api_set_new_plugin_component($id, $thrash1, $other, $thrash2) {
2969	if (defined ('METACONSOLE')) {
2970		return;
2971	}
2972
2973
2974	if ($id == "") {
2975		returnError('error_set_new_plugin_component',
2976			__('Error creating plugin component. Plugin component name cannot be left blank.'));
2977		return;
2978	}
2979
2980	if ($other['data'][7] == "") {
2981		returnError('error_set_new_plugin_component', __('Error creating plugin component. Incorrect value for Id plugin.'));
2982		return;
2983	}
2984
2985	if ($other['data'][21] == "") {
2986		returnError('error_set_new_plugin_component', __('Error creating plugin component. Plugin component group cannot be left blank.'));
2987		return;
2988	}
2989
2990	$disabled_types_event = array();
2991	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][12];
2992	$disabled_types_event = json_encode($disabled_types_event);
2993
2994	$values = array (
2995		'description' => $other['data'][1],
2996		'module_interval' => $other['data'][2],
2997		'max' => $other['data'][3],
2998		'min' => $other['data'][4],
2999		'tcp_port' => $other['data'][5],
3000		'id_module_group' => $other['data'][6],
3001		'id_modulo' => 4,
3002		'id_plugin' => $other['data'][7],
3003		'plugin_user' => $other['data'][8],
3004		'plugin_pass' => $other['data'][9],
3005		'plugin_parameter' => $other['data'][10],
3006		'max_timeout' => $other['data'][11],
3007		'history_data' => $other['data'][12],
3008		'min_warning' => $other['data'][13],
3009		'max_warning' => $other['data'][14],
3010		'str_warning' => $other['data'][15],
3011		'min_critical' => $other['data'][16],
3012		'max_critical' => $other['data'][17],
3013		'str_critical' => $other['data'][18],
3014		'min_ff_event' => $other['data'][19],
3015		'post_process' => $other['data'][20],
3016		'id_group' => $other['data'][21],
3017		'disabled_types_event' => $disabled_types_event,
3018		'each_ff' => $other['data'][23],
3019		'min_ff_event_normal' => $other['data'][24],
3020		'min_ff_event_warning' => $other['data'][25],
3021		'min_ff_event_critical' => $other['data'][26]);
3022
3023	$name_check = db_get_value ('name', 'tnetwork_component', 'name', $id);
3024
3025	if ($name_check !== false) {
3026		returnError('error_set_new_plugin_component', __('Error creating plugin component. This plugin component already exists.'));
3027		return;
3028	}
3029
3030	$id = network_components_create_network_component ($id, $other['data'][0], $other['data'][21], $values);
3031
3032	if (!$id)
3033		returnError('error_set_new_plugin_component', 'Error creating plugin component.');
3034	else
3035		returnData('string', array('type' => 'string', 'data' => $id));
3036}
3037
3038/**
3039 * Create new SNMP component.
3040 *
3041 * @param $id string Name of the SNMP component.
3042 * @param $thrash1 Don't use.
3043 * @param array $other it's array, $other as param is <snmp_component_type>;<description>;
3044 *  <module_interval>;<max_value>;<min_value>;<id_module_group>;<max_timeout>;
3045 *  <history_data>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;
3046 *  <ff_threshold>;<post_process>;<snmp_version>;<snmp_oid>;<snmp_community>;
3047 *  <snmp3_auth_user>;<snmp3_auth_pass>;<module_port>;<snmp3_privacy_method>;<snmp3_privacy_pass>;<snmp3_auth_method>;<snmp3_security_level>;<snmp_component_group>;<enable_unknown_events>;
3048 *  <each_ff>;<ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critical> in this
3049 *  order and separator char (after text ; ) and separator (pass in param
3050 *  othermode as othermode=url_encode_separator_<separator>)
3051 *  example:
3052 *
3053 *  api.php?op=set&op2=new_snmp_component&id=example_snmp_component_name&other=16|SNMP%20component%20created%20by%20Api|300|30|10|3||1|10|20|str|21|30|str1|15|50.00|3|.1.3.6.1.2.1.2.2.1.8.2|public|example_auth_user|example_auth_pass|66|AES|example_priv_pass|MD5|authNoPriv|12&other_mode=url_encode_separator_|
3054 *
3055 * @param $thrash2 Don't use.
3056
3057 */
3058function api_set_new_snmp_component($id, $thrash1, $other, $thrash2) {
3059	if (defined ('METACONSOLE')) {
3060		return;
3061	}
3062
3063	if ($id == "") {
3064		returnError('error_set_new_snmp_component', __('Error creating SNMP component. SNMP component name cannot be left blank.'));
3065		return;
3066	}
3067
3068	if ($other['data'][0] < 15 or $other['data'][0] > 17) {
3069		returnError('error_set_new_snmp_component', __('Error creating SNMP component. Incorrect value for Snmp component type field.'));
3070		return;
3071	}
3072
3073	if ($other['data'][25] == "") {
3074		returnError('error_set_new_snmp_component', __('Error creating SNMP component. Snmp component group cannot be left blank.'));
3075		return;
3076	}
3077
3078	$disabled_types_event = array();
3079	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][27];
3080	$disabled_types_event = json_encode($disabled_types_event);
3081
3082	# SNMP version 3
3083	if ($other['data'][16] == "3") {
3084
3085		if ($other['data'][22] != "AES" and $other['data'][22] != "DES") {
3086			returnError('error_set_new_snmp_component', __('Error creating SNMP component. snmp3_priv_method doesn\'t exists. Set it to \'AES\' or \'DES\'. '));
3087			return;
3088		}
3089
3090		if ($other['data'][25] != "authNoPriv"
3091			and $other['data'][25] != "authPriv"
3092			and $other['data'][25] != "noAuthNoPriv") {
3093
3094			returnError('error_set_new_snmp_component',
3095				__('Error creating SNMP component. snmp3_sec_level doesn\'t exists. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. '));
3096			return;
3097		}
3098
3099		if ($other['data'][24] != "MD5" and $other['data'][24] != "SHA") {
3100			returnError('error_set_new_snmp_component',
3101				__('Error creating SNMP component. snmp3_auth_method doesn\'t exists. Set it to \'MD5\' or \'SHA\'. '));
3102			return;
3103		}
3104
3105		$values = array (
3106			'description' => $other['data'][1],
3107			'module_interval' => $other['data'][2],
3108			'max' => $other['data'][3],
3109			'min' => $other['data'][4],
3110			'id_module_group' => $other['data'][5],
3111			'max_timeout' => $other['data'][6],
3112			'history_data' => $other['data'][7],
3113			'min_warning' => $other['data'][8],
3114			'max_warning' => $other['data'][9],
3115			'str_warning' => $other['data'][10],
3116			'min_critical' => $other['data'][11],
3117			'max_critical' => $other['data'][12],
3118			'str_critical' => $other['data'][13],
3119			'min_ff_event' => $other['data'][14],
3120			'post_process' => $other['data'][15],
3121			'tcp_send' => $other['data'][16],
3122			'snmp_oid' => $other['data'][17],
3123			'snmp_community' => $other['data'][18],
3124			'plugin_user' => $other['data'][19],		// snmp3_auth_user
3125			'plugin_pass' => $other['data'][20],		// snmp3_auth_pass
3126			'tcp_port' => $other['data'][21],
3127			'id_modulo' => 2,
3128			'custom_string_1' => $other['data'][22],	// snmp3_privacy_method
3129			'custom_string_2' => $other['data'][23],	// snmp3_privacy_pass
3130			'plugin_parameter' => $other['data'][24],	// snmp3_auth_method
3131			'custom_string_3' => $other['data'][25],	// snmp3_security_level
3132			'id_group' => $other['data'][26],
3133			'disabled_types_event' => $disabled_types_event,
3134			'each_ff' => $other['data'][28],
3135			'min_ff_event_normal' => $other['data'][29],
3136			'min_ff_event_warning' => $other['data'][30],
3137			'min_ff_event_critical' => $other['data'][31]
3138			);
3139	}
3140	else {
3141		$values = array (
3142			'description' => $other['data'][1],
3143			'module_interval' => $other['data'][2],
3144			'max' => $other['data'][3],
3145			'min' => $other['data'][4],
3146			'id_module_group' => $other['data'][5],
3147			'max_timeout' => $other['data'][6],
3148			'history_data' => $other['data'][7],
3149			'min_warning' => $other['data'][8],
3150			'max_warning' => $other['data'][9],
3151			'str_warning' => $other['data'][10],
3152			'min_critical' => $other['data'][11],
3153			'max_critical' => $other['data'][12],
3154			'str_critical' => $other['data'][13],
3155			'min_ff_event' => $other['data'][14],
3156			'post_process' => $other['data'][15],
3157			'tcp_send' => $other['data'][16],
3158			'snmp_oid' => $other['data'][17],
3159			'snmp_community' => $other['data'][18],
3160			'plugin_user' => '',
3161			'plugin_pass' => '',
3162			'tcp_port' => $other['data'][21],
3163			'id_modulo' => 2,
3164			'id_group' => $other['data'][22],
3165			'disabled_types_event' => $disabled_types_event,
3166			'each_ff' => $other['data'][24],
3167			'min_ff_event_normal' => $other['data'][25],
3168			'min_ff_event_warning' => $other['data'][26],
3169			'min_ff_event_critical' => $other['data'][27]
3170			);
3171	}
3172
3173	$name_check = db_get_value ('name', 'tnetwork_component', 'name', $id);
3174
3175	if ($name_check !== false) {
3176		returnError('error_set_new_snmp_component', __('Error creating SNMP component. This SNMP component already exists.'));
3177		return;
3178	}
3179
3180	$id = network_components_create_network_component ($id, $other['data'][0], $other['data'][25], $values);
3181
3182	if (!$id)
3183		returnError('error_set_new_snmp_component', 'Error creating SNMP component.');
3184	else
3185		returnData('string', array('type' => 'string', 'data' => $id));
3186}
3187
3188/**
3189 * Create new local (data) component.
3190 *
3191 * @param $id string Name of the local component.
3192 * @param $thrash1 Don't use.
3193 * @param array $other it's array, $other as param is <description>;<id_os>;
3194 *  <local_component_group>;<configuration_data>;<enable_unknown_events>;
3195 *  <ff_threshold>;<each_ff>;<ff_threshold_normal>;<ff_threshold_warning>;
3196 *  <ff_threshold_critical>;<ff_timeout>  in this order and separator char
3197 *  (after text ; ) and separator (pass in param othermode as
3198 *  othermode=url_encode_separator_<separator>)
3199 *  example:
3200 *
3201 *  api.php?op=set&op2=new_local_component&id=example_local_component_name&other=local%20component%20created%20by%20Api~5~12~module_begin%0dmodule_name%20example_local_component_name%0dmodule_type%20generic_data%0dmodule_exec%20ps%20|%20grep%20pid%20|%20wc%20-l%0dmodule_interval%202%0dmodule_end&other_mode=url_encode_separator_~
3202 *
3203 * @param $thrash2 Don't use.
3204
3205 */
3206function api_set_new_local_component($id, $thrash1, $other, $thrash2) {
3207	if (defined ('METACONSOLE')) {
3208		return;
3209	}
3210
3211	if ($id == "") {
3212		returnError('error_set_new_local_component',
3213			__('Error creating local component. Local component name cannot be left blank.'));
3214		return;
3215	}
3216
3217	if ($other['data'][1] == "") {
3218		returnError('error_set_new_local_component',
3219			__('Error creating local component. Local component group cannot be left blank.'));
3220		return;
3221	}
3222
3223	$disabled_types_event = array();
3224	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][4];
3225	$disabled_types_event = json_encode($disabled_types_event);
3226
3227	$values = array (
3228		'description' => $other['data'][0],
3229		'id_network_component_group' => $other['data'][2],
3230		'disabled_types_event' => $disabled_types_event,
3231		'min_ff_event' => $other['data'][5],
3232		'each_ff' => $other['data'][6],
3233		'min_ff_event_normal' => $other['data'][7],
3234		'min_ff_event_warning' => $other['data'][8],
3235		'min_ff_event_critical' => $other['data'][9],
3236		'ff_timeout' => $other['data'][10]);
3237
3238	$name_check = enterprise_hook('local_components_get_local_components',
3239		array(array('name' => $id), 'name'));
3240
3241	if ($name_check === ENTERPRISE_NOT_HOOK) {
3242		returnError('error_set_new_local_component',
3243			__('Error creating local component.'));
3244		return;
3245	}
3246
3247	if ($name_check !== false) {
3248		returnError('error_set_new_local_component',
3249			__('Error creating local component. This local component already exists.'));
3250		return;
3251	}
3252
3253	$id = enterprise_hook('local_components_create_local_component',
3254		array($id, $other['data'][3], $other['data'][1], $values));
3255
3256	if (!$id)
3257		returnError('error_set_new_local_component', 'Error creating local component.');
3258	else
3259		returnData('string', array('type' => 'string', 'data' => $id));
3260}
3261
3262/**
3263 * Get module data value from all agents filter by module name. And return id_agents, agent_name and module value.
3264 *
3265 * @param $id string Name of the module.
3266 * @param $thrash1 Don't use.
3267 * @param array $other Don't use.
3268 *  example:
3269 *
3270 *  api.php?op=get&op2=module_value_all_agents&id=example_module_name
3271 *
3272 * @param $thrash2 Don't use.
3273
3274 */
3275function api_get_module_value_all_agents($id, $thrash1, $other, $thrash2) {
3276	if (defined ('METACONSOLE')) {
3277		return;
3278	}
3279
3280	if ($id == "") {
3281		returnError('error_get_module_value_all_agents',
3282			__('Error getting module value from all agents. Module name cannot be left blank.'));
3283		return;
3284	}
3285
3286	$id_module = db_get_value ('id_agente_modulo', 'tagente_modulo', 'nombre', $id);
3287
3288	if ($id_module === false) {
3289		returnError('error_get_module_value_all_agents',
3290			__('Error getting module value from all agents. Module name doesn\'t exists.'));
3291		return;
3292	}
3293
3294	$sql = sprintf("SELECT agent.id_agente, agent.nombre, module_state.datos FROM tagente agent, tagente_modulo module, tagente_estado module_state WHERE agent.id_agente = module.id_agente AND module.id_agente_modulo=module_state.id_agente_modulo AND module.nombre = '%s'", $id);
3295
3296	$module_values = db_get_all_rows_sql($sql);
3297
3298	if (!$module_values) {
3299		returnError('error_get_module_value_all_agents', 'Error getting module values from all agents.');
3300	}
3301	else {
3302		$data = array('type' => 'array', 'data' => $module_values);
3303
3304		returnData('csv', $data, ';');
3305	}
3306}
3307
3308/**
3309 * Create an alert template. And return the id of new template.
3310 *
3311 * @param string $id Name of alert template to add.
3312 * @param $thrash1 Don't use.
3313 * @param array $other it's array, $other as param is <type>;<description>;<id_alert_action>;
3314 *  <field1>;<field2>;<field3>;<value>;<matches_value>;<max_value>;<min_value>;<time_threshold>;
3315 *  <max_alerts>;<min_alerts>;<time_from>;<time_to>;<monday>;<tuesday>;<wednesday>;
3316 *  <thursday>;<friday>;<saturday>;<sunday>;<recovery_notify>;<field2_recovery>;<field3_recovery>;<priority>;<id_group> in this order
3317 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
3318 *  example:
3319 *
3320 *  example 1 (condition: regexp =~ /pp/, action: Mail to XXX, max_alert: 10, min_alert: 0, priority: WARNING, group: databases):
3321 *  api.php?op=set&op2=create_alert_template&id=pepito&other=regex|template%20based%20in%20regexp|1||||pp|1||||10|0|||||||||||||3&other_mode=url_encode_separator_|
3322 *
3323 * 	example 2 (condition: value is not between 5 and 10, max_value: 10.00, min_value: 5.00, time_from: 00:00:00, time_to: 15:00:00, priority: CRITICAL, group: Servers):
3324 *  api.php?op=set&op2=create_alert_template&id=template_min_max&other=max_min|template%20based%20in%20range|NULL||||||10|5||||00:00:00|15:00:00|||||||||||4|2&other_mode=url_encode_separator_|
3325 *
3326 * @param $thrash3 Don't use
3327 */
3328function api_set_create_alert_template($name, $thrash1, $other, $thrash3) {
3329	if (defined ('METACONSOLE')) {
3330		return;
3331	}
3332
3333	if ($name == "") {
3334		returnError('error_create_alert_template',
3335			__('Error creating alert template. Template name cannot be left blank.'));
3336		return;
3337	}
3338
3339	$template_name = $name;
3340
3341	$type = $other['data'][0];
3342
3343	if ($other['data'][2] != "") {
3344		$values = array(
3345			'description' => $other['data'][1],
3346			'id_alert_action' => $other['data'][2],
3347			'field1' => $other['data'][3],
3348			'field2' => $other['data'][4],
3349			'field3' => $other['data'][5],
3350			'value' => $other['data'][6],
3351			'matches_value' => $other['data'][7],
3352			'max_value' => $other['data'][8],
3353			'min_value' => $other['data'][9],
3354			'time_threshold' => $other['data'][10],
3355			'max_alerts' => $other['data'][11],
3356			'min_alerts' => $other['data'][12],
3357			'time_from' => $other['data'][13],
3358			'time_to' => $other['data'][14],
3359			'monday' => $other['data'][15],
3360			'tuesday' => $other['data'][16],
3361			'wednesday' => $other['data'][17],
3362			'thursday' => $other['data'][18],
3363			'friday' => $other['data'][19],
3364			'saturday' => $other['data'][20],
3365			'sunday' => $other['data'][21],
3366			'recovery_notify' => $other['data'][22],
3367			'field2_recovery' => $other['data'][23],
3368			'field3_recovery' => $other['data'][24],
3369			'priority' => $other['data'][25],
3370			'id_group' => $other['data'][26]
3371		);
3372	}
3373	else {
3374		$values = array(
3375			'description' => $other['data'][1],
3376			'field1' => $other['data'][3],
3377			'field2' => $other['data'][4],
3378			'field3' => $other['data'][5],
3379			'value' => $other['data'][6],
3380			'matches_value' => $other['data'][7],
3381			'max_value' => $other['data'][8],
3382			'min_value' => $other['data'][9],
3383			'time_threshold' => $other['data'][10],
3384			'max_alerts' => $other['data'][11],
3385			'min_alerts' => $other['data'][12],
3386			'time_from' => $other['data'][13],
3387			'time_to' => $other['data'][14],
3388			'monday' => $other['data'][15],
3389			'tuesday' => $other['data'][16],
3390			'wednesday' => $other['data'][17],
3391			'thursday' => $other['data'][18],
3392			'friday' => $other['data'][19],
3393			'saturday' => $other['data'][20],
3394			'sunday' => $other['data'][21],
3395			'recovery_notify' => $other['data'][22],
3396			'field2_recovery' => $other['data'][23],
3397			'field3_recovery' => $other['data'][24],
3398			'priority' => $other['data'][25],
3399			'id_group' => $other['data'][26]
3400		);
3401	}
3402
3403	$id_template = alerts_create_alert_template($template_name, $type, $values);
3404
3405	if (is_error($id_template)) {
3406		// TODO: Improve the error returning more info
3407		returnError('error_create_alert_template', __('Error creating alert template.'));
3408	}
3409	else {
3410		returnData('string', array('type' => 'string', 'data' => $id_template));
3411	}
3412}
3413
3414/**
3415 * Update an alert template. And return a message with the result of the operation.
3416 *
3417 * @param string $id_template Id of the template to update.
3418 * @param $thrash1 Don't use.
3419 * @param array $other it's array, $other as param is <template_name>;<type>;<description>;<id_alert_action>;
3420 *  <field1>;<field2>;<field3>;<value>;<matches_value>;<max_value>;<min_value>;<time_threshold>;
3421 *  <max_alerts>;<min_alerts>;<time_from>;<time_to>;<monday>;<tuesday>;<wednesday>;
3422 *  <thursday>;<friday>;<saturday>;<sunday>;<recovery_notify>;<field2_recovery>;<field3_recovery>;<priority>;<id_group> in this order
3423 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
3424 *
3425 *  example:
3426 *
3427 * api.php?op=set&op2=update_alert_template&id=38&other=example_template_with_changed_name|onchange|changing%20from%20min_max%20to%20onchange||||||1||||5|1|||1|1|0|1|1|0|0|1|field%20recovery%20example%201|field%20recovery%20example%202|1|8&other_mode=url_encode_separator_|
3428 *
3429 * @param $thrash3 Don't use
3430 */
3431function api_set_update_alert_template($id_template, $thrash1, $other, $thrash3) {
3432	if (defined ('METACONSOLE')) {
3433		return;
3434	}
3435
3436	if ($id_template == "") {
3437		returnError('error_update_alert_template',
3438			__('Error updating alert template. Id_template cannot be left blank.'));
3439		return;
3440	}
3441
3442	$result_template = alerts_get_alert_template_name($id_template);
3443
3444	if (!$result_template) {
3445		returnError('error_update_alert_template',
3446			__('Error updating alert template. Id_template doesn\'t exists.'));
3447		return;
3448	}
3449
3450	$fields_template = array('name', 'type', 'description',
3451		'id_alert_action', 'field1', 'field2', 'field3', 'value',
3452		'matches_value', 'max_value', 'min_value', 'time_threshold',
3453		'max_alerts', 'min_alerts', 'time_from', 'time_to', 'monday',
3454		'tuesday', 'wednesday', 'thursday', 'friday', 'saturday',
3455		'sunday', 'recovery_notify', 'field2_recovery',
3456		'field3_recovery', 'priority', 'id_group');
3457
3458	$cont = 0;
3459	foreach ($fields_template as $field) {
3460		if ($other['data'][$cont] != "") {
3461			$values[$field] = $other['data'][$cont];
3462		}
3463
3464		$cont++;
3465	}
3466
3467	$id_template = alerts_update_alert_template($id_template, $values);
3468
3469	if (is_error($id_template)) {
3470		// TODO: Improve the error returning more info
3471		returnError('error_create_alert_template',
3472			__('Error updating alert template.'));
3473	}
3474	else {
3475		returnData('string',
3476			array('type' => 'string',
3477				'data' => __('Correct updating of alert template')));
3478	}
3479}
3480
3481/**
3482 * Delete an alert template. And return a message with the result of the operation.
3483 *
3484 * @param string $id_template Id of the template to delete.
3485 * @param $thrash1 Don't use.
3486 * @param array $other Don't use
3487 *
3488 *  example:
3489 *
3490 * api.php?op=set&op2=delete_alert_template&id=38
3491 *
3492 * @param $thrash3 Don't use
3493 */
3494function api_set_delete_alert_template($id_template, $thrash1, $other, $thrash3) {
3495	if (defined ('METACONSOLE')) {
3496		return;
3497	}
3498
3499	if ($id_template == "") {
3500		returnError('error_delete_alert_template',
3501			__('Error deleting alert template. Id_template cannot be left blank.'));
3502		return;
3503	}
3504
3505	$result = alerts_delete_alert_template($id_template);
3506
3507	if ($result == 0) {
3508		// TODO: Improve the error returning more info
3509		returnError('error_create_alert_template',
3510			__('Error deleting alert template.'));
3511	}
3512	else {
3513		returnData('string', array('type' => 'string',
3514			'data' => __('Correct deleting of alert template.')));
3515	}
3516}
3517
3518/**
3519 * Get all alert tamplates, and print all the result like a csv.
3520 *
3521 * @param $thrash1 Don't use.
3522 * @param $thrash2 Don't use.
3523 * @param array $other it's array, but only <csv_separator> is available.
3524 *  example:
3525 *
3526 *  api.php?op=get&op2=all_alert_templates&return_type=csv&other=;
3527 *
3528 * @param $thrash3 Don't use.
3529 */
3530function api_get_all_alert_templates($thrash1, $thrash2, $other, $thrash3) {
3531	if (defined ('METACONSOLE')) {
3532		return;
3533	}
3534
3535	if (!isset($other['data'][0]))
3536		$separator = ';'; // by default
3537	else
3538		$separator = $other['data'][0];
3539
3540	$filter_templates = false;
3541
3542	$template = alerts_get_alert_templates();
3543
3544	if ($template !== false) {
3545		$data['type'] = 'array';
3546		$data['data'] = $template;
3547	}
3548
3549	if (!$template) {
3550		returnError('error_get_all_alert_templates',
3551			__('Error getting all alert templates.'));
3552	}
3553	else {
3554		returnData('csv', $data, $separator);
3555	}
3556}
3557
3558/**
3559 * Get an alert tamplate, and print the result like a csv.
3560 *
3561 * @param string $id_template Id of the template to get.
3562 * @param $thrash1 Don't use.
3563 * @param array $other Don't use
3564 *
3565 *  example:
3566 *
3567 * api.php?op=get&op2=alert_template&id=25
3568 *
3569 * @param $thrash3 Don't use
3570 */
3571function api_get_alert_template($id_template, $thrash1, $other, $thrash3) {
3572	if (defined ('METACONSOLE')) {
3573		return;
3574	}
3575
3576	$filter_templates = false;
3577
3578	if ($id_template != "") {
3579		$result_template = alerts_get_alert_template_name($id_template);
3580
3581		if (!$result_template) {
3582			returnError('error_get_alert_template',
3583				__('Error getting alert template. Id_template doesn\'t exists.'));
3584			return;
3585		}
3586
3587		$filter_templates = array('id' => $id_template);
3588	}
3589
3590	$template = alerts_get_alert_templates($filter_templates,
3591		array('id', 'name', 'description', 'id_alert_action', 'type', 'id_group'));
3592
3593	if ($template !== false) {
3594		$data['type'] = 'array';
3595		$data['data'] = $template;
3596	}
3597
3598	if (!$template) {
3599		returnError('error_get_alert_template',
3600			__('Error getting alert template.'));
3601	}
3602	else {
3603		returnData('csv', $data, ';');
3604	}
3605}
3606
3607/**
3608 * Get module groups, and print all the result like a csv.
3609 *
3610 * @param $thrash1 Don't use.
3611 * @param $thrash2 Don't use.
3612 * @param array $other it's array, but only <csv_separator> is available.
3613 *  example:
3614 *
3615 *  api.php?op=get&op2=module_groups&return_type=csv&other=;
3616 *
3617 * @param $thrash3 Don't use.
3618 */
3619function api_get_module_groups($thrash1, $thrash2, $other, $thrash3) {
3620	if (defined ('METACONSOLE')) {
3621		return;
3622	}
3623
3624	if (!isset($other['data'][0]))
3625		$separator = ';'; // by default
3626	else
3627		$separator = $other['data'][0];
3628
3629	$filter = false;
3630
3631	$module_groups = @db_get_all_rows_filter ('tmodule_group', $filter);
3632
3633	if ($module_groups !== false) {
3634		$data['type'] = 'array';
3635		$data['data'] = $module_groups;
3636	}
3637
3638	if (!$module_groups) {
3639		returnError('error_get_module_groups', __('Error getting module groups.'));
3640	}
3641	else {
3642		returnData('csv', $data, $separator);
3643	}
3644}
3645
3646/**
3647 * Get plugins, and print all the result like a csv.
3648 *
3649 * @param $thrash1 Don't use.
3650 * @param $thrash2 Don't use.
3651 * @param array $other it's array, but only <csv_separator> is available.
3652 *  example:
3653 *
3654 *  api.php?op=get&op2=plugins&return_type=csv&other=;
3655 *
3656 * @param $thrash3 Don't use.
3657 */
3658function api_get_plugins($thrash1, $thrash2, $other, $thrash3) {
3659	if (defined ('METACONSOLE')) {
3660		return;
3661	}
3662
3663	if (!isset($other['data'][0]))
3664		$separator = ';'; // by default
3665	else
3666		$separator = $other['data'][0];
3667
3668	$filter = false;
3669	$field_list = array( 'id', 'name', 'description',
3670				'max_timeout', 'max_retries',
3671				'execute', 'net_dst_opt',
3672				'net_port_opt', 'user_opt',
3673				'pass_opt', 'plugin_type',
3674				'macros', 'parameters');
3675
3676	$plugins = @db_get_all_rows_filter ('tplugin', $filter, $field_list);
3677
3678	if ($plugins !== false) {
3679		$data['type'] = 'array';
3680		$data['data'] = $plugins;
3681	}
3682
3683	if (!$plugins) {
3684		returnError('error_get_plugins', __('Error getting plugins.'));
3685	}
3686	else {
3687		returnData('csv', $data, $separator);
3688	}
3689}
3690
3691/**
3692 * Create a network module from a network component. And return the id of new module.
3693 *
3694 * @param string $agent_name The name of the agent where the module will be created
3695 * @param string $component_name The name of the network component
3696 * @param $thrash1 Don't use
3697 * @param $thrash2 Don't use
3698 */
3699function api_set_create_network_module_from_component($agent_name, $component_name, $thrash1, $thrash2) {
3700	if (defined ('METACONSOLE')) {
3701		return;
3702	}
3703
3704	$agent_id = agents_get_agent_id($agent_name);
3705
3706	if (!$agent_id) {
3707		returnError('error_network_module_from_component', __('Error creating module from network component. Agent doesn\'t exists.'));
3708		return;
3709	}
3710
3711	$component= db_get_row ('tnetwork_component', 'name', $component_name);
3712
3713	if (!$component) {
3714		returnError('error_network_module_from_component', __('Error creating module from network component. Network component doesn\'t exists.'));
3715		return;
3716	}
3717
3718	// Adapt fields to module structure
3719	unset($component['id_nc']);
3720	unset($component['id_group']);
3721	$component['id_tipo_modulo'] = $component['type'];
3722	unset($component['type']);
3723	$component['descripcion'] = $component['description'];
3724	unset($component['description']);
3725	unset($component['name']);
3726	$component['ip_target'] = agents_get_address($agent_id);
3727
3728	// Create module
3729	$module_id = modules_create_agent_module ($agent_id, $component_name, $component, true);
3730
3731	if (!$module_id) {
3732		returnError('error_network_module_from_component', __('Error creating module from network component. Error creating module.'));
3733		return;
3734	}
3735
3736	return $module_id;
3737}
3738
3739/**
3740 * Assign a module to an alert template. And return the id of new relationship.
3741 *
3742 * @param string $id_template Name of alert template to add.
3743 * @param $thrash1 Don't use.
3744 * @param array $other it's array, $other as param is <id_module>;<id_agent> in this order
3745 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
3746 *  example:
3747 *
3748 *  api.php?op=set&op2=create_module_template&id=1&other=1|10&other_mode=url_encode_separator_|
3749 *
3750 * @param $thrash3 Don't use
3751 */
3752function api_set_create_module_template($id, $thrash1, $other, $thrash3) {
3753	if (defined ('METACONSOLE')) {
3754		return;
3755	}
3756
3757	if ($id == "") {
3758		returnError('error_module_to_template',
3759			__('Error assigning module to template. Id_template cannot be left blank.'));
3760		return;
3761	}
3762
3763	if ($other['data'][0] == "") {
3764		returnError('error_module_to_template',
3765			__('Error assigning module to template. Id_module cannot be left blank.'));
3766		return;
3767	}
3768
3769	if ($other['data'][1] == "") {
3770		returnError('error_module_to_template',
3771			__('Error assigning module to template. Id_agent cannot be left blank.'));
3772		return;
3773	}
3774
3775	$result_template = alerts_get_alert_template($id);
3776
3777	if (!$result_template) {
3778		returnError('error_module_to_template',
3779			__('Error assigning module to template. Id_template doensn\'t exists.'));
3780		return;
3781	}
3782
3783	$id_module = $other['data'][0];
3784	$id_agent = $other['data'][1];
3785
3786	$result_agent = agents_get_name($id_agent);
3787
3788	if (!$result_agent) {
3789		returnError('error_module_to_template', __('Error assigning module to template. Id_agent doesn\'t exists.'));
3790		return;
3791	}
3792
3793	$result_module = db_get_value ('nombre', 'tagente_modulo', 'id_agente_modulo', (int) $id_module);
3794
3795	if (!$result_module) {
3796		returnError('error_module_to_template', __('Error assigning module to template. Id_module doesn\'t exists.'));
3797		return;
3798	}
3799
3800	$id_template_module = alerts_create_alert_agent_module($id_module, $id);
3801
3802	if (is_error($id_template_module)) {
3803		// TODO: Improve the error returning more info
3804		returnError('error_module_to_template', __('Error assigning module to template.'));
3805	}
3806	else {
3807		returnData('string', array('type' => 'string', 'data' => $id_template_module));
3808	}
3809}
3810
3811/**
3812 * Delete an module assigned to a template. And return a message with the result of the operation.
3813 *
3814 * @param string $id Id of the relationship between module and template (talert_template_modules) to delete.
3815 * @param $thrash1 Don't use.
3816 * @param array $other Don't use
3817 *
3818 *  example:
3819 *
3820 * api.php?op=set&op2=delete_module_template&id=38
3821 *
3822 * @param $thrash3 Don't use
3823 */
3824function api_set_delete_module_template($id, $thrash1, $other, $thrash3) {
3825	if (defined ('METACONSOLE')) {
3826		return;
3827	}
3828
3829	if ($id == "") {
3830		returnError('error_delete_module_template', __('Error deleting module template. Id_module_template cannot be left blank.'));
3831		return;
3832	}
3833
3834	$result_module_template = alerts_get_alert_agent_module($id);
3835
3836	if (!$result_module_template) {
3837		returnError('error_delete_module_template', __('Error deleting module template. Id_module_template doesn\'t exists.'));
3838		return;
3839	}
3840
3841	$result = alerts_delete_alert_agent_module($id);
3842
3843	if ($result == 0) {
3844		// TODO: Improve the error returning more info
3845		returnError('error_delete_module_template', __('Error deleting module template.'));
3846	}
3847	else {
3848		returnData('string', array('type' => 'string', 'data' => __('Correct deleting of module template.')));
3849	}
3850}
3851
3852/**
3853 * Delete an module assigned to a template. And return a message with the result of the operation.
3854 *
3855 * @param $id		Agent Name
3856 * @param $id2		Alert Template Name
3857 * @param $other	[0] : Module Name
3858 * @param $trash1	Don't use
3859 *
3860 *  example:
3861 *
3862 * api.php?op=set&op2=delete_module_template_by_names&id=my_latest_agent&id2=test_template&other=memfree
3863 *
3864 */
3865function api_set_delete_module_template_by_names($id, $id2, $other, $trash1) {
3866	if (defined ('METACONSOLE')) {
3867		return;
3868	}
3869
3870	$result = 0;
3871
3872	if ($other['type'] != 'string') {
3873		returnError('error_parameter', 'Error in the parameters.');
3874		return;
3875	}
3876
3877	$idAgent = agents_get_agent_id($id);
3878
3879	$row = db_get_row_filter('talert_templates', array('name' => $id2));
3880
3881	if ($row === false) {
3882		returnError('error_parameter', 'Error in the parameters.');
3883		return;
3884	}
3885
3886	$idTemplate = $row['id'];
3887	$idActionTemplate = $row['id_alert_action'];
3888
3889	$idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $idAgent, 'nombre' => $other['data']));
3890
3891	if ($idAgentModule === false) {
3892		returnError('error_parameter', 'Error in the parameters.');
3893		return;
3894	}
3895
3896	$values = array(
3897		'id_agent_module' => $idAgentModule,
3898		'id_alert_template' => $idTemplate);
3899
3900	$result = db_process_sql_delete ('talert_template_modules', $values);
3901
3902	if ($result == 0) {
3903		// TODO: Improve the error returning more info
3904		returnError('error_delete_module_template_by_name', __('Error deleting module template.'));
3905	}
3906	else {
3907		returnData('string', array('type' => 'string', 'data' => __('Correct deleting of module template.')));
3908	}
3909}
3910
3911/**
3912 * Validate all alerts. And return a message with the result of the operation.
3913 *
3914 * @param string Don't use.
3915 * @param $thrash1 Don't use.
3916 * @param array $other Don't use
3917 *
3918 *  example:
3919 *
3920 * api.php?op=set&op2=validate_all_alerts
3921 *
3922 * @param $thrash3 Don't use
3923 */
3924function api_set_validate_all_alerts($id, $thrash1, $other, $thrash3) {
3925
3926	if (defined ('METACONSOLE')) {
3927		return;
3928	}
3929
3930	// Return all groups
3931	$allGroups = db_get_all_rows_filter('tgrupo', array(), 'id_grupo');
3932
3933	$groups = array();
3934
3935	foreach ($allGroups as $row) {
3936		$groups[] = $row['id_grupo'];
3937	}
3938	// Added group All
3939	$groups[] = 0;
3940
3941	$id_groups = implode(',', $groups);
3942
3943	$sql = sprintf ("SELECT id_agente
3944		FROM tagente
3945		WHERE id_grupo IN (%s) AND disabled = 0",
3946		$id_groups);
3947
3948	$id_agents = array();
3949	$result_agents = array();
3950
3951	$id_agents = db_get_all_rows_sql($sql);
3952
3953	foreach ($id_agents as $id_agent) {
3954		$result_agents[] = $id_agent['id_agente'];
3955	}
3956
3957	$agents_string = implode(',', $result_agents);
3958
3959	$sql = sprintf ("
3960		SELECT talert_template_modules.id
3961		FROM talert_template_modules
3962			INNER JOIN tagente_modulo t2
3963				ON talert_template_modules.id_agent_module = t2.id_agente_modulo
3964			INNER JOIN tagente t3
3965				ON t2.id_agente = t3.id_agente
3966			INNER JOIN talert_templates t4
3967				ON talert_template_modules.id_alert_template = t4.id
3968		WHERE id_agent_module in (%s)", $agents_string);
3969
3970	$alerts = db_get_all_rows_sql($sql);
3971
3972	$total_alerts = count($alerts);
3973	$count_results = 0;
3974	foreach ($alerts as $alert) {
3975		$result = alerts_validate_alert_agent_module($alert['id'], true);
3976
3977		if ($result) {
3978			$count_results++;
3979		}
3980	}
3981
3982	if ($total_alerts > $count_results) {
3983		$errors = $total_alerts - $count_results;
3984		returnError('error_validate_all_alerts', __('Error validate all alerts. Failed ' . $errors . '.'));
3985	}
3986	else {
3987		returnData('string', array('type' => 'string', 'data' => __('Correct validating of all alerts.')));
3988	}
3989}
3990
3991/**
3992 * Validate all policy alerts. And return a message with the result of the operation.
3993 *
3994 * @param string Don't use.
3995 * @param $thrash1 Don't use.
3996 * @param array $other Don't use
3997 *
3998 *  example:
3999 *
4000 * api.php?op=set&op2=validate_all_policy_alerts
4001 *
4002 * @param $thrash3 Don't use
4003 */
4004function api_set_validate_all_policy_alerts($id, $thrash1, $other, $thrash3) {
4005
4006	if (defined ('METACONSOLE')) {
4007		return;
4008	}
4009
4010	# Get all policies
4011	$policies = enterprise_hook('policies_get_policies', array(false, false, false, true));
4012
4013	if ($duplicated === ENTERPRISE_NOT_HOOK) {
4014		returnError('error_validate_all_policy_alerts', __('Error validating all alert policies.'));
4015		return;
4016	}
4017
4018	// Count of valid results
4019	$total_alerts = 0;
4020	$count_results = 0;
4021	// Check all policies
4022	foreach ($policies as $policy) {
4023		$policy_alerts = array();
4024		$policy_alerts = enterprise_hook('policies_get_alerts',  array($policy['id'], false, false));
4025
4026
4027
4028		// Number of alerts in this policy
4029		if ($policy_alerts != false) {
4030			$partial_alerts = count($policy_alerts);
4031			// Added alerts of this policy to the total
4032			$total_alerts = $total_alerts + $partial_alerts;
4033		}
4034
4035		$result_pol_alerts = array();
4036		foreach ($policy_alerts as $policy_alert) {
4037			$result_pol_alerts[] = $policy_alert['id'];
4038		}
4039
4040		$id_pol_alerts = implode(',', $result_pol_alerts);
4041
4042		// If the policy has alerts
4043		if (count($result_pol_alerts) != 0) {
4044			$sql = sprintf ("
4045				SELECT id
4046				FROM talert_template_modules
4047				WHERE id_policy_alerts IN (%s)",
4048				$id_pol_alerts);
4049
4050			$id_alerts = db_get_all_rows_sql($sql);
4051
4052			$result_alerts = array();
4053			foreach ($id_alerts as $id_alert) {
4054				$result_alerts[] = $id_alert['id'];
4055			}
4056
4057			// Validate alerts of these modules
4058			foreach ($result_alerts as $result_alert) {
4059				$result = alerts_validate_alert_agent_module($result_alert, true);
4060
4061				if ($result) {
4062					$count_results++;
4063				}
4064			}
4065		}
4066
4067	}
4068
4069	// Check results
4070	if ($total_alerts > $count_results) {
4071		$errors = $total_alerts - $count_results;
4072		returnError('error_validate_all_alerts', __('Error validate all policy alerts. Failed ' . $errors . '.'));
4073	}
4074	else {
4075		returnData('string', array('type' => 'string', 'data' => __('Correct validating of all policy alerts.')));
4076	}
4077}
4078
4079/**
4080 * Stop a schedule downtime. And return a message with the result of the operation.
4081 *
4082 * @param string $id Id of the downtime to stop.
4083 * @param $thrash1 Don't use.
4084 * @param array $other Don't use
4085 *
4086 *  example:
4087 *
4088 * api.php?op=set&op2=stop_downtime&id=38
4089 *
4090 * @param $thrash3 Don't use
4091 */
4092function api_set_stop_downtime($id, $thrash1, $other, $thrash3) {
4093	if (defined ('METACONSOLE')) {
4094		return;
4095	}
4096
4097	if ($id == "") {
4098		returnError('error_stop_downtime', __('Error stopping downtime. Id_downtime cannot be left blank.'));
4099		return;
4100	}
4101
4102	$date_stop = date ("Y-m-j",get_system_time ());
4103	$time_stop = date ("h:iA",get_system_time ());
4104	$date_time_stop = strtotime ($date_stop.' '.$time_stop);
4105
4106	$values = array();
4107	$values['date_to'] = $date_time_stop;
4108
4109	$result_update = db_process_sql_update('tplanned_downtime', $values, array ('id' => $id));
4110
4111	if ($result_update < 0)
4112		returnError('error_stop_downtime', 'Error stopping downtime.');
4113	else
4114		returnData('string', array('type' => 'string', 'data' => __('Downtime stopped.')));
4115}
4116
4117function api_set_add_tag_module($id, $id2, $thrash1, $thrash2) {
4118	if (defined ('METACONSOLE')) {
4119		return;
4120	}
4121
4122	$id_module = $id;
4123	$id_tag = $id2;
4124
4125	$exists = db_get_row_filter('ttag_module',
4126		array('id_agente_modulo' => $id_module,
4127			'id_tag' => $id_tag));
4128
4129	if (empty($exists)) {
4130		db_process_sql_insert('ttag_module',
4131			array('id_agente_modulo' => $id_module,
4132			'id_tag' => $id_tag));
4133
4134		$exists = db_get_row_filter('ttag_module',
4135			array('id_agente_modulo' => $id_module,
4136				'id_tag' => $id_tag));
4137	}
4138
4139	if (empty($exists))
4140		returnError('error_set_tag_module', 'Error set tag module.');
4141	else
4142		returnData('string',
4143			array('type' => 'string', 'data' => 1));
4144}
4145
4146function api_set_remove_tag_module($id, $id2, $thrash1, $thrash2) {
4147	if (defined ('METACONSOLE')) {
4148		return;
4149	}
4150
4151	$id_module = $id;
4152	$id_tag = $id2;
4153
4154	$row = db_get_row_filter('ttag_module',
4155		array('id_agente_modulo' => $id_module,
4156			'id_tag' => $id_tag));
4157
4158	$correct = 0;
4159
4160	if (!empty($row)) {
4161
4162		// Avoid to delete from policies
4163
4164		if ($row['id_policy_module'] == 0) {
4165			$correct = db_process_sql_delete('ttag_module',
4166				array('id_agente_modulo' => $id_module,
4167					'id_tag' => $id_tag));
4168		}
4169	}
4170
4171	returnData('string',
4172		array('type' => 'string', 'data' => $correct));
4173}
4174
4175function api_set_tag($id, $thrash1, $other, $thrash3) {
4176	if (defined ('METACONSOLE')) {
4177		return;
4178	}
4179
4180	$values = array();
4181	$values['name'] = $id;
4182	$values['description'] = $other['data'][0];
4183	$values['url'] = $other['data'][1];
4184	$values['email'] = $other['data'][2];
4185	$values['phone'] = $other['data'][3];
4186
4187	$id_tag = tags_create_tag($values);
4188
4189	if (empty($id_tag))
4190		returnError('error_set_tag', 'Error set tag.');
4191	else
4192		returnData('string',
4193			array('type' => 'string', 'data' => $id_tag));
4194}
4195
4196/**
4197 * Return all planned downtime.
4198 *
4199 * @param $thrash1 Don't use.
4200 * @param array $other it's array, $other as param is <name>;<id_group>;<type_downtime>;<type_execution>;<type_periodicity>; in this order
4201 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4202 *  example:
4203 *
4204 *  api.php?op=get&op2=all_planned_downtimes&other=test|0|quiet|periodically|weekly&other_mode=url_encode_separator_|&return_type=json
4205 *
4206 * @param type of return json or csv.
4207 */
4208
4209function api_get_all_planned_downtimes ($thrash1, $thrash2, $other, $returnType = 'json') {
4210	if (defined ('METACONSOLE')) {
4211		return;
4212	}
4213
4214	$values = array();
4215	$values = array(
4216		"name LIKE '%".$other['data'][0]."%'"
4217	);
4218
4219	if (isset($other['data'][1]) && ($other['data'][1] != false ))
4220		$values['id_group'] = $other['data'][1];
4221	if (isset($other['data'][2]) && ($other['data'][2] != false))
4222		$values['type_downtime'] = $other['data'][2];
4223	if (isset($other['data'][3]) && ($other['data'][3]!= false) )
4224		$values['type_execution'] = $other['data'][3];
4225	if (isset($other['data'][4]) && ($other['data'][4] != false) )
4226		$values['type_periodicity'] = $other['data'][4];
4227
4228
4229	$returned = all_planned_downtimes($values);
4230
4231	returnData($returnType,
4232			array('type' => 'array', 'data' => $returned));
4233}
4234
4235/**
4236 * Return all items of planned downtime.
4237 *
4238 * @param $id id of planned downtime.
4239 * @param  array $other it's array, $other as param is <name>;<id_group>;<type_downtime>;<type_execution>;<type_periodicity>; in this order
4240 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4241 *
4242 *  example:
4243 *
4244 *   api.php?op=get&op2=planned_downtimes_items&other=test|0|quiet|periodically|weekly&other_mode=url_encode_separator_|&return_type=json
4245 *
4246 * @param type of return json or csv.
4247 */
4248
4249function api_get_planned_downtimes_items ($thrash1, $thrash2, $other, $returnType = 'json') {
4250	if (defined ('METACONSOLE')) {
4251		return;
4252	}
4253
4254	$values = array();
4255	$values = array(
4256		"name LIKE '%".$other['data'][0]."%'"
4257	);
4258
4259	if (isset($other['data'][1]) && ($other['data'][1] != false ))
4260		$values['id_group'] = $other['data'][1];
4261	if (isset($other['data'][2]) && ($other['data'][2] != false))
4262		$values['type_downtime'] = $other['data'][2];
4263	if (isset($other['data'][3]) && ($other['data'][3]!= false) )
4264		$values['type_execution'] = $other['data'][3];
4265	if (isset($other['data'][4]) && ($other['data'][4] != false) )
4266		$values['type_periodicity'] = $other['data'][4];
4267
4268
4269	$returned = all_planned_downtimes($values);
4270
4271	$is_quiet = false;
4272	$return = array('list_index'=>array('id_agents','id_downtime','all_modules'));
4273
4274	foreach ($returned as $downtime) {
4275		if ($downtime['type_downtime'] === 'quiet')
4276			$is_quiet = true;
4277
4278		$filter['id_downtime'] = $downtime['id'];
4279
4280		$return[] = planned_downtimes_items ($filter);
4281	}
4282
4283	if ($is_quiet)
4284		$return['list_index'][] = 'modules';
4285
4286	if ( $returnType == 'json' )
4287		unset($return['list_index']);
4288
4289	returnData($returnType,
4290			array('type' => 'array', 'data' => $return));
4291}
4292
4293/**
4294 * Delete planned downtime.
4295 *
4296 * @param $id id of planned downtime.
4297 * @param $thrash1 not use.
4298 * @param $thrash2 not use.
4299 *
4300 *  api.php?op=set&op2=planned_downtimes_deleted &id=10
4301 *
4302 * @param type of return json or csv.
4303 */
4304
4305function api_set_planned_downtimes_deleted ($id, $thrash1, $thrash2, $returnType) {
4306	if (defined ('METACONSOLE')) {
4307		return;
4308	}
4309
4310	$values = array();
4311	$values = array(
4312		'id_downtime' => $id
4313	);
4314
4315	$returned = delete_planned_downtimes($values);
4316
4317	returnData($returnType,
4318			array('type' => 'string', 'data' => $returned));
4319}
4320
4321/**
4322 * Create a new planned downtime.
4323 *
4324 * @param $id name of planned downtime.
4325 * @param $thrash1 Don't use.
4326 * @param array $other it's array, $other as param is <description>;<date_from>;<date_to>;<id_group>;<monday>;
4327 *  <tuesday>;<wednesday>;<thursday>;<friday>;<saturday>;<sunday>;<periodically_time_from>;<periodically_time_to>;
4328 * 	<periodically_day_from>;<periodically_day_to>;<type_downtime>;<type_execution>;<type_periodicity>; in this order
4329 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4330 *  example:
4331 *
4332 *  api.php?op=set&op2=planned_downtimes_created&id=pepito&other=testing|08-22-2015|08-31-2015|0|1|1|1|1|1|1|1|17:06:00|19:06:00|1|31|quiet|periodically|weekly&other_mode=url_encode_separator_|
4333 *
4334 * @param $thrash3 Don't use.
4335 */
4336
4337function api_set_planned_downtimes_created ($id, $thrash1, $other, $thrash3) {
4338	if (defined ('METACONSOLE')) {
4339		return;
4340	}
4341
4342        $date_from = strtotime(html_entity_decode($other['data'][1]));
4343        $date_to = strtotime(html_entity_decode($other['data'][2]));
4344
4345	$values = array();
4346	$values['name'] = $id;
4347	$values = array(
4348		'name' => $id,
4349		'description' => $other['data'][0],
4350		'date_from' => $date_from,
4351		'date_to' => $date_to,
4352		'id_group' => $other['data'][3],
4353		'monday' => $other['data'][4],
4354		'tuesday' => $other['data'][5],
4355		'wednesday' => $other['data'][6],
4356		'thursday' => $other['data'][7],
4357		'friday' => $other['data'][8],
4358		'saturday' => $other['data'][9],
4359		'sunday' => $other['data'][10],
4360		'periodically_time_from' => $other['data'][11],
4361		'periodically_time_to' => $other['data'][12],
4362		'periodically_day_from' => $other['data'][13],
4363		'periodically_day_to' => $other['data'][14],
4364		'type_downtime' => $other['data'][15],
4365		'type_execution' => $other['data'][16],
4366		'type_periodicity' => $other['data'][17]
4367	);
4368
4369	$returned = planned_downtimes_created($values);
4370
4371	if (!$returned['return'])
4372		returnError('error_set_planned_downtime', $returned['message'] );
4373	else
4374		returnData('string',
4375			array('type' => 'string', 'data' => $returned['return']));
4376}
4377
4378/**
4379 * Add new items to planned Downtime.
4380 *
4381 * @param $id id of planned downtime.
4382 * @param $thrash1 Don't use.
4383 * @param array $other it's array, $other as param is <id_agent1;id_agent2;id_agent3;....id_agentn;>;
4384 * 	<name_module1;name_module2;name_module3;......name_modulen;> in this order
4385 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4386 *  example:
4387 *
4388 *  api.php?op=set&op2=planned_downtimes_additem&id=123&other=1;2;3;4|Status;Unkown_modules&other_mode=url_encode_separator_|
4389 *
4390 * @param $thrash3 Don't use.
4391 */
4392
4393function api_set_planned_downtimes_additem ($id, $thrash1, $other, $thrash3) {
4394	if (defined ('METACONSOLE')) {
4395		return;
4396	}
4397
4398	$total_agents = explode(';',$other['data'][0]);
4399	$agents = $total_agents;
4400	$bad_agents = array();
4401	$i = 0;
4402	foreach ($total_agents as $agent_id) {
4403		$result_agent = (bool) db_get_value ('id_agente', 'tagente', 'id_agente', $agent_id);
4404		if ( !$result_agent ) {
4405			$bad_agents[] = $agent_id;
4406			unset($agents[$i]);
4407		}
4408		$i++;
4409	}
4410
4411	if ( isset($other['data'][1]) )
4412		$name_modules = explode(';',io_safe_output($other['data'][1]));
4413	else
4414		$name_modules = false;
4415
4416	if ($name_modules)
4417		$all_modules = false;
4418	else
4419		$all_modules = true;
4420
4421	if ( !empty($agents) )
4422		$returned = planned_downtimes_add_items($id, $agents, $all_modules, $name_modules);
4423
4424	if ( empty($agents) )
4425		returnError('error_set_planned_downtime_additem', "No agents to create planned downtime items");
4426	else{
4427
4428		if ( !empty($returned['bad_modules']) )
4429			$bad_modules = __("and this modules are doesn't exists or not applicable a this agents: ") . implode(", ",$returned['bad_modules']);
4430		if ( !empty($returned['bad_agents']) )
4431			$bad_agent = __("and this agents are generate problems: ") . implode(", ", $returned['bad_agents']) ;
4432		if ( !empty($bad_agents) )
4433			$agents_no_exists = __("and this agents with ids are doesn't exists: ") . implode(", ", $bad_agents) ;
4434		returnData('string',
4435			array('type' => 'string', 'data' => "Successfully created items " . $bad_agent . " " . $bad_modules . " " . $agents_no_exists));
4436	}
4437}
4438
4439/**
4440 * Add agent to a policy. And return a message with the result of the operation.
4441 *
4442 * @param string $id Id of the target policy.
4443 * @param $thrash1 Don't use.
4444 * @param array $other it's array, $other as param is <id_agent> in this order
4445 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4446 *  example:
4447 *
4448 *  example:
4449 *
4450 * api.php?op=set&op2=add_agent_policy&id=1&other=167&other_mode=url_encode_separator_|
4451 *
4452 * @param $thrash3 Don't use
4453 */
4454function api_set_add_agent_policy($id, $thrash1, $other, $thrash2) {
4455	if (defined ('METACONSOLE')) {
4456		return;
4457	}
4458
4459	if ($id == "") {
4460		returnError('error_add_agent_policy', __('Error adding agent to policy. Id_policy cannot be left blank.'));
4461		return;
4462	}
4463
4464	if ($other['data'][0] == "") {
4465		returnError('error_add_agent_policy', __('Error adding agent to policy. Id_agent cannot be left blank.'));
4466		return;
4467	}
4468
4469	// Check if the agent exists
4470	$result_agent = db_get_value ('id_agente', 'tagente', 'id_agente', (int) $other['data'][0]);
4471
4472	if (!$result_agent) {
4473		returnError('error_add_agent_policy', __('Error adding agent to policy. Id_agent doesn\'t exists.'));
4474		return;
4475	}
4476
4477	// Check if the agent is already in the policy
4478	$id_agent_policy = enterprise_hook('policies_get_agents', array($id, array('id_agent' => $other['data'][0]), 'id'));
4479
4480	if ($id_agent_policy === ENTERPRISE_NOT_HOOK) {
4481		returnError('error_add_agent_policy', __('Error adding agent to policy.'));
4482		return;
4483	}
4484
4485	if ($id_agent_policy === false) {
4486		$success = enterprise_hook('policies_create_agent', array($other['data'][0], $id, true));
4487	}
4488	else {
4489		returnError('error_add_agent_policy', __('Error adding agent to policy. The agent is already in the policy.'));
4490		return;
4491	}
4492
4493	if ($success)
4494		returnData('string', array('type' => 'string', 'data' => $success));
4495	else
4496		returnError('error_add_agent_policy', 'Error adding agent to policy.');
4497}
4498
4499/**
4500 * Add data module to policy. And return id from new module.
4501 *
4502 * @param string $id Id of the target policy.
4503 * @param $thrash1 Don't use.
4504 * @param array $other it's array, $other as param is <module_name>;<id_module_type>;<description>;
4505 * <id_module_group>;<min>;<max>;<post_process>;<module_interval>;<min_warning>;<max_warning>;<str_warning>;
4506 * <min_critical>;<max_critical>;<str_critical>;<history_data>;<configuration_data>;
4507 * <disabled_types_event>;<module_macros>;<ff_threshold>;<each_ff>;<ff_threshold_normal>;
4508 * <ff_threshold_warning>;<ff_threshold_critical>;<ff_timeout> in this order
4509 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4510 *  example:
4511 *
4512 *  example:
4513 *
4514 *  api.php?op=set&op2=add_data_module_policy&id=1&other=data_module_policy_example_name~2~data%20module%20created%20by%20Api~2~0~0~50.00~10~20~180~~21~35~~1~module_begin%0dmodule_name%20pandora_process%0dmodule_type%20generic_data%0dmodule_exec%20ps%20aux%20|%20grep%20pandora%20|%20wc%20-l%0dmodule_end&other_mode=url_encode_separator_~
4515 *
4516 * @param $thrash3 Don't use
4517 */
4518function api_set_add_data_module_policy($id, $thrash1, $other, $thrash3) {
4519	if (defined ('METACONSOLE')) {
4520		return;
4521	}
4522
4523	if ($id == "") {
4524		returnError('error_add_data_module_policy', __('Error adding data module to policy. Id_policy cannot be left blank.'));
4525		return;
4526	}
4527
4528	if ($other['data'][0] == "") {
4529		returnError('error_add_data_module_policy', __('Error adding data module to policy. Module_name cannot be left blank.'));
4530		return;
4531	}
4532
4533	// Check if the module is already in the policy
4534	$name_module_policy = enterprise_hook('policies_get_modules', array($id, array('name'=>$other['data'][0]), 'name'));
4535
4536	if ($name_module_policy === ENTERPRISE_NOT_HOOK) {
4537		returnError('error_add_data_module_policy', __('Error adding data module to policy.'));
4538		return;
4539	}
4540
4541	$disabled_types_event = array();
4542	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][16];
4543	$disabled_types_event = json_encode($disabled_types_event);
4544
4545	$values = array();
4546	$values['id_tipo_modulo'] = $other['data'][1];
4547	$values['description'] = $other['data'][2];
4548	$values['id_module_group'] = $other['data'][3];
4549	$values['min'] = $other['data'][4];
4550	$values['max'] = $other['data'][5];
4551	$values['post_process'] = $other['data'][6];
4552	$values['module_interval'] = $other['data'][7];
4553	$values['min_warning'] = $other['data'][8];
4554	$values['max_warning'] = $other['data'][9];
4555	$values['str_warning'] = $other['data'][10];
4556	$values['min_critical'] = $other['data'][11];
4557	$values['max_critical'] = $other['data'][12];
4558	$values['str_critical'] = $other['data'][13];
4559	$values['history_data'] = $other['data'][14];
4560	$values['configuration_data'] = $other['data'][15];
4561	$values['disabled_types_event'] = $disabled_types_event;
4562	$values['module_macros'] = $other['data'][17];
4563	$values['min_ff_event'] = $other['data'][18];
4564	$values['each_ff'] = $other['data'][19];
4565	$values['min_ff_event_normal'] = $other['data'][20];
4566	$values['min_ff_event_warning'] = $other['data'][21];
4567	$values['min_ff_event_critical'] = $other['data'][22];
4568	$values['ff_timeout'] = $other['data'][23];
4569
4570	if ($name_module_policy !== false) {
4571		if ($name_module_policy[0]['name'] == $other['data'][0]) {
4572			returnError('error_add_data_module_policy',
4573				__('Error adding data module to policy. The module is already in the policy.'));
4574			return;
4575		}
4576	}
4577
4578	$success = enterprise_hook('policies_create_module',
4579		array($other['data'][0], $id, 1, $values, false));
4580
4581	if ($success)
4582		//returnData('string', array('type' => 'string', 'data' => __('Data module added to policy. Is necessary to apply the policy in order to changes take effect.')));
4583		returnData('string', array('type' => 'string', 'data' => $success));
4584	else
4585		returnError('error_add_data_module_policy', 'Error adding data module to policy.');
4586
4587}
4588
4589/**
4590 * Update data module in policy. And return id from new module.
4591 *
4592 * @param string $id Id of the target policy module.
4593 * @param $thrash1 Don't use.
4594 * @param array $other it's array, $other as param is <id_policy_module>;<description>;
4595 * <id_module_group>;<min>;<max>;<post_process>;<module_interval>;<min_warning>;<max_warning>;<str_warning>;
4596 * <min_critical>;<max_critical>;<str_critical>;<history_data>;<configuration_data>;
4597 * <disabled_types_event>;<module_macros> in this order
4598 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4599 *  example:
4600 *
4601 *  example:
4602 *
4603 *  api.php?op=set&op2=update_data_module_policy&id=1&other=10~data%20module%20updated%20by%20Api~2~0~0~50.00~10~20~180~~21~35~~1~module_begin%0dmodule_name%20pandora_process%0dmodule_type%20generic_data%0dmodule_exec%20ps%20aux%20|%20grep%20pandora%20|%20wc%20-l%0dmodule_end&other_mode=url_encode_separator_~
4604 *
4605 * @param $thrash3 Don't use
4606 */
4607function api_set_update_data_module_policy($id, $thrash1, $other, $thrash3) {
4608	if (defined ('METACONSOLE')) {
4609		return;
4610	}
4611
4612	if ($id == "") {
4613		returnError('error_update_data_module_policy', __('Error updating data module in policy. Id_policy cannot be left blank.'));
4614		return;
4615	}
4616
4617	if ($other['data'][0] == "") {
4618		returnError('error_update_data_module_policy', __('Error updating data module in policy. Id_policy_module cannot be left blank.'));
4619		return;
4620	}
4621
4622	// Check if the module exists
4623	$module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module'));
4624
4625	if ($module_policy === false) {
4626		returnError('error_update_data_module_policy', __('Error updating data module in policy. Module doesn\'t exists.'));
4627		return;
4628	}
4629
4630	if ($module_policy[0]['id_module'] != 1) {
4631		returnError('error_update_data_module_policy',
4632			__('Error updating data module in policy. Module type is not network type.'));
4633		return;
4634	}
4635
4636	$fields_data_module = array(
4637		'id','description', 'id_module_group', 'min', 'max',
4638		'post_process', 'module_interval', 'min_warning', 'max_warning',
4639		'str_warning', 'min_critical', 'max_critical', 'str_critical',
4640		'history_data', 'configuration_data', 'disabled_types_event',
4641		'module_macros');
4642
4643	$cont = 0;
4644	foreach ($fields_data_module as $field) {
4645		if ($other['data'][$cont] != "" and $field != 'id') {
4646			$values[$field] = $other['data'][$cont];
4647		}
4648
4649		$cont++;
4650	}
4651
4652
4653	$result_update = enterprise_hook('policies_update_module',
4654		array($other['data'][0], $values, false));
4655
4656
4657	if ($result_update < 0)
4658		returnError('error_update_data_module_policy', 'Error updating policy module.');
4659	else
4660		returnData('string',
4661			array('type' => 'string', 'data' => __('Data policy module updated.')));
4662}
4663
4664/**
4665 * Add network module to policy. And return a result message.
4666 *
4667 * @param string $id Id of the target policy.
4668 * @param $thrash1 Don't use.
4669 * @param array $other it's array, $other as param is <module_name>;<id_module_type>;<description>;
4670 * <id_module_group>;<min>;<max>;<post_process>;<module_interval>;<min_warning>;<max_warning>;<str_warning>;
4671 * <min_critical>;<max_critical>;<str_critical>;<history_data>;<time_threshold>;<disabled>;<module_port>;
4672 * <snmp_community>;<snmp_oid>;<custom_id>;<disabled_types_event>;<module_macros>;
4673 * <each_ff>;<ff_threshold_normal>;<ff_threshold_warning>;<ff_threshold_critical> in this order
4674 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4675 *  example:
4676 *
4677 *  example:
4678 *
4679 *  api.php?op=set&op2=add_network_module_policy&id=1&other=network_module_policy_example_name|6|network%20module%20created%20by%20Api|2|0|0|50.00|180|10|20||21|35||1|15|0|66|||0&other_mode=url_encode_separator_|
4680 *
4681 * @param $thrash3 Don't use
4682 */
4683function api_set_add_network_module_policy($id, $thrash1, $other, $thrash3) {
4684	if (defined ('METACONSOLE')) {
4685		return;
4686	}
4687
4688	if ($id == "") {
4689		returnError('error_network_data_module_policy',
4690			__('Error adding network module to policy. Id_policy cannot be left blank.'));
4691		return;
4692	}
4693
4694	if ($other['data'][0] == "") {
4695		returnError('error_network_data_module_policy',
4696			__('Error adding network module to policy. Module_name cannot be left blank.'));
4697		return;
4698	}
4699
4700	if ($other['data'][1] < 6 or $other['data'][1] > 18) {
4701		returnError('error_network_data_module_policy',
4702			__('Error adding network module to policy. Id_module_type is not correct for network modules.'));
4703		return;
4704	}
4705
4706	// Check if the module is already in the policy
4707	$name_module_policy = enterprise_hook('policies_get_modules',
4708		array($id, array('name'=>$other['data'][0]), 'name'));
4709
4710	if ($name_module_policy === ENTERPRISE_NOT_HOOK) {
4711		returnError('error_network_data_module_policy',
4712			__('Error adding network module to policy.'));
4713		return;
4714	}
4715
4716	$disabled_types_event = array();
4717	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][21];
4718	$disabled_types_event = json_encode($disabled_types_event);
4719
4720	$values = array();
4721	$values['id_tipo_modulo'] = $other['data'][1];
4722	$values['description'] = $other['data'][2];
4723	$values['id_module_group'] = $other['data'][3];
4724	$values['min'] = $other['data'][4];
4725	$values['max'] = $other['data'][5];
4726	$values['post_process'] = $other['data'][6];
4727	$values['module_interval'] = $other['data'][7];
4728	$values['min_warning'] = $other['data'][8];
4729	$values['max_warning'] = $other['data'][9];
4730	$values['str_warning'] = $other['data'][10];
4731	$values['min_critical'] = $other['data'][11];
4732	$values['max_critical'] = $other['data'][12];
4733	$values['str_critical'] = $other['data'][13];
4734	$values['history_data'] = $other['data'][14];
4735	$values['min_ff_event'] = $other['data'][15];
4736	$values['disabled'] = $other['data'][16];
4737	$values['tcp_port'] = $other['data'][17];
4738	$values['snmp_community'] = $other['data'][18];
4739	$values['snmp_oid'] = $other['data'][19];
4740	$values['custom_id'] = $other['data'][20];
4741	$values['disabled_types_event'] = $disabled_types_event;
4742	$values['module_macros'] = $other['data'][22];
4743	$values['each_ff'] = $other['data'][23];
4744	$values['min_ff_event_normal'] = $other['data'][24];
4745	$values['min_ff_event_warning'] = $other['data'][25];
4746	$values['min_ff_event_critical'] = $other['data'][26];
4747
4748	if ($name_module_policy !== false) {
4749		if ($name_module_policy[0]['name'] == $other['data'][0]) {
4750			returnError('error_network_data_module_policy', __('Error adding network module to policy. The module is already in the policy.'));
4751			return;
4752		}
4753	}
4754
4755	$success = enterprise_hook('policies_create_module', array($other['data'][0], $id, 2, $values, false));
4756
4757	if ($success)
4758		returnData('string', array('type' => 'string', 'data' => $success));
4759	else
4760		returnError('error_add_network_module_policy', 'Error adding network module to policy.');
4761}
4762
4763/**
4764 * Update network module in policy. And return a result message.
4765 *
4766 * @param string $id Id of the target policy module.
4767 * @param $thrash1 Don't use.
4768 * @param array $other it's array, $other as param is <id_policy_module>;<description>;
4769 * <id_module_group>;<min>;<max>;<post_process>;<module_interval>;<min_warning>;<max_warning>;<str_warning>;
4770 * <min_critical>;<max_critical>;<str_critical>;<history_data>;<time_threshold>;<disabled>;<module_port>;
4771 * <snmp_community>;<snmp_oid>;<custom_id>;<disabled_types_event>;<module_macros> in this order
4772 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4773 *  example:
4774 *
4775 *  example:
4776 *
4777 *  api.php?op=set&op2=update_network_module_policy&id=1&other=14|network%20module%20updated%20by%20Api|2|0|0|150.00|300|10|20||21|35||1|15|0|66|||0&other_mode=url_encode_separator_|
4778 *
4779 * @param $thrash3 Don't use
4780 */
4781function api_set_update_network_module_policy($id, $thrash1, $other, $thrash3) {
4782	if (defined ('METACONSOLE')) {
4783		return;
4784	}
4785
4786	if ($id == "") {
4787		returnError('error_update_network_module_policy',
4788			__('Error updating network module in policy. Id_policy cannot be left blank.'));
4789		return;
4790	}
4791
4792	if ($other['data'][0] == "") {
4793		returnError('error_update_network_module_policy',
4794			__('Error updating network module in policy. Id_policy_module cannot be left blank.'));
4795		return;
4796	}
4797
4798	// Check if the module exists
4799	$module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module'));
4800
4801	if ($module_policy === false) {
4802		returnError('error_update_network_module_policy',
4803			__('Error updating network module in policy. Module doesn\'t exists.'));
4804		return;
4805	}
4806
4807	if ($module_policy[0]['id_module'] != 2) {
4808		returnError('error_update_network_module_policy',
4809			__('Error updating network module in policy. Module type is not network type.'));
4810		return;
4811	}
4812
4813	$fields_network_module = array('id','description',
4814		'id_module_group', 'min', 'max', 'post_process',
4815		'module_interval', 'min_warning', 'max_warning', 'str_warning',
4816		'min_critical', 'max_critical', 'str_critical', 'history_data',
4817		'min_ff_event', 'disabled', 'tcp_port', 'snmp_community',
4818		'snmp_oid', 'custom_id', 'disabled_types_event', 'module_macros');
4819
4820	$cont = 0;
4821	foreach ($fields_network_module as $field) {
4822		if ($other['data'][$cont] != "" and $field != 'id') {
4823			$values[$field] = $other['data'][$cont];
4824		}
4825
4826		$cont++;
4827	}
4828
4829	$result_update = enterprise_hook('policies_update_module', array($other['data'][0], $values, false));
4830
4831
4832	if ($result_update < 0)
4833		returnError('error_update_network_module_policy', 'Error updating policy module.');
4834	else
4835		returnData('string', array('type' => 'string', 'data' => __('Network policy module updated.')));
4836}
4837
4838/**
4839 * Add plugin module to policy. And return id from new module.
4840 *
4841 * @param string $id Id of the target policy.
4842 * @param $thrash1 Don't use.
4843 * @param array $other it's array, $other as param is <name_module>;<disabled>;<id_module_type>;
4844 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
4845 *  <history_data>;<module_port>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
4846 *  <min>;<max>;<custom_id>;<description>;<id_plugin>;<plugin_user>;<plugin_pass>;<plugin_parameter>;
4847 *  <disabled_types_event>;<macros>;<module_macros>;<each_ff>;<ff_threshold_normal>;
4848 *  <ff_threshold_warning>;<ff_threshold_critical> in this order
4849 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4850 *  example:
4851 *
4852 *  api.php?op=set&op2=add_plugin_module_policy&id=1&other=example%20plugin%20module%20name|0|1|2|0|0||0|0||15|0|66|||300|50.00|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_|
4853 *
4854 * @param $thrash3 Don't use
4855 */
4856function api_set_add_plugin_module_policy($id, $thrash1, $other, $thrash3) {
4857	if (defined ('METACONSOLE')) {
4858		return;
4859	}
4860
4861	if ($id == "") {
4862		returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Id_policy cannot be left blank.'));
4863		return;
4864	}
4865
4866	if ($other['data'][0] == "") {
4867		returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Module_name cannot be left blank.'));
4868		return;
4869	}
4870
4871	if ($other['data'][22] == "") {
4872		returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Id_plugin cannot be left blank.'));
4873		return;
4874	}
4875
4876	// Check if the module is already in the policy
4877	$name_module_policy = enterprise_hook('policies_get_modules', array($id, array('name'=>$other['data'][0]), 'name'));
4878
4879	if ($name_module_policy === ENTERPRISE_NOT_HOOK) {
4880		returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy.'));
4881		return;
4882	}
4883
4884	$disabled_types_event = array();
4885	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][25];
4886	$disabled_types_event = json_encode($disabled_types_event);
4887
4888	$values = array();
4889	$values['disabled'] = $other['data'][1];
4890	$values['id_tipo_modulo'] = $other['data'][2];
4891	$values['id_module_group'] = $other['data'][3];
4892	$values['min_warning'] = $other['data'][4];
4893	$values['max_warning'] = $other['data'][5];
4894	$values['str_warning'] = $other['data'][6];
4895	$values['min_critical'] = $other['data'][7];
4896	$values['max_critical'] = $other['data'][8];
4897	$values['str_critical'] = $other['data'][9];
4898	$values['min_ff_event'] = $other['data'][10];
4899	$values['history_data'] = $other['data'][11];
4900	$values['tcp_port'] = $other['data'][12];
4901	$values['snmp_community'] = $other['data'][13];
4902	$values['snmp_oid'] = $other['data'][14];
4903	$values['module_interval'] = $other['data'][15];
4904	$values['post_process'] = $other['data'][16];
4905	$values['min'] = $other['data'][17];
4906	$values['max'] = $other['data'][18];
4907	$values['custom_id'] = $other['data'][19];
4908	$values['description'] = $other['data'][20];
4909	$values['id_plugin'] = $other['data'][21];
4910	$values['plugin_user'] = $other['data'][22];
4911	$values['plugin_pass'] = $other['data'][23];
4912	$values['plugin_parameter'] = $other['data'][24];
4913	$values['disabled_types_event'] = $disabled_types_event;
4914	$values['macros'] = base64_decode ($other['data'][26]);
4915	$values['module_macros'] = $other['data'][27];
4916	$values['each_ff'] = $other['data'][28];
4917	$values['min_ff_event_normal'] = $other['data'][29];
4918	$values['min_ff_event_warning'] = $other['data'][30];
4919	$values['min_ff_event_critical'] = $other['data'][31];
4920
4921	if ($name_module_policy !== false) {
4922		if ($name_module_policy[0]['name'] == $other['data'][0]) {
4923			returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. The module is already in the policy.'));
4924			return;
4925		}
4926	}
4927
4928	$success = enterprise_hook('policies_create_module', array($other['data'][0], $id, 4, $values, false));
4929
4930	if ($success)
4931		returnData('string', array('type' => 'string', 'data' => $success));
4932	else
4933		returnError('error_add_plugin_module_policy', 'Error adding plugin module to policy.');
4934}
4935
4936/**
4937 * Update plugin module in policy. And return a result message.
4938 *
4939 * @param string $id Id of the target policy module.
4940 * @param $thrash1 Don't use.
4941 * @param array $other it's array, $other as param is <id_policy_module>;<disabled>;
4942 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
4943 *  <history_data>;<module_port>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
4944 *  <min>;<max>;<custom_id>;<description>;<id_plugin>;<plugin_user>;<plugin_pass>;<plugin_parameter>;
4945 *  <disabled_types_event>;<macros>;<module_macros> in this order
4946 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
4947 *  example:
4948 *
4949 *  example:
4950 *
4951 *  api.php?op=set&op2=update_plugin_module_policy&id=1&other=23|0|1|0|0||0|0||15|0|166|||180|150.00|0|0|0|plugin%20module%20updated%20from%20api|2|example_user|pass|-p%20min&other_mode=url_encode_separator_|
4952 *
4953 * @param $thrash3 Don't use
4954 */
4955function api_set_update_plugin_module_policy($id, $thrash1, $other, $thrash3) {
4956	if (defined ('METACONSOLE')) {
4957		return;
4958	}
4959
4960	if ($id == "") {
4961		returnError('error_update_plugin_module_policy',
4962			__('Error updating plugin module in policy. Id_policy cannot be left blank.'));
4963		return;
4964	}
4965
4966	if ($other['data'][0] == "") {
4967		returnError('error_update_plugin_module_policy',
4968			__('Error updating plugin module in policy. Id_policy_module cannot be left blank.'));
4969		return;
4970	}
4971
4972	// Check if the module exists
4973	$module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module'));
4974
4975	if ($module_policy === false) {
4976		returnError('error_updating_plugin_module_policy',
4977			__('Error updating plugin module in policy. Module doesn\'t exists.'));
4978		return;
4979	}
4980
4981	if ($module_policy[0]['id_module'] != 4) {
4982		returnError('error_updating_plugin_module_policy',
4983			__('Error updating plugin module in policy. Module type is not network type.'));
4984		return;
4985	}
4986
4987	$fields_plugin_module = array('id','disabled', 'id_module_group',
4988		'min_warning', 'max_warning', 'str_warning', 'min_critical',
4989		'max_critical', 'str_critical', 'min_ff_event', 'history_data',
4990		'tcp_port', 'snmp_community', 'snmp_oid', 'module_interval',
4991		'post_process', 'min', 'max', 'custom_id', 'description',
4992		'id_plugin', 'plugin_user', 'plugin_pass', 'plugin_parameter',
4993		'disabled_types_event', 'macros', 'module_macros');
4994
4995	$cont = 0;
4996	foreach ($fields_plugin_module as $field) {
4997		if ($other['data'][$cont] != "" and $field != 'id') {
4998			$values[$field] = $other['data'][$cont];
4999
5000			if( $field === 'macros' ) {
5001				$values[$field] = base64_decode($values[$field]);
5002			}
5003		}
5004
5005		$cont++;
5006	}
5007
5008	$result_update = enterprise_hook('policies_update_module',
5009		array($other['data'][0], $values, false));
5010
5011
5012	if ($result_update < 0)
5013		returnError('error_update_plugin_module_policy', 'Error updating policy module.');
5014	else
5015		returnData('string', array('type' => 'string', 'data' => __('Plugin policy module updated.')));
5016}
5017
5018/**
5019 * Add module data configuration into agent configuration file
5020 *
5021 * @param string $id_agent Id of the agent
5022 * @param string $module_name
5023 * @param array $configuration_data is an array. The data in it is the new configuration data of the module
5024 * @param $thrash3 Don't use
5025 *
5026 * Call example:
5027 *
5028 *  api.php?op=set&op2=add_module_in_conf&user=admin&pass=pandora&id=9043&id2=example_name&other=bW9kdWxlX2JlZ2luCm1vZHVsZV9uYW1lIGV4YW1wbGVfbmFtZQptb2R1bGVfdHlwZSBnZW5lcmljX2RhdGEKbW9kdWxlX2V4ZWMgZWNobyAxOwptb2R1bGVfZW5k
5029 *
5030 * @return string 0 when success, -1 when error, -2 if already exist
5031 */
5032function api_set_add_module_in_conf($id_agent, $module_name, $configuration_data, $thrash3) {
5033	if (defined ('METACONSOLE')) {
5034		return;
5035	}
5036
5037	$new_configuration_data = io_safe_output(urldecode($configuration_data['data']));
5038
5039	// Check if exist a current module with the same name in the conf file
5040	$old_configuration_data = config_agents_get_module_from_conf($id_agent, io_safe_output($module_name));
5041
5042	// If exists a module with same name, abort
5043	if(!empty($old_configuration_data)) {
5044		returnError('error_adding_module_conf', '-2');
5045		exit;
5046	}
5047
5048	$result = enterprise_hook('config_agents_add_module_in_conf', array($id_agent, $new_configuration_data));
5049
5050	if($result && $result !== ENTERPRISE_NOT_HOOK) {
5051		returnData('string', array('type' => 'string', 'data' => '0'));
5052	}
5053	else {
5054		returnError('error_adding_module_conf', '-1');
5055	}
5056}
5057
5058
5059/**
5060 * Get module data configuration from agent configuration file
5061 *
5062 * @param string $id_agent Id of the agent
5063 * @param string $module_name
5064 * @param $thrash2 Don't use
5065 * @param $thrash3 Don't use
5066 *
5067 * Call example:
5068 *
5069 *  api.php?op=get&op2=module_from_conf&user=admin&pass=pandora&id=9043&id2=example_name
5070 *
5071 * @return string Module data when success, empty when error
5072 */
5073function api_get_module_from_conf($id_agent, $module_name, $thrash2, $thrash3) {
5074	if (defined ('METACONSOLE')) {
5075		return;
5076	}
5077
5078	$result = enterprise_hook('config_agents_get_module_from_conf',
5079		array($id_agent, io_safe_output($module_name)));
5080
5081	if ($result !== ENTERPRISE_NOT_HOOK) {
5082		returnData('string', array('type' => 'string', 'data' => $result));
5083	}
5084	else {
5085		returnError('error_adding_module_conf', '');
5086	}
5087}
5088
5089/**
5090 * Delete module data configuration from agent configuration file
5091 *
5092 * @param string $id_agent Id of the agent
5093 * @param string $module_name
5094 * @param $thrash2 Don't use
5095 * @param $thrash3 Don't use
5096 *
5097 * Call example:
5098 *
5099 *  api.php?op=set&op2=delete_module_in_conf&user=admin&pass=pandora&id=9043&id2=example_name
5100 *
5101 * @return string 0 when success, -1 when error
5102 */
5103function api_set_delete_module_in_conf($id_agent, $module_name, $thrash2, $thrash3) {
5104	if (defined ('METACONSOLE')) {
5105		return;
5106	}
5107
5108	$result = config_agents_delete_module_in_conf($id_agent, $module_name);
5109
5110	$result = enterprise_hook('config_agents_delete_module_in_conf', array($id_agent, $module_name));
5111
5112	if($result && $result !== ENTERPRISE_NOT_HOOK) {
5113		returnData('string', array('type' => 'string', 'data' => '0'));
5114	}
5115	else {
5116		returnError('error_deleting_module_conf', '-1');
5117	}
5118}
5119
5120/**
5121 * Update module data configuration from agent configuration file
5122 *
5123 * @param string $id_agent Id of the agent
5124 * @param string $module_name
5125 * @param array $configuration_data is an array. The data in it is the new configuration data of the module
5126 * @param $thrash3 Don't use
5127 *
5128 * Call example:
5129 *
5130 *  api.php?op=set&op2=update_module_in_conf&user=admin&pass=pandora&id=9043&id2=example_name&other=bW9kdWxlX2JlZ2luCm1vZHVsZV9uYW1lIGV4YW1wbGVfbmFtZQptb2R1bGVfdHlwZSBnZW5lcmljX2RhdGEKbW9kdWxlX2V4ZWMgZWNobyAxOwptb2R1bGVfZW5k
5131 *
5132 * @return string 0 when success, 1 when no changes, -1 when error, -2 if doesnt exist
5133 */
5134function api_set_update_module_in_conf($id_agent, $module_name, $configuration_data_serialized, $thrash3) {
5135	if (defined ('METACONSOLE')) {
5136		return;
5137	}
5138
5139	$new_configuration_data = io_safe_output(urldecode($configuration_data_serialized['data']));
5140
5141	// Get current configuration
5142	$old_configuration_data = config_agents_get_module_from_conf($id_agent, io_safe_output($module_name));
5143
5144	// If not exists
5145	if(empty($old_configuration_data)) {
5146		returnError('error_editing_module_conf', '-2');
5147		exit;
5148	}
5149
5150	// If current configuration and new configuration are equal, abort
5151	if ($new_configuration_data == $old_configuration_data) {
5152		returnData('string', array('type' => 'string', 'data' => '1'));
5153		exit;
5154	}
5155
5156	$result = enterprise_hook('config_agents_update_module_in_conf', array($id_agent, $old_configuration_data, $new_configuration_data));
5157
5158	if($result && $result !== ENTERPRISE_NOT_HOOK) {
5159		returnData('string', array('type' => 'string', 'data' => '0'));
5160	}
5161	else {
5162		returnError('error_editing_module_conf', '-1');
5163	}
5164}
5165
5166/**
5167 * Add SNMP module to policy. And return id from new module.
5168 *
5169 * @param string $id Id of the target policy.
5170 * @param $thrash1 Don't use.
5171 * @param array $other it's array, $other as param is <name_module>;<disabled>;<id_module_type>;
5172 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
5173 *  <history_data>;<module_port>;<snmp_version>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
5174 *  <min>;<max>;<custom_id>;<description>;<snmp3_priv_method>;<snmp3_priv_pass>;<snmp3_sec_level>;<snmp3_auth_method>;
5175 *  <snmp3_auth_user>;<snmp3_auth_pass>;<disabled_types_event>;;<each_ff>;<ff_threshold_normal>;
5176 *  <ff_threshold_warning>;<ff_threshold_critical> in this order
5177 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5178 *  example:
5179 *
5180 *  api.php?op=set&op2=add_snmp_module_policy&id=1&other=example%20SNMP%20module%20name|0|15|2|0|0||0|0||15|1|66|3|public|.1.3.6.1.2.1.1.1.0|180|50.00|10|60|0|SNMP%20module%20modified%20by%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_|
5181 *
5182 * @param $thrash3 Don't use
5183 */
5184function api_set_add_snmp_module_policy($id, $thrash1, $other, $thrash3) {
5185	if (defined ('METACONSOLE')) {
5186		return;
5187	}
5188
5189	if ($id == "") {
5190		returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Id_policy cannot be left blank.'));
5191		return;
5192	}
5193
5194	if ($other['data'][0] == "") {
5195		returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Module_name cannot be left blank.'));
5196		return;
5197	}
5198
5199	// Check if the module is already in the policy
5200	$name_module_policy = enterprise_hook('policies_get_modules', array($id, array('name'=>$other['data'][0]), 'name'));
5201
5202	if ($name_module_policy === ENTERPRISE_NOT_HOOK) {
5203		returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy.'));
5204		return;
5205	}
5206
5207	if ($other['data'][2] < 15 or $other['data'][2] > 18) {
5208		returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Id_module_type is not correct for SNMP modules.'));
5209		return;
5210	}
5211
5212	$disabled_types_event = array();
5213	$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][28];
5214	$disabled_types_event = json_encode($disabled_types_event);
5215
5216	# SNMP version 3
5217	if ($other['data'][13] == "3") {
5218
5219		if ($other['data'][22] != "AES" and $other['data'][22] != "DES") {
5220			returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_priv_method doesn\'t exists. Set it to \'AES\' or \'DES\'. '));
5221			return;
5222		}
5223
5224		if ($other['data'][24] != "authNoPriv" and $other['data'][24] != "authPriv" and $other['data'][24] != "noAuthNoPriv") {
5225			returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_sec_level doesn\'t exists. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. '));
5226			return;
5227		}
5228
5229		if ($other['data'][25] != "MD5" and $other['data'][25] != "SHA") {
5230			returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_auth_method doesn\'t exists. Set it to \'MD5\' or \'SHA\'. '));
5231			return;
5232		}
5233
5234		$values = array(
5235			'disabled' => $other['data'][1],
5236			'id_tipo_modulo' => $other['data'][2],
5237			'id_module_group' => $other['data'][3],
5238			'min_warning' => $other['data'][4],
5239			'max_warning' => $other['data'][5],
5240			'str_warning' => $other['data'][6],
5241			'min_critical' => $other['data'][7],
5242			'max_critical' => $other['data'][8],
5243			'str_critical' => $other['data'][9],
5244			'min_ff_event' => $other['data'][10],
5245			'history_data' => $other['data'][11],
5246			'tcp_port' => $other['data'][12],
5247			'tcp_send' => $other['data'][13],
5248			'snmp_community' => $other['data'][14],
5249			'snmp_oid' => $other['data'][15],
5250			'module_interval' => $other['data'][16],
5251			'post_process' => $other['data'][17],
5252			'min' => $other['data'][18],
5253			'max' => $other['data'][19],
5254			'custom_id' => $other['data'][20],
5255			'description' => $other['data'][21],
5256			'custom_string_1' => $other['data'][22],
5257			'custom_string_2' => $other['data'][23],
5258			'custom_string_3' => $other['data'][24],
5259			'plugin_parameter' => $other['data'][25],
5260			'plugin_user' => $other['data'][26],
5261			'plugin_pass' => $other['data'][27],
5262			'disabled_types_event' => $disabled_types_event,
5263			'each_ff' => $other['data'][29],
5264			'min_ff_event_normal' => $other['data'][30],
5265			'min_ff_event_warning' => $other['data'][31],
5266			'min_ff_event_critical' => $other['data'][32]
5267		);
5268	}
5269	else {
5270		$values = array(
5271			'disabled' => $other['data'][1],
5272			'id_tipo_modulo' => $other['data'][2],
5273			'id_module_group' => $other['data'][3],
5274			'min_warning' => $other['data'][4],
5275			'max_warning' => $other['data'][5],
5276			'str_warning' => $other['data'][6],
5277			'min_critical' => $other['data'][7],
5278			'max_critical' => $other['data'][8],
5279			'str_critical' => $other['data'][9],
5280			'min_ff_event' => $other['data'][10],
5281			'history_data' => $other['data'][11],
5282			'tcp_port' => $other['data'][12],
5283			'tcp_send' => $other['data'][13],
5284			'snmp_community' => $other['data'][14],
5285			'snmp_oid' => $other['data'][15],
5286			'module_interval' => $other['data'][16],
5287			'post_process' => $other['data'][17],
5288			'min' => $other['data'][18],
5289			'max' => $other['data'][19],
5290			'custom_id' => $other['data'][20],
5291			'description' => $other['data'][21],
5292			'disabled_types_event' => $disabled_types_event,
5293			'each_ff' => $other['data'][23],
5294			'min_ff_event_normal' => $other['data'][24],
5295			'min_ff_event_warning' => $other['data'][25],
5296			'min_ff_event_critical' => $other['data'][26]
5297		);
5298	}
5299
5300	if ($name_module_policy !== false) {
5301		if ($name_module_policy[0]['name'] == $other['data'][0]) {
5302			returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. The module is already in the policy.'));
5303			return;
5304		}
5305	}
5306
5307	$success = enterprise_hook('policies_create_module', array($other['data'][0], $id, 2, $values, false));
5308
5309	if ($success)
5310		returnData('string', array('type' => 'string', 'data' => $success));
5311	else
5312		returnError('error_add_snmp_module_policy', 'Error adding SNMP module to policy.');
5313
5314}
5315
5316/**
5317 * Update SNMP module in policy. And return a result message.
5318 *
5319 * @param string $id Id of the target policy module.
5320 * @param $thrash1 Don't use.
5321 * @param array $other it's array, $other as param is <id_policy_module>;<disabled>;
5322 *  <id_module_group>;<min_warning>;<max_warning>;<str_warning>;<min_critical>;<max_critical>;<str_critical>;<ff_threshold>;
5323 *  <history_data>;<module_port>;<snmp_version>;<snmp_community>;<snmp_oid>;<module_interval>;<post_process>;
5324 *  <min>;<max>;<custom_id>;<description>;<snmp3_priv_method>;<snmp3_priv_pass>;<snmp3_sec_level>;<snmp3_auth_method>;
5325 *  <snmp3_auth_user>;<snmp3_auth_pass> in this order
5326 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5327 *  example:
5328 *
5329 *  example:
5330 *
5331 *  api.php?op=set&op2=update_snmp_module_policy&id=1&other=14|0|2|0|0||0|0||30|1|66|3|nonpublic|.1.3.6.1.2.1.1.1.0|300|150.00|10|60|0|SNMP%20module%20updated%20by%20API|DES|example_priv_passw|authPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_|
5332 *
5333 * @param $thrash3 Don't use
5334 */
5335function api_set_update_snmp_module_policy($id, $thrash1, $other, $thrash3) {
5336	if (defined ('METACONSOLE')) {
5337		return;
5338	}
5339
5340	if ($id == "") {
5341		returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Id_policy cannot be left blank.'));
5342		return;
5343	}
5344
5345	if ($other['data'][0] == "") {
5346		returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Id_policy_module cannot be left blank.'));
5347		return;
5348	}
5349
5350	// Check if the module exists
5351	$module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module'));
5352
5353	if ($module_policy === false) {
5354		returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Module doesn\'t exists.'));
5355		return;
5356	}
5357
5358	if ($module_policy[0]['id_module'] != 2) {
5359		returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Module type is not SNMP type.'));
5360		return;
5361	}
5362
5363
5364	# SNMP version 3
5365	if ($other['data'][12] == "3") {
5366
5367		if ($other['data'][21] != "AES" and $other['data'][21] != "DES") {
5368			returnError('error_update_snmp_module_policy',
5369				__('Error updating SNMP module. snmp3_priv_method doesn\'t exists. Set it to \'AES\' or \'DES\'. '));
5370
5371			return;
5372		}
5373
5374		if ($other['data'][23] != "authNoPriv"
5375			and $other['data'][23] != "authPriv"
5376			and $other['data'][23] != "noAuthNoPriv") {
5377
5378			returnError('error_update_snmp_module_policy',
5379				__('Error updating SNMP module. snmp3_sec_level doesn\'t exists. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. '));
5380
5381			return;
5382		}
5383
5384		if ($other['data'][24] != "MD5" and $other['data'][24] != "SHA") {
5385			returnError('error_update_snmp_module_policy',
5386				__('Error updating SNMP module. snmp3_auth_method doesn\'t exists. Set it to \'MD5\' or \'SHA\'. '));
5387
5388			return;
5389		}
5390
5391		$fields_snmp_module = array('id','disabled', 'id_module_group',
5392			'min_warning', 'max_warning', 'str_warning', 'min_critical',
5393			'max_critical', 'str_critical', 'min_ff_event',
5394			'history_data', 'tcp_port', 'tcp_send', 'snmp_community',
5395			'snmp_oid', 'module_interval', 'post_process', 'min', 'max',
5396			'custom_id', 'description', 'custom_string_1',
5397			'custom_string_2', 'custom_string_3', 'plugin_parameter',
5398			'plugin_user', 'plugin_pass');
5399	}
5400	else {
5401		$fields_snmp_module = array('id','disabled', 'id_module_group',
5402			'min_warning', 'max_warning', 'str_warning', 'min_critical',
5403			'max_critical', 'str_critical', 'min_ff_event',
5404			'history_data', 'tcp_port', 'tcp_send', 'snmp_community',
5405			'snmp_oid', 'module_interval', 'post_process', 'min', 'max',
5406			'custom_id', 'description');
5407	}
5408
5409	$cont = 0;
5410	foreach ($fields_snmp_module as $field) {
5411		if ($other['data'][$cont] != "" and $field != 'id') {
5412			$values[$field] = $other['data'][$cont];
5413		}
5414
5415		$cont++;
5416	}
5417
5418	$result_update = enterprise_hook('policies_update_module',
5419		array($other['data'][0], $values, false));
5420
5421
5422	if ($result_update < 0)
5423		returnError('error_update_snmp_module_policy', 'Error updating policy module.');
5424	else
5425		returnData('string',
5426			array('type' => 'string', 'data' => __('SNMP policy module updated.')));
5427}
5428
5429
5430/**
5431 * Apply policy. And return id from the applying operation.
5432 *
5433 * @param string $id Id of the target policy.
5434 * @param $thrash1 Don't use.
5435 * @param array $other Don't use
5436 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5437 *  example:
5438 *
5439 *  api.php?op=set&op2=apply_policy&id=1
5440 *
5441 * @param $thrash3 Don't use
5442 */
5443function api_set_apply_policy($id, $thrash1, $other, $thrash3) {
5444	if (defined ('METACONSOLE')) {
5445		return;
5446	}
5447
5448	if ($id == "") {
5449		returnError('error_apply_policy', __('Error applying policy. Id_policy cannot be left blank.'));
5450		return;
5451	}
5452
5453	# Check if this operation is duplicated
5454	$duplicated = enterprise_hook('policies_get_policy_queue_status', array($id));
5455
5456	if ($duplicated === ENTERPRISE_NOT_HOOK) {
5457		// We want to return a value
5458		if ($other == "return") {
5459			return -1;
5460		}
5461		else {
5462			returnError('error_apply_policy', __('Error applying policy.'));
5463			return;
5464		}
5465	}
5466
5467	if ($duplicated == STATUS_IN_QUEUE_APPLYING or $duplicated == STATUS_IN_QUEUE_IN) {
5468		// We want to return a value
5469		if ($other == "return") {
5470			return -1;
5471		}
5472		else {
5473			returnError('error_apply_policy',
5474				__('Error applying policy. This policy is already pending to apply.'));
5475			return;
5476		}
5477	}
5478
5479	$id = enterprise_hook('add_policy_queue_operation', array($id, 0, 'apply'));
5480
5481	if ($id === ENTERPRISE_NOT_HOOK) {
5482		// We want to return a value
5483		if ($other == "return") {
5484			return -1;
5485		}
5486		else {
5487			returnError('error_apply_policy', __('Error applying policy.'));
5488			return;
5489		}
5490	}
5491
5492	// We want to return a value
5493	if ($other == "return") {
5494		if ($id)
5495			return $id;
5496		else
5497			return -1;
5498	}
5499	else {
5500		if ($id)
5501			returnData('string', array('type' => 'string', 'data' => $id));
5502		else
5503			returnError('error_apply_policy', 'Error applying policy.');
5504	}
5505}
5506
5507
5508/**
5509 * Apply all policy in database. And return the number of policies applied.
5510 *
5511 * @param string $id Don't use.
5512 * @param $thrash1 Don't use.
5513 * @param array $other Don't use
5514 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5515 *  example:
5516 *
5517 *  api.php?op=set&op2=apply_all_policies
5518 *
5519 * @param $thrash3 Don't use
5520 */
5521function api_set_apply_all_policies($thrash1, $thrash2, $other, $thrash3) {
5522	if (defined ('METACONSOLE')) {
5523		return;
5524	}
5525
5526	$policies = array();
5527
5528	# Get all policies
5529	$policies = enterprise_hook('policies_get_policies', array(false, false, false, true));
5530
5531	if ($policies === ENTERPRISE_NOT_HOOK) {
5532		returnError('error_apply_all_policy', __('Error applying all policies.'));
5533		return;
5534	}
5535
5536	$num_policies = count($policies);
5537	$count_results = 0;
5538	foreach ($policies as $policy) {
5539		$return_value = enterprise_hook('add_policy_queue_operation',
5540			array($policy['id'], 0, 'apply'));
5541
5542		if ($return_value != -1) {
5543			$count_results++;
5544		}
5545	}
5546
5547	if ($num_policies > $count_results) {
5548		$errors = $num_policies - $count_results;
5549
5550		returnError('error_apply_policy', 'Error applying policy. ' . $errors . ' failed. ');
5551	}
5552	else {
5553		returnData('string', array('type' => 'string', 'data' => $count_results));
5554	}
5555}
5556
5557/**
5558 * Create a new group. And return the id_group of the new group.
5559 *
5560 * @param string $id Name of the new group.
5561 * @param $thrash1 Don't use.
5562 * @param array $other it's array, $other as param is <icon_name>;<id_group_parent>;<description> in this order
5563 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5564 *  example:
5565 *
5566 * 	example 1 (with parent group: Servers)
5567 *
5568 *  api.php?op=set&op2=create_group&id=example_group_name&other=applications|1&other_mode=url_encode_separator_|
5569 *
5570 * 	example 2 (without parent group)
5571 *
5572 * 	api.php?op=set&op2=create_group&id=example_group_name2&other=computer|&other_mode=url_encode_separator_|
5573 *
5574 * @param $thrash3 Don't use
5575 */
5576function api_set_create_group($id, $thrash1, $other, $thrash3) {
5577
5578	$group_name = $id;
5579
5580
5581
5582	if ($id == "") {
5583		returnError('error_create_group',
5584			__('Error in group creation. Group_name cannot be left blank.'));
5585		return;
5586	}
5587
5588	if ($other['data'][0] == "") {
5589		returnError('error_create_group',
5590			__('Error in group creation. Icon_name cannot be left blank.'));
5591		return;
5592	}
5593
5594
5595
5596	$safe_other_data = io_safe_input($other['data']);
5597
5598	if ($safe_other_data[1] != "") {
5599			$group = groups_get_group_by_id($safe_other_data[1]);
5600
5601		if ($group == false) {
5602			returnError('error_create_group',
5603				__('Error in group creation. Id_parent_group doesn\'t exists.'));
5604			return;
5605		}
5606	}
5607
5608	if ($safe_other_data[1] != "") {
5609		$values = array(
5610			'icon' => $safe_other_data[0],
5611			'parent' => $safe_other_data[1],
5612			'description' => $safe_other_data[2]
5613		);
5614	}
5615	else {
5616		$values = array(
5617			'icon' => $safe_other_data[0],
5618			'description' => $safe_other_data[2]
5619		);
5620	}
5621	$values['propagate'] = $safe_other_data[3];
5622	$values['disabled'] = $safe_other_data[4];
5623	$values['custom_id'] =$safe_other_data[5];
5624	$values['contact'] = $safe_other_data[6];
5625	$values['other'] = $safe_other_data[7];
5626
5627	$id_group = groups_create_group($group_name, $values);
5628
5629	if (is_error($id_group)) {
5630		// TODO: Improve the error returning more info
5631		returnError('error_create_group', __('Error in group creation.'));
5632	}
5633	else {
5634
5635		if (defined("METACONSOLE")) {
5636			$servers = db_get_all_rows_sql ("SELECT *
5637				FROM tmetaconsole_setup
5638				WHERE disabled = 0");
5639
5640			if ($servers === false)
5641				$servers = array();
5642
5643			$result = array();
5644			foreach($servers as $server) {
5645				// If connection was good then retrieve all data server
5646				if (metaconsole_connect($server) == NOERR) {
5647					$values['id_grupo'] = $id_group;
5648					$id_group_node = groups_create_group($group_name, $values);
5649				}
5650				metaconsole_restore_db();
5651			}
5652		}
5653
5654		returnData('string', array('type' => 'string', 'data' => $id_group));
5655	}
5656}
5657
5658/**
5659 * Update a group.
5660 *
5661 * @param integer $id Group ID
5662 * @param $thrash2 Don't use.
5663 * @param array $other it's array, $other as param is <group_name>;<icon_name>;<parent_group_id>;<propagete>;<disabled>;<custom_id>;<description>;<contact>;<other> in this order
5664 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5665 *  example:
5666 *
5667 * 	api.php?op=set&op2=update_group&id=example_group_id&other=New%20Name|application|2|new%20description|1|0|custom%20id||&other_mode=url_encode_separator_|
5668 *
5669 * @param $thrash3 Don't use
5670 */
5671function api_set_update_group($id_group, $thrash2, $other, $thrash3) {
5672	global $config;
5673
5674	if (defined ('METACONSOLE')) {
5675		return;
5676	}
5677
5678		//html_debug_print($other);
5679	$name = $other['data'][0];
5680	$icon = $other['data'][1];
5681	$parent = $other['data'][2];
5682	$description = $other['data'][3];
5683	$propagate = $other['data'][4];
5684	$disabled = $other['data'][5];
5685	$custom_id = $other['data'][6];
5686	$contact = $other['data'][7];
5687	$other = $other['data'][8];
5688
5689	$return = db_process_sql_update('tgrupo',
5690		array('nombre' => $name,
5691			'icon' => $icon,
5692			'parent' => $parent,
5693			'description' => $description,
5694			'propagate' => $propagate,
5695			'disabled' => $disabled,
5696			'custom_id' => $custom_id,
5697			'contact' => $contact,
5698			'other' => $other),
5699		array('id_grupo' => $id_group));
5700
5701	returnData('string',
5702		array('type' => 'string', 'data' => (int)((bool)$return)));
5703}
5704
5705/**
5706 * Create a new netflow filter. And return the id_group of the new group.
5707 *
5708 * @param $thrash1 Don't use.
5709 * @param $thrash2 Don't use.
5710 * @param array $other it's array, $other as param is <filter_name>;<group_id>;<filter>;<aggregate_by>;<output_format> in this order
5711 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5712 *
5713 * Possible values of 'aggregate_by' field: dstip,dstport,none,proto,srcip,srcport
5714 * Possible values of 'output_format' field: kilobytes,kilobytespersecond,megabytes,megabytespersecond
5715 *
5716 *  example:
5717 *
5718 * 	api.php?op=set&op2=create_netflow_filter&id=Filter name&other=9|host 192.168.50.3 OR host 192.168.50.4 or HOST 192.168.50.6|dstport|kilobytes&other_mode=url_encode_separator_|
5719 *
5720 * @param $thrash3 Don't use
5721 */
5722function api_set_create_netflow_filter($thrash1, $thrash2, $other, $thrash3) {
5723	if (defined ('METACONSOLE')) {
5724		return;
5725	}
5726
5727	if ($other['data'][0] == "") {
5728		returnError('error_create_netflow_filter', __('Error in netflow filter creation. Filter name cannot be left blank.'));
5729		return;
5730	}
5731
5732	if ($other['data'][1] == "") {
5733		returnError('error_create_netflow_filter', __('Error in netflow filter creation. Group id cannot be left blank.'));
5734		return;
5735	}
5736	else {
5737		$group = groups_get_group_by_id($other['data'][1]);
5738
5739		if ($group == false) {
5740			returnError('error_create_group', __('Error in group creation. Id_parent_group doesn\'t exists.'));
5741			return;
5742		}
5743	}
5744
5745	if ($other['data'][2] == "") {
5746		returnError('error_create_netflow_filter', __('Error in netflow filter creation. Filter cannot be left blank.'));
5747		return;
5748	}
5749
5750	if ($other['data'][3] == "") {
5751		returnError('error_create_netflow_filter', __('Error in netflow filter creation. Aggregate_by cannot be left blank.'));
5752		return;
5753	}
5754
5755	if ($other['data'][4] == "") {
5756		returnError('error_create_netflow_filter', __('Error in netflow filter creation. Output_format cannot be left blank.'));
5757		return;
5758	}
5759
5760	$values = array (
5761		'id_name'=> $other['data'][0],
5762		'id_group' => $other['data'][1],
5763		'advanced_filter'=> $other['data'][2],
5764		'aggregate'=> $other['data'][3],
5765		'output'=> $other['data'][4]
5766	);
5767
5768	// Save filter args
5769	$values['filter_args'] = netflow_get_filter_arguments ($values);
5770
5771	$id = db_process_sql_insert('tnetflow_filter', $values);
5772
5773	if ($id === false) {
5774		returnError('error_create_netflow_filter', __('Error in netflow filter creation.'));
5775	}
5776	else {
5777		returnData('string', array('type' => 'string', 'data' => $id));
5778	}
5779}
5780
5781/**
5782 * Get module data in CSV format.
5783 *
5784 * @param integer $id The ID of module in DB.
5785 * @param $thrash1 Don't use.
5786 * @param array $other it's array, $other as param is <separator>;<period> in this order
5787 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5788 *  example:
5789 *
5790 *  api.php?op=get&op2=module_data&id=17&other=;|604800&other_mode=url_encode_separator_|
5791 *
5792 * @param $returnType Don't use.
5793 */
5794function api_get_module_data($id, $thrash1, $other, $returnType) {
5795	if (defined ('METACONSOLE')) {
5796		return;
5797	}
5798
5799	$separator = $other['data'][0];
5800	$periodSeconds = $other['data'][1];
5801
5802	$sql = sprintf ("SELECT utimestamp, datos
5803		FROM tagente_datos
5804		WHERE id_agente_modulo = %d AND utimestamp > %d
5805		ORDER BY utimestamp DESC", $id, get_system_time () - $periodSeconds);
5806
5807	$data['type'] = 'array';
5808	$data['list_index'] = array('utimestamp', 'datos');
5809	$data['data'] = db_get_all_rows_sql($sql);
5810
5811	if ($data === false)
5812		returnError('error_query_module_data', 'Error in the query of module data.');
5813	else
5814		returnData('csv', $data, $separator);
5815}
5816
5817/**
5818 * Return a image file of sparse graph of module data in a period time.
5819 *
5820 * @param integer $id id of a module data.
5821 * @param $thrash1 Don't use.
5822 * @param array $other it's array, $other as param is <period>;<width>;<height>;<label>;<start_date>; in this order
5823 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5824 *  example:
5825 *
5826 *  api.php?op=get&op2=graph_module_data&id=17&other=604800|555|245|pepito|2009-12-07&other_mode=url_encode_separator_|
5827 *
5828 * @param $thrash2 Don't use.
5829 */
5830function api_get_graph_module_data($id, $thrash1, $other, $thrash2) {
5831	if (defined ('METACONSOLE')) {
5832		return;
5833	}
5834
5835	$period = $other['data'][0];
5836	$width = $other['data'][1];
5837	$height = $other['data'][2];
5838	$graph_type = 'sparse';
5839	$draw_alerts = 0;
5840	$draw_events = 0;
5841	$zoom = 1;
5842	$label = $other['data'][3];
5843	$avg_only = 0;
5844	$start_date = $other['data'][4];
5845	$date = strtotime($start_date);
5846
5847
5848	$homeurl = '../';
5849	$ttl = 1;
5850
5851	global $config;
5852	$config['flash_charts'] = 0;
5853
5854	$image = grafico_modulo_sparse ($id, $period, $draw_events,
5855		$width, $height , $label, null,
5856		$draw_alerts, $avg_only, false,
5857		$date, '', 0, 0,true,
5858		false, $homeurl, $ttl);
5859
5860	preg_match("/<div class=\"nodata_text\">/",
5861		$image, $match);
5862
5863	if (!empty($match[0])) {
5864		echo "Error no data";
5865	}
5866	else {
5867		// Extract url of the image from img tag
5868		preg_match("/src='([^']*)'/i", $image, $match);
5869
5870		if (empty($match[1])) {
5871			echo "Error getting graph";
5872		}
5873		else {
5874			header('Content-type: image/png');
5875			header('Location: ' . $match[1]);
5876		}
5877	}
5878}
5879
5880/**
5881 * Create new user.
5882 *
5883 * @param string $id String username for user login in Pandora
5884 * @param $thrash2 Don't use.
5885 * @param array $other it's array, $other as param is <fullname>;<firstname>;<lastname>;<middlename>;
5886 *  <email>;<phone>;<languages>;<comments> in this order and separator char
5887 *  (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5888 *  example:
5889 *
5890 *  api.php?op=set&op2=new_user&id=md&other=miguel|de%20dios|matias|kkk|pandora|md@md.com|666|es|descripcion%20y%20esas%20cosas&other_mode=url_encode_separator_|
5891 *
5892 * @param $thrash3 Don't use.
5893 */
5894function api_set_new_user($id, $thrash2, $other, $thrash3) {
5895	if (defined ('METACONSOLE')) {
5896		return;
5897	}
5898
5899	$values = array ();
5900	$values['fullname'] = $other['data'][0];
5901	$values['firstname'] = $other['data'][1];
5902	$values['lastname'] = $other['data'][2];
5903	$values['middlename'] = $other['data'][3];
5904	$password = $other['data'][4];
5905	$values['email'] = $other['data'][5];
5906	$values['phone'] = $other['data'][6];
5907	$values['language'] = $other['data'][7];
5908	$values['comments'] = $other['data'][8];
5909
5910	if (!create_user ($id, $password, $values))
5911		returnError('error_create_user', 'Error create user');
5912	else
5913		returnData('string', array('type' => 'string', 'data' => __('Create user.')));
5914}
5915
5916/**
5917 * Update new user.
5918 *
5919 * @param string $id String username for user login in Pandora
5920 * @param $thrash2 Don't use.
5921 * @param array $other it's array, $other as param is <fullname>;<firstname>;<lastname>;<middlename>;<password>;
5922 *  <email>;<phone>;<language>;<comments>;<is_admin>;<block_size>;<flash_chart> in this order and separator char
5923 *  (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5924 *  example:
5925 *
5926 *  api.php?op=set&op2=update_user&id=example_user_name&other=example_fullname||example_lastname||example_new_passwd|example_email||example_language|example%20comment|1|30|&other_mode=url_encode_separator_|
5927 *
5928 * @param $thrash3 Don't use.
5929 */
5930function api_set_update_user($id, $thrash2, $other, $thrash3) {
5931
5932	if (defined ('METACONSOLE')) {
5933		return;
5934	}
5935
5936	$fields_user = array('fullname',
5937		'firstname',
5938		'lastname',
5939		'middlename',
5940		'password',
5941		'email',
5942		'phone',
5943		'language',
5944		'comments',
5945		'is_admin',
5946		'block_size',
5947		'flash_chart');
5948
5949
5950	if ($id == "") {
5951		returnError('error_update_user',
5952			__('Error updating user. Id_user cannot be left blank.'));
5953		return;
5954	}
5955
5956	$result_user = users_get_user_by_id($id);
5957
5958	if (!$result_user) {
5959		returnError('error_update_user',
5960			__('Error updating user. Id_user doesn\'t exists.'));
5961		return;
5962	}
5963
5964	$cont = 0;
5965	foreach ($fields_user as $field) {
5966		if ($other['data'][$cont] != "" and $field != "password") {
5967			$values[$field] = $other['data'][$cont];
5968		}
5969
5970		$cont++;
5971	}
5972
5973	// If password field has data
5974	if ($other['data'][4] != "") {
5975		if (!update_user_password($id, $other['data'][4])) {
5976			returnError('error_update_user', __('Error updating user. Password info incorrect.'));
5977			return;
5978		}
5979	}
5980
5981	if (!update_user ($id, $values))
5982		returnError('error_create_user', 'Error updating user');
5983	else
5984		returnData('string', array('type' => 'string', 'data' => __('Updated user.')));
5985}
5986
5987/**
5988 * Enable/disable user given an id
5989 *
5990 * @param string $id String username for user login in Pandora
5991 * @param $thrash2 Don't use.
5992 * @param array $other it's array, $other as param is <enable/disable value> in this order and separator char
5993 *  (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
5994 *  example:
5995 *
5996 * 	example 1 (Disable user 'example_name')
5997 *
5998 *  api.php?op=set&op2=enable_disable_user&id=example_name&other=0&other_mode=url_encode_separator_|
5999 *
6000 * 	example 2 (Enable user 'example_name')
6001 *
6002 *  api.php?op=set&op2=enable_disable_user&id=example_name&other=1&other_mode=url_encode_separator_|
6003 *
6004 * @param $thrash3 Don't use.
6005 */
6006
6007function api_set_enable_disable_user ($id, $thrash2, $other, $thrash3) {
6008
6009	if (defined ('METACONSOLE')) {
6010		return;
6011	}
6012
6013	if ($id == "") {
6014		returnError('error_enable_disable_user',
6015			__('Error enable/disable user. Id_user cannot be left blank.'));
6016		return;
6017	}
6018
6019
6020	if ($other['data'][0] != "0" and $other['data'][0] != "1") {
6021		returnError('error_enable_disable_user',
6022			__('Error enable/disable user. Enable/disable value cannot be left blank.'));
6023		return;
6024	}
6025
6026	if (users_get_user_by_id($id) == false) {
6027		returnError('error_enable_disable_user',
6028			__('Error enable/disable user. The user doesn\'t exists.'));
6029		return;
6030	}
6031
6032	$result = users_disable($id, $other['data'][0]);
6033
6034	if (is_error($result)) {
6035		// TODO: Improve the error returning more info
6036		returnError('error_enable_disable_user',
6037			__('Error in user enabling/disabling.'));
6038	}
6039	else {
6040		if ($other['data'][0] == "0") {
6041			returnData('string',
6042				array('type' => 'string', 'data' => __('Enabled user.')));
6043		}
6044		else {
6045			returnData('string',
6046			array('type' => 'string', 'data' => __('Disabled user.')));
6047		}
6048	}
6049}
6050
6051
6052function otherParameter2Filter($other, $return_as_array = false) {
6053	$filter = array();
6054
6055	if (isset($other['data'][1]) && ($other['data'][1] != -1) && ($other['data'][1] != '')) {
6056		$filter['criticity'] = $other['data'][1];
6057	}
6058
6059	$idAgent = null;
6060	if (isset($other['data'][2]) && $other['data'][2] != '') {
6061		$idAgent = agents_get_agent_id($other['data'][2]);
6062
6063		if (!empty($idAgent)) {
6064			$filter['id_agente'] = $idAgent;
6065		}
6066		else {
6067			$filter['sql'] = "1=0";
6068		}
6069	}
6070
6071	$idAgentModulo = null;
6072	if (isset($other['data'][3]) && $other['data'][3] != '') {
6073		$filterModule = array('nombre' => $other['data'][3]);
6074		if ($idAgent != null) {
6075			$filterModule['id_agente'] = $idAgent;
6076		}
6077		$idAgentModulo = db_get_value_filter('id_agente_modulo', 'tagente_modulo', $filterModule);
6078		if ($idAgentModulo !== false) {
6079			$filter['id_agentmodule'] = $idAgentModulo;
6080		}
6081	}
6082
6083	if (isset($other['data'][4]) && $other['data'][4] != '') {
6084		$idTemplate = db_get_value_filter('id', 'talert_templates', array('name' => $other['data'][4]));
6085		if ($idTemplate !== false) {
6086			if ($idAgentModulo != null) {
6087				$idAlert = db_get_value_filter('id', 'talert_template_modules', array('id_agent_module' => $idAgentModulo,  'id_alert_template' => $idTemplate));
6088				if ($idAlert !== false) {
6089					$filter['id_alert_am'] = $idAlert;
6090				}
6091			}
6092		}
6093	}
6094
6095	if (isset($other['data'][5]) && $other['data'][5] != '') {
6096		$filter['id_usuario'] = $other['data'][5];
6097	}
6098
6099	$filterString = db_format_array_where_clause_sql ($filter);
6100	if ($filterString == '') {
6101		$filterString = '1 = 1';
6102	}
6103
6104	if (isset($other['data'][6]) && ($other['data'][6] != '') && ($other['data'][6] != -1)) {
6105		if ($return_as_array) {
6106			$filter['utimestamp']['>'] = $other['data'][6];
6107		}
6108		else {
6109			$filterString .= ' AND utimestamp >= ' . $other['data'][6];
6110		}
6111	}
6112
6113	if (isset($other['data'][7]) && ($other['data'][7] != '') && ($other['data'][7] != -1)) {
6114		if ($return_as_array) {
6115			$filter['utimestamp']['<'] = $other['data'][7];
6116		}
6117		else {
6118			$filterString .= ' AND utimestamp <= ' . $other['data'][7];
6119		}
6120	}
6121
6122	if (isset($other['data'][8]) && ($other['data'][8] != '')) {
6123		if ($return_as_array) {
6124			$filter['estado'] = $other['data'][8];
6125		}
6126		else {
6127			$estado = (int)$other['data'][8];
6128
6129			if ($estado >= 0) {
6130				$filterString .= ' AND estado = ' . $estado;
6131			}
6132		}
6133	}
6134
6135	if (isset($other['data'][9]) && ($other['data'][9] != '')) {
6136		if ($return_as_array) {
6137			$filter['evento'] = $other['data'][9];
6138		}
6139		else {
6140			$filterString .= ' AND evento like "%' . $other['data'][9] . '%"';
6141		}
6142	}
6143
6144	if (isset($other['data'][10]) && ($other['data'][10] != '')) {
6145		if ($return_as_array) {
6146			$filter['limit'] = $other['data'][10];
6147		}
6148		else {
6149			$filterString .= ' LIMIT ' . $other['data'][10];
6150		}
6151	}
6152
6153	if (isset($other['data'][11]) && ($other['data'][11] != '')) {
6154		if ($return_as_array) {
6155			$filter['offset'] = $other['data'][11];
6156		}
6157		else {
6158			$filterString .= ' OFFSET ' . $other['data'][11];
6159		}
6160	}
6161
6162	if (isset($other['data'][12]) && ($other['data'][12] != '')) {
6163		if ($return_as_array) {
6164			$filter['total'] = false;
6165			$filter['more_criticity'] = false;
6166
6167			if ($other['data'][12] == 'total') {
6168				$filter['total'] = true;
6169			}
6170
6171			if ($other['data'][12] == 'more_criticity') {
6172				$filter['more_criticity'] = true;
6173			}
6174		}
6175		else {
6176
6177		}
6178	}
6179	else {
6180		if ($return_as_array) {
6181			$filter['total'] = false;
6182			$filter['more_criticity'] = false;
6183		}
6184		else {
6185
6186		}
6187	}
6188
6189	if (isset($other['data'][13]) && ($other['data'][13] != '')) {
6190		if ($return_as_array) {
6191			$filter['id_group'] = $other['data'][13];
6192		}
6193		else {
6194			$filterString .= ' AND id_grupo =' . $other['data'][13];
6195		}
6196	}
6197
6198	if (isset($other['data'][14]) && ($other['data'][14] != '')) {
6199
6200		if ($return_as_array) {
6201			$filter['tag'] = $other['data'][14];
6202		}
6203		else {
6204			$filterString .= " AND tags LIKE '" . $other['data'][14]."'";
6205		}
6206	}
6207
6208	if (isset($other['data'][15]) && ($other['data'][15] != '')) {
6209		if ($return_as_array) {
6210			$filter['event_type'] = $other['data'][15];
6211		}
6212		else {
6213			$event_type = $other['data'][15];
6214
6215			if ($event_type == "not_normal") {
6216				$filterString .= " AND ( event_type LIKE '%warning%'
6217					OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%' ) ";
6218			}
6219			else {
6220				$filterString .= ' AND event_type LIKE "%' . $event_type . '%"';
6221			}
6222		}
6223
6224	}
6225
6226	if ($return_as_array) {
6227		return $filter;
6228	}
6229	else {
6230		return $filterString;
6231	}
6232}
6233
6234/**
6235 *
6236 * @param $id
6237 * @param $id2
6238 * @param $other
6239 * @param $trash1
6240 */
6241function api_set_new_alert_template($id, $id2, $other, $trash1) {
6242	if (defined ('METACONSOLE')) {
6243		return;
6244	}
6245
6246	if ($other['type'] == 'string') {
6247		returnError('error_parameter', 'Error in the parameters.');
6248		return;
6249	}
6250	else if ($other['type'] == 'array') {
6251		$idAgent = agents_get_agent_id($id);
6252
6253		$row = db_get_row_filter('talert_templates', array('name' => $id2));
6254
6255		if ($row === false) {
6256			returnError('error_parameter', 'Error in the parameters.');
6257			return;
6258		}
6259
6260		$idTemplate = $row['id'];
6261		$idActionTemplate = $row['id_alert_action'];
6262
6263		$idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $idAgent, 'nombre' => $other['data'][0]));
6264
6265		if ($idAgentModule === false) {
6266			returnError('error_parameter', 'Error in the parameters.');
6267			return;
6268		}
6269
6270		$values = array(
6271			'id_agent_module' => $idAgentModule,
6272			'id_alert_template' => $idTemplate);
6273
6274		$return = db_process_sql_insert('talert_template_modules', $values);
6275
6276		$data['type'] = 'string';
6277		if ($return === false) {
6278			$data['data'] = 0;
6279		}
6280		else {
6281			$data['data'] = $return;
6282		}
6283		returnData('string', $data);
6284		return;
6285	}
6286}
6287
6288function api_set_delete_module($id, $id2, $other, $trash1) {
6289	if (defined ('METACONSOLE')) {
6290		return;
6291	}
6292
6293	if ($other['type'] == 'string') {
6294		$simulate = false;
6295		if ($other['data'] == 'simulate') {
6296			$simulate = true;
6297		}
6298
6299		$idAgent = agents_get_agent_id($id);
6300
6301		$idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $idAgent, 'nombre' => $id2));
6302
6303		if ($idAgentModule === false) {
6304			returnError('error_parameter', 'Error in the parameters.');
6305			return;
6306		}
6307
6308		if (!$simulate) {
6309			$return = modules_delete_agent_module($idAgentModule);
6310		}
6311		else {
6312			$return = true;
6313		}
6314
6315		$data['type'] = 'string';
6316		if ($return === false) {
6317			$data['data'] = 0;
6318		}
6319		else {
6320			$data['data'] = $return;
6321		}
6322		returnData('string', $data);
6323		return;
6324	}
6325	else {
6326		returnError('error_parameter', 'Error in the parameters.');
6327		return;
6328	}
6329}
6330
6331function api_set_module_data($id, $thrash2, $other, $trash1) {
6332	global $config;
6333
6334	if (defined ('METACONSOLE')) {
6335		return;
6336	}
6337
6338	if ($other['type'] == 'array') {
6339		$idAgentModule = $id;
6340		$data = $other['data'][0];
6341		$time = $other['data'][1];
6342
6343		if ($time == 'now') $time = time();
6344
6345		$agentModule = db_get_row_filter('tagente_modulo', array('id_agente_modulo' => $idAgentModule));
6346		if ($agentModule === false) {
6347			returnError('error_parameter', 'Not found module agent.');
6348		}
6349		else {
6350			$agent = db_get_row_filter('tagente', array('id_agente' => $agentModule['id_agente']));
6351
6352			$xmlTemplate = "<?xml version='1.0' encoding='ISO-8859-1'?>
6353				<agent_data description='' group='' os_name='%s' " .
6354				" os_version='%s' interval='%d' version='%s' timestamp='%s' agent_name='%s' timezone_offset='%d'>
6355					<module>
6356						<name><![CDATA[%s]]></name>
6357						<description><![CDATA[%s]]></description>
6358						<type><![CDATA[%s]]></type>
6359						<data><![CDATA[%s]]></data>
6360					</module>
6361				</agent_data>";
6362
6363			$xml = sprintf($xmlTemplate, io_safe_output(get_os_name($agent['id_os'])),
6364				io_safe_output($agent['os_version']), $agent['intervalo'],
6365				io_safe_output($agent['agent_version']), date('Y/m/d H:i:s', $time),
6366				io_safe_output($agent['nombre']), $agent['timezone_offset'],
6367				io_safe_output($agentModule['nombre']), io_safe_output($agentModule['descripcion']), modules_get_type_name($agentModule['id_tipo_modulo']), $data);
6368
6369
6370			if (false === @file_put_contents($config['remote_config'] . '/' . io_safe_output($agent['nombre']) . '.' . $time . '.data', $xml)) {
6371				returnError('error_file', 'Can save agent data xml.');
6372			}
6373			else {
6374				returnData('string', array('type' => 'string', 'data' => $xml));
6375				return;
6376			}
6377		}
6378	}
6379	else {
6380		returnError('error_parameter', 'Error in the parameters.');
6381		return;
6382	}
6383}
6384
6385function api_set_new_module($id, $id2, $other, $trash1) {
6386	if (defined ('METACONSOLE')) {
6387		return;
6388	}
6389
6390	if ($other['type'] == 'string') {
6391		returnError('error_parameter', 'Error in the parameters.');
6392		return;
6393	}
6394	else if ($other['type'] == 'array') {
6395		$values = array();
6396		$values['id_agente'] = agents_get_agent_id($id);
6397		$values['nombre'] = $id2;
6398
6399		$values['id_tipo_modulo'] = db_get_value_filter('id_tipo', 'ttipo_modulo', array('nombre' => $other['data'][0]));
6400		if ($values['id_tipo_modulo'] === false) {
6401			returnError('error_parameter', 'Error in the parameters.');
6402			return;
6403		}
6404
6405		if ($other['data'][1] == '') {
6406			returnError('error_parameter', 'Error in the parameters.');
6407			return;
6408		}
6409
6410		$values['ip_target'] = $other['data'][1];
6411
6412		if (strstr($other['data'][0], 'icmp') === false) {
6413			if (($other['data'][2] == '') || ($other['data'][2] <= 0 || $other['data'][2] > 65535)) {
6414				returnError('error_parameter', 'Error in the parameters.');
6415				return;
6416			}
6417
6418			$values['tcp_port'] = $other['data'][2];
6419		}
6420
6421		$values['descripcion'] = $other['data'][3];
6422
6423		if ($other['data'][4] != '') {
6424			$values['min'] = $other['data'][4];
6425		}
6426
6427		if ($other['data'][5] != '') {
6428			$values['max'] = $other['data'][5];
6429		}
6430
6431		if ($other['data'][6] != '') {
6432			$values['post_process'] = $other['data'][6];
6433		}
6434
6435		if ($other['data'][7] != '') {
6436			$values['module_interval'] = $other['data'][7];
6437		}
6438
6439		if ($other['data'][8] != '') {
6440			$values['min_warning'] = $other['data'][8];
6441		}
6442
6443		if ($other['data'][9] != '') {
6444			$values['max_warning'] = $other['data'][9];
6445		}
6446
6447		if ($other['data'][10] != '') {
6448			$values['str_warning'] = $other['data'][10];
6449		}
6450
6451		if ($other['data'][11] != '') {
6452			$values['min_critical'] = $other['data'][11];
6453		}
6454
6455		if ($other['data'][12] != '') {
6456			$values['max_critical'] = $other['data'][12];
6457		}
6458
6459		if ($other['data'][13] != '') {
6460			$values['str_critical'] = $other['data'][13];
6461		}
6462
6463		if ($other['data'][14] != '') {
6464			$values['history_data'] = $other['data'][14];
6465		}
6466
6467		$disabled_types_event = array();
6468		$disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][15];
6469		$disabled_types_event = json_encode($disabled_types_event);
6470		$values['disabled_types_event'] = $disabled_types_event;
6471
6472		$values['id_modulo'] = 2;
6473
6474		$return = modules_create_agent_module($values['id_agente'],
6475			$values['nombre'], $values);
6476
6477		$data['type'] = 'string';
6478		if ($return === false) {
6479			$data['data'] = 0;
6480		}
6481		else {
6482			$data['data'] = $return;
6483		}
6484		returnData('string', $data);
6485		return;
6486	}
6487}
6488
6489/**
6490 *
6491 * @param unknown_type $id
6492 * @param unknown_type $id2
6493 * @param unknown_type $other
6494 * @param unknown_type $trash1
6495 */
6496function api_set_alert_actions($id, $id2, $other, $trash1) {
6497	if (defined ('METACONSOLE')) {
6498		return;
6499	}
6500
6501	if ($other['type'] == 'string') {
6502		returnError('error_parameter', 'Error in the parameters.');
6503		return;
6504	}
6505	else if ($other['type'] == 'array') {
6506		$idAgent = agents_get_agent_id($id);
6507
6508		$row = db_get_row_filter('talert_templates', array('name' => $id2));
6509		if ($row === false) {
6510			returnError('error_parameter', 'Error in the parameters.');
6511			return;
6512		}
6513		$idTemplate = $row['id'];
6514
6515		$idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $idAgent, 'nombre' => $other['data'][0]));
6516		if ($idAgentModule === false) {
6517			returnError('error_parameter', 'Error in the parameters.');
6518			return;
6519		}
6520
6521		$idAlertTemplateModule = db_get_value_filter('id', 'talert_template_modules', array('id_alert_template' => $idTemplate, 'id_agent_module' => $idAgentModule));
6522		if ($idAlertTemplateModule === false) {
6523			returnError('error_parameter', 'Error in the parameters.');
6524			return;
6525		}
6526
6527		if ($other['data'][1] != '') {
6528			$idAction = db_get_value_filter('id', 'talert_actions', array('name' => $other['data'][1]));
6529			if ($idAction === false) {
6530				returnError('error_parameter', 'Error in the parameters.');
6531				return;
6532			}
6533		}
6534		else {
6535			returnError('error_parameter', 'Error in the parameters.');
6536			return;
6537		}
6538
6539		$firesMin = $other['data'][2];
6540		$firesMax = $other['data'][3];
6541
6542		$values = array('id_alert_template_module' => $idAlertTemplateModule,
6543			'id_alert_action' => $idAction, 'fires_min' => $firesMin, 'fires_max' => $firesMax);
6544
6545		$return = db_process_sql_insert('talert_template_module_actions', $values);
6546
6547		$data['type'] = 'string';
6548		if ($return === false) {
6549			$data['data'] = 0;
6550		}
6551		else {
6552			$data['data'] = $return;
6553		}
6554		returnData('string', $data);
6555		return;
6556	}
6557}
6558
6559function api_set_new_event($trash1, $trash2, $other, $trash3) {
6560	$simulate = false;
6561	$time = get_system_time();
6562
6563	if ($other['type'] == 'string') {
6564		if ($other['data'] != '') {
6565			returnError('error_parameter', 'Error in the parameters.');
6566			return;
6567		}
6568	}
6569	else if ($other['type'] == 'array') {
6570		$values = array();
6571
6572		if (($other['data'][0] == null) && ($other['data'][0] == '')) {
6573			returnError('error_parameter', 'Error in the parameters.');
6574			return;
6575		}
6576		else {
6577			$values['evento'] = $other['data'][0];
6578		}
6579
6580		if (($other['data'][1] == null) && ($other['data'][1] == '')) {
6581			returnError('error_parameter', 'Error in the parameters.');
6582			return;
6583		}
6584		else {
6585			$valuesAvaliable = array('unknown', 'alert_fired', 'alert_recovered',
6586				'alert_ceased', 'alert_manual_validation',
6587				'recon_host_detected', 'system','error', 'new_agent',
6588				'going_up_warning', 'going_up_critical', 'going_down_warning',
6589				'going_down_normal', 'going_down_critical', 'going_up_normal','configuration_change');
6590
6591			if (in_array($other['data'][1], $valuesAvaliable)) {
6592				$values['event_type'] = $other['data'][1];
6593			}
6594			else {
6595				returnError('error_parameter', 'Error in the parameters.');
6596				return;
6597			}
6598		}
6599
6600		if (($other['data'][2] == null) && ($other['data'][2] == '')) {
6601			returnError('error_parameter', 'Error in the parameters.');
6602			return;
6603		}
6604		else {
6605			$values['estado'] = $other['data'][2];
6606		}
6607
6608		if (($other['data'][3] == null) && ($other['data'][3] == '')) {
6609			returnError('error_parameter', 'Error in the parameters.');
6610			return;
6611		}
6612		else {
6613			$values['id_agente'] = agents_get_agent_id($other['data'][3]);
6614		}
6615
6616		if (($other['data'][4] == null) && ($other['data'][4] == '')) {
6617			returnError('error_parameter', 'Error in the parameters.');
6618			return;
6619		}
6620		else {
6621			$idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo',
6622				array('nombre' => $other['data'][4], 'id_agente' => $values['id_agente']));
6623		}
6624
6625		if ($idAgentModule === false) {
6626			returnError('error_parameter', 'Error in the parameters.');
6627			return;
6628		}
6629		else {
6630			$values['id_agentmodule'] = $idAgentModule;
6631		}
6632
6633		if (($other['data'][5] == null) && ($other['data'][5] == '')) {
6634			returnError('error_parameter', 'Error in the parameters.');
6635			return;
6636		}
6637		else {
6638			if ($other['data'][5] != 'all') {
6639				$idGroup = db_get_value_filter('id_grupo', 'tgrupo', array('nombre' => $other['data'][5]));
6640			}
6641			else {
6642				$idGroup = 0;
6643			}
6644
6645			if ($idGroup === false) {
6646				returnError('error_parameter', 'Error in the parameters.');
6647				return;
6648			}
6649			else {
6650				$values['id_grupo'] = $idGroup;
6651			}
6652		}
6653
6654		if (($other['data'][6] == null) && ($other['data'][6] == '')) {
6655			returnError('error_parameter', 'Error in the parameters.');
6656			return;
6657		}
6658		else {
6659			if (($other['data'][6] >= 0) && ($other['data'][6] <= 4)) {
6660				$values['criticity'] = $other['data'][6];
6661			}
6662			else {
6663				returnError('error_parameter', 'Error in the parameters.');
6664				return;
6665			}
6666		}
6667
6668		if (($other['data'][7] == null) && ($other['data'][7] == '')) {
6669			//its optional parameter
6670		}
6671		else {
6672			$idAlert = db_get_value_sql("SELECT t1.id
6673				FROM talert_template_modules t1
6674					INNER JOIN talert_templates t2
6675						ON t1.id_alert_template = t2.id
6676				WHERE t1.id_agent_module = 1
6677					AND t2.name LIKE '" . $other['data'][7] . "'");
6678
6679			if ($idAlert === false) {
6680				returnError('error_parameter', 'Error in the parameters.');
6681				return;
6682			}
6683			else {
6684				$values['id_alert_am'] = $idAlert;
6685			}
6686		}
6687	}
6688
6689	$values['timestamp'] = date("Y-m-d H:i:s", $time);
6690	$values['utimestamp'] = $time;
6691
6692	$return = db_process_sql_insert('tevento', $values);
6693
6694	$data['type'] = 'string';
6695	if ($return === false) {
6696		$data['data'] = 0;
6697	}
6698	else {
6699		$data['data'] = $return;
6700	}
6701	returnData('string', $data);
6702	return;
6703}
6704
6705function api_set_event_validate_filter_pro($trash1, $trash2, $other, $trash3) {
6706	$simulate = false;
6707
6708
6709	$table_events = 'tevento';
6710	if (defined ('METACONSOLE')) {
6711		$table_events = 'tmetaconsole_event';
6712	}
6713
6714	if ($other['type'] == 'string') {
6715		if ($other['data'] != '') {
6716			returnError('error_parameter', 'Error in the parameters.');
6717			return;
6718		}
6719	}
6720	else if ($other['type'] == 'array') {
6721		$filter = array();
6722
6723		if (($other['data'][1] != null) && ($other['data'][1] != -1)
6724			&& ($other['data'][1] != '')) {
6725
6726			$filter['criticity'] = $other['data'][1];
6727		}
6728
6729		if (($other['data'][2] != null) && ($other['data'][2] != -1)
6730			&& ($other['data'][2] != '')) {
6731
6732			$filter['id_agente'] = $other['data'][2];
6733		}
6734
6735		if (($other['data'][3] != null) && ($other['data'][3] != -1)
6736			&& ($other['data'][3] != '')) {
6737
6738			$filter['id_agentmodule'] = $other['data'][3];
6739		}
6740
6741		if (($other['data'][4] != null) && ($other['data'][4] != -1)
6742			&& ($other['data'][4] != '')) {
6743
6744			$filter['id_alert_am'] = $other['data'][4];
6745		}
6746
6747		if (($other['data'][5] != null) && ($other['data'][5] != '')) {
6748			$filter['id_usuario'] = $other['data'][5];
6749		}
6750
6751		$filterString = db_format_array_where_clause_sql ($filter);
6752		if ($filterString == '') {
6753			$filterString = '1 = 1';
6754		}
6755
6756		if (($other['data'][6] != null) && ($other['data'][6] != -1)) {
6757			$filterString .= ' AND utimestamp > ' . $other['data'][6];
6758		}
6759
6760		if (($other['data'][7] != null) && ($other['data'][7] != -1)) {
6761			$filterString .= 'AND utimestamp < ' . $other['data'][7];
6762		}
6763	}
6764
6765	if ($simulate) {
6766		$rows = db_get_all_rows_filter($table_events, $filterString);
6767		if ($rows !== false) {
6768			returnData('string', count($rows));
6769			return;
6770		}
6771	}
6772	else {
6773		$count = db_process_sql_update($table_events,
6774			array('estado' => 1), $filterString);
6775
6776		returnData('string',
6777			array('type' => 'string', 'data' => $count));
6778		return;
6779	}
6780}
6781
6782function api_set_event_validate_filter($trash1, $trash2, $other, $trash3) {
6783	$simulate = false;
6784
6785	$table_events = 'tevento';
6786	if (defined ('METACONSOLE')) {
6787		$table_events = 'tmetaconsole_event';
6788	}
6789
6790	if ($other['type'] == 'string') {
6791		if ($other['data'] != '') {
6792			returnError('error_parameter', 'Error in the parameters.');
6793			return;
6794		}
6795	}
6796	else if ($other['type'] == 'array') {
6797		$separator = $other['data'][0];
6798
6799		if (($other['data'][8] != null) && ($other['data'][8] != '')) {
6800			if ($other['data'][8] == 'simulate') {
6801				$simulate = true;
6802			}
6803		}
6804
6805		$filterString = otherParameter2Filter($other);
6806
6807	}
6808
6809	if ($simulate) {
6810		$rows = db_get_all_rows_filter($table_events, $filterString);
6811		if ($rows !== false) {
6812			returnData('string', count($rows));
6813			return;
6814		}
6815	}
6816	else {
6817		$count = db_process_sql_update(
6818			$table_events, array('estado' => 1), $filterString);
6819
6820		returnData('string',
6821			array('type' => 'string', 'data' => $count));
6822		return;
6823	}
6824}
6825
6826function api_set_validate_events($id_event, $trash1, $other, $return_type, $user_in_db) {
6827	$text = $other['data'];
6828
6829	// Set off the standby mode when close an event
6830	$event = events_get_event ($id_event);
6831	alerts_agent_module_standby ($event['id_alert_am'], 0);
6832
6833	$result = events_change_status ($id_event, EVENT_VALIDATE);
6834
6835	if ($result) {
6836		if (!empty($text)) {
6837			//Set the comment for the validation
6838			events_comment($id_event, $text);
6839		}
6840
6841		returnData('string',
6842			array('type' => 'string', 'data' => 'Correct validation'));
6843	}
6844	else {
6845		returnError('Error in validation operation.');
6846	}
6847}
6848
6849function api_get_gis_agent($id_agent, $trash1, $tresh2, $return_type, $user_in_db) {
6850	if (defined ('METACONSOLE')) {
6851		return;
6852	}
6853
6854	$agent_gis_data = db_get_row_sql("
6855		SELECT *
6856		FROM tgis_data_status
6857		WHERE tagente_id_agente = " . $id_agent);
6858
6859	if ($agent_gis_data) {
6860		returnData($return_type,
6861			array('type' => 'array', 'data' => array($agent_gis_data)));
6862	}
6863	else {
6864		returnError('Error.');
6865	}
6866}
6867
6868function api_set_gis_agent_only_position($id_agent, $trash1, $other, $return_type, $user_in_db) {
6869	global $config;
6870
6871	if (defined ('METACONSOLE')) {
6872		return;
6873	}
6874
6875	$new_gis_data = $other['data'];
6876
6877	$correct = true;
6878
6879	if (isset($new_gis_data[0])) {
6880		$latitude = $new_gis_data[0];
6881	}
6882	else $correct = false;
6883
6884	if (isset($new_gis_data[1])) {
6885		$longitude = $new_gis_data[1];
6886	}
6887	else $correct = false;
6888
6889	if (isset($new_gis_data[2])) {
6890		$altitude = $new_gis_data[2];
6891	}
6892	else $correct = false;
6893
6894	if (!$config['activate_gis']) {
6895		$correct = false;
6896	}
6897	else {
6898		if ($correct) {
6899			$correct = agents_update_gis($id_agent, $latitude,
6900				$longitude, $altitude, 0, 1, date( 'Y-m-d H:i:s'), null,
6901				1, __('Save by Pandora Console'),
6902				__('Update by Pandora Console'),
6903				__('Insert by Pandora Console'));
6904		}
6905	}
6906
6907	$data = array('type' => 'string', 'data' => (int)$correct);
6908
6909	$returnType = 'string';
6910	returnData($returnType, $data);
6911}
6912
6913function api_set_gis_agent($id_agent, $trash1, $other, $return_type, $user_in_db) {
6914	global $config;
6915
6916	if (defined ('METACONSOLE')) {
6917		return;
6918	}
6919
6920	$new_gis_data = $other['data'];
6921
6922	$correct = true;
6923
6924	if (isset($new_gis_data[0])) {
6925		$latitude = $new_gis_data[0];
6926	}
6927	else $correct = false;
6928
6929	if (isset($new_gis_data[1])) {
6930		$longitude = $new_gis_data[1];
6931	}
6932	else $correct = false;
6933
6934	if (isset($new_gis_data[2])) {
6935		$altitude = $new_gis_data[2];
6936	}
6937	else $correct = false;
6938
6939	if (isset($new_gis_data[3])) {
6940		$ignore_new_gis_data = $new_gis_data[3];
6941	}
6942	else $correct = false;
6943
6944	if (isset($new_gis_data[4])) {
6945		$manual_placement = $new_gis_data[4];
6946	}
6947	else $correct = false;
6948
6949	if (isset($new_gis_data[5])) {
6950		$start_timestamp = $new_gis_data[5];
6951	}
6952	else $correct = false;
6953
6954	if (isset($new_gis_data[6])) {
6955		$end_timestamp = $new_gis_data[6];
6956	}
6957	else $correct = false;
6958
6959	if (isset($new_gis_data[7])) {
6960		$number_of_packages = $new_gis_data[7];
6961	}
6962	else $correct = false;
6963
6964	if (isset($new_gis_data[8])) {
6965		$description_save_history = $new_gis_data[8];
6966	}
6967	else $correct = false;
6968
6969	if (isset($new_gis_data[9])) {
6970		$description_update_gis = $new_gis_data[9];
6971	}
6972	else $correct = false;
6973
6974	if (isset($new_gis_data[10])) {
6975		$description_first_insert = $new_gis_data[10];
6976	}
6977	else $correct = false;
6978
6979	if (!$config['activate_gis']) {
6980		$correct = false;
6981	}
6982	else {
6983		if ($correct) {
6984			$correct = agents_update_gis($id_agent, $latitude,
6985				$longitude, $altitude, $ignore_new_gis_data,
6986				$manual_placement, $start_timestamp, $end_timestamp,
6987				$number_of_packages, $description_save_history,
6988				$description_update_gis, $description_first_insert);
6989		}
6990	}
6991
6992	$data = array('type' => 'string', 'data' => (int)$correct);
6993
6994	$returnType = 'string';
6995	returnData($returnType, $data);
6996}
6997
6998function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db) {
6999	global $config;
7000
7001	$table_events = 'tevento';
7002	if (defined ('METACONSOLE')) {
7003		$table_events = 'tmetaconsole_event';
7004	}
7005
7006	//By default.
7007	$status = 3;
7008	$search = '';
7009	$event_type = '';
7010	$severity = -1;
7011	$id_agent = -1;
7012	$id_agentmodule = -1;
7013	$id_alert_am = -1;
7014	$id_event = -1;
7015	$id_user_ack = 0;
7016	$event_view_hr = 0;
7017	$tag = '';
7018	$group_rep = 0;
7019	$offset = 0;
7020	$pagination = 40;
7021	$utimestamp_upper = 0;
7022	$utimestamp_bottom = 0;
7023
7024	$filter = otherParameter2Filter($other, true);
7025
7026	if (isset($filter['criticity']))
7027		$severity = $filter['criticity'];
7028	if (isset($filter['id_agente']))
7029		$id_agent = $filter['id_agente'];
7030	if (isset($filter['id_agentmodule']))
7031		$id_agentmodule = $filter['id_agentmodule'];
7032	if (isset($filter['id_alert_am']))
7033		$id_alert_am = $filter['id_alert_am'];
7034	if (isset($filter['id_usuario']))
7035		$id_user_ack = $filter['id_usuario'];
7036	if (isset($filter['estado']))
7037		$status = $filter['estado'];
7038	if (isset($filter['evento']))
7039		$search = $filter['evento'];
7040	if (isset($filter['limit']))
7041		$pagination = $filter['limit'];
7042	if (isset($filter['offset']))
7043		$offset = $filter['offset'];
7044
7045
7046	$id_group = (int)$filter['id_group'];
7047
7048	$user_groups = users_get_groups ($user_in_db, "ER");
7049	$user_id_groups = array();
7050	if (!empty($user_groups))
7051		$user_id_groups = array_keys ($user_groups);
7052
7053	$is_admin = (bool)db_get_value('is_admin', 'tusuario', 'id_user',
7054		$user_in_db);
7055
7056	if (isset($filter['id_group'])) {
7057		//The admin can see all groups
7058		if ($is_admin) {
7059			if (($id_group !== -1) && ($id_group !== 0))
7060				$id_groups = array($id_group);
7061		}
7062		else {
7063			if (empty($id_group)) {
7064				$id_groups = $user_id_groups;
7065			}
7066			else {
7067				if (in_array($id_group, $user_id_groups)) {
7068					$id_groups = array($id_group);
7069				}
7070				else {
7071					$id_groups = array();
7072				}
7073			}
7074		}
7075	}
7076	else {
7077		if (!$is_admin) {
7078			$id_groups = $user_id_groups;
7079		}
7080	}
7081
7082	if (isset($filter['tag']))
7083		$tag = $filter['tag'];
7084	if (isset($filter['event_type']))
7085		$event_type = $filter['event_type'];
7086	if ($filter['utimestamp']) {
7087		if (isset($filter['utimestamp']['>'])) {
7088			$utimestamp_upper = $filter['utimestamp']['>'];
7089		}
7090		if (isset($filter['utimestamp']['<'])) {
7091			$utimestamp_bottom = $filter['utimestamp']['<'];
7092		}
7093	}
7094
7095
7096	//TODO MOVE THIS CODE AND THE CODE IN pandora_console/operation/events/events_list.php
7097	//to a function.
7098
7099
7100
7101	$sql_post = '';
7102
7103	if (!empty($id_groups)) {
7104		$sql_post = " AND id_grupo IN (".implode (",", $id_groups).")";
7105	}
7106	else {
7107		//The admin can see all groups
7108		if (!$is_admin) {
7109			$sql_post = " AND 1=0";
7110		}
7111	}
7112
7113	// Skip system messages if user is not PM
7114	if (!check_acl ($user_in_db, 0, "PM")) {
7115		$sql_post .= " AND id_grupo != 0";
7116	}
7117
7118	switch ($status) {
7119		case 0:
7120		case 1:
7121		case 2:
7122			$sql_post .= " AND estado = ".$status;
7123			break;
7124		case 3:
7125			$sql_post .= " AND (estado = 0 OR estado = 2)";
7126			break;
7127	}
7128
7129	if ($search != "") {
7130		$sql_post .= " AND evento LIKE '%".io_safe_input($search)."%'";
7131	}
7132
7133	if ($event_type != "") {
7134		// If normal, warning, could be several (going_up_warning, going_down_warning... too complex
7135		// for the user so for him is presented only "warning, critical and normal"
7136		if ($event_type == "warning" || $event_type == "critical" || $event_type == "normal") {
7137			$sql_post .= " AND event_type LIKE '%$event_type%' ";
7138		}
7139		elseif ($event_type == "not_normal") {
7140			$sql_post .= " AND ( event_type LIKE '%warning%'
7141				OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%' ) ";
7142		}
7143		else {
7144			$sql_post .= " AND event_type = '".$event_type."'";
7145		}
7146
7147	}
7148
7149	if ($severity != -1)
7150		$sql_post .= " AND criticity = ".$severity;
7151
7152	if ($id_agent != -1)
7153		$sql_post .= " AND id_agente = ".$id_agent;
7154
7155	if ($id_agentmodule != -1)
7156		$sql_post .= " AND id_agentmodule = ".$id_agentmodule;
7157
7158	if ($id_alert_am != -1)
7159		$sql_post .= " AND id_alert_am = ".$id_alert_am;
7160
7161	if ($id_event != -1)
7162		$sql_post .= " AND id_evento = " . $id_event;
7163
7164	if ($id_user_ack != "0")
7165		$sql_post .= " AND id_usuario = '" . $id_user_ack . "'";
7166
7167	if ($utimestamp_upper != 0)
7168		$sql_post .= " AND utimestamp >= " . $utimestamp_upper;
7169
7170	if ($utimestamp_bottom != 0)
7171		$sql_post .= " AND utimestamp <= " . $utimestamp_bottom;
7172
7173	if ($event_view_hr > 0) {
7174		//Put hours in seconds
7175		$unixtime = get_system_time () - ($event_view_hr * SECONDS_1HOUR);
7176		$sql_post .= " AND (utimestamp > " . $unixtime . " OR estado = 2)";
7177	}
7178
7179	//Search by tag
7180	if ($tag != "") {
7181		$sql_post .= " AND tags LIKE '" . io_safe_input($tag) . "'";
7182	}
7183
7184	//Inject the raw sql
7185	if (isset($filter['sql'])) {
7186		$sql_post .= " AND (" . $filter['sql'] . ") ";
7187	}
7188
7189
7190	if ($group_rep == 0) {
7191		switch ($config["dbtype"]) {
7192			case "mysql":
7193				if ($filter['total']) {
7194					$sql = "SELECT COUNT(*)
7195						FROM " . $table_events . "
7196						WHERE 1=1 " . $sql_post;
7197				}
7198				else if ($filter['more_criticity']) {
7199					$sql = "SELECT criticity
7200						FROM " . $table_events . "
7201						WHERE 1=1 " . $sql_post . "
7202						ORDER BY criticity DESC
7203						LIMIT 1";
7204				}
7205				else {
7206					if (defined ('METACONSOLE')) {
7207						$sql = "SELECT *,
7208							(SELECT t2.nombre
7209								FROM tgrupo t2
7210								WHERE t2.id_grupo = " . $table_events . ".id_grupo) AS group_name,
7211							(SELECT t2.icon
7212								FROM tgrupo t2
7213								WHERE t2.id_grupo = " . $table_events . ".id_grupo) AS group_icon
7214							FROM " . $table_events . "
7215							WHERE 1=1 " . $sql_post . "
7216							ORDER BY utimestamp DESC
7217							LIMIT " . $offset . "," . $pagination;
7218					}
7219					else {
7220						$sql = "SELECT *,
7221							(SELECT t1.nombre
7222								FROM tagente t1
7223								WHERE t1.id_agente = tevento.id_agente) AS agent_name,
7224							(SELECT t2.nombre
7225								FROM tgrupo t2
7226								WHERE t2.id_grupo = tevento.id_grupo) AS group_name,
7227							(SELECT t2.icon
7228								FROM tgrupo t2
7229								WHERE t2.id_grupo = tevento.id_grupo) AS group_icon,
7230							(SELECT tmodule.name
7231								FROM tmodule
7232								WHERE id_module IN (
7233									SELECT tagente_modulo.id_modulo
7234									FROM tagente_modulo
7235									WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name
7236							FROM " . $table_events . "
7237							WHERE 1=1 " . $sql_post . "
7238							ORDER BY utimestamp DESC
7239							LIMIT " . $offset . "," . $pagination;
7240					}
7241
7242				}
7243				break;
7244			case "postgresql":
7245				//TODO TOTAL
7246				$sql = "SELECT *,
7247					(SELECT t1.nombre
7248						FROM tagente t1
7249						WHERE t1.id_agente = tevento.id_agente) AS agent_name,
7250					(SELECT t2.nombre
7251						FROM tgrupo t2
7252						WHERE t2.id_grupo = tevento.id_grupo) AS group_name,
7253					(SELECT t2.icon
7254						FROM tgrupo t2
7255						WHERE t2.id_grupo = tevento.id_grupo) AS group_icon,
7256					(SELECT tmodule.name
7257						FROM tmodule
7258						WHERE id_module IN (
7259							SELECT tagente_modulo.id_modulo
7260							FROM tagente_modulo
7261							WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name
7262					FROM tevento
7263					WHERE 1=1 " . $sql_post . "
7264					ORDER BY utimestamp DESC
7265					LIMIT " . $pagination . " OFFSET " . $offset;
7266				break;
7267			case "oracle":
7268				//TODO TOTAL
7269				$set = array();
7270				$set['limit'] = $pagination;
7271				$set['offset'] = $offset;
7272
7273				$sql = "SELECT *,
7274					(SELECT t1.nombre
7275						FROM tagente t1
7276						WHERE t1.id_agente = tevento.id_agente) AS agent_name,
7277					(SELECT t2.nombre
7278						FROM tgrupo t2
7279						WHERE t2.id_grupo = tevento.id_grupo) AS group_name,
7280					(SELECT t2.icon
7281						FROM tgrupo t2
7282						WHERE t2.id_grupo = tevento.id_grupo) AS group_icon,
7283					(SELECT tmodule.name
7284						FROM tmodule
7285						WHERE id_module IN (
7286							SELECT tagente_modulo.id_modulo
7287							FROM tagente_modulo
7288							WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name
7289					FROM tevento
7290					WHERE 1=1 " . $sql_post . " ORDER BY utimestamp DESC";
7291				$sql = oracle_recode_query ($sql, $set);
7292				break;
7293		}
7294	}
7295	else {
7296		switch ($config["dbtype"]) {
7297			case "mysql":
7298				db_process_sql ('SET group_concat_max_len = 9999999');
7299
7300				$sql = "SELECT *, MAX(id_evento) AS id_evento,
7301						GROUP_CONCAT(DISTINCT user_comment SEPARATOR '') AS user_comment,
7302						MIN(estado) AS min_estado, MAX(estado) AS max_estado,
7303						COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep
7304					FROM " . $table_events . "
7305					WHERE 1=1 " . $sql_post . "
7306					GROUP BY evento, id_agentmodule
7307					ORDER BY timestamp_rep DESC
7308					LIMIT " . $offset . "," . $pagination;
7309				break;
7310			case "postgresql":
7311				$sql = "SELECT *, MAX(id_evento) AS id_evento,
7312						array_to_string(array_agg(DISTINCT user_comment), '') AS user_comment,
7313						MIN(estado) AS min_estado, MAX(estado) AS max_estado,
7314						COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep
7315					FROM " . $table_events . "
7316					WHERE 1=1 " . $sql_post . "
7317					GROUP BY evento, id_agentmodule
7318					ORDER BY timestamp_rep DESC
7319					LIMIT " . $pagination . " OFFSET " . $offset;
7320				break;
7321			case "oracle":
7322				$set = array();
7323				$set['limit'] = $pagination;
7324				$set['offset'] = $offset;
7325				// TODO: Remove duplicate user comments
7326				$sql = "SELECT a.*, b.event_rep, b.timestamp_rep
7327					FROM (SELECT *
7328						FROM tevento
7329						WHERE 1=1 ".$sql_post.") a,
7330					(SELECT MAX (id_evento) AS id_evento,
7331						to_char(evento) AS evento, id_agentmodule,
7332						COUNT(*) AS event_rep, MIN(estado) AS min_estado,
7333						MAX(estado) AS max_estado,
7334						LISTAGG(user_comment, '') AS user_comment,
7335						MAX(utimestamp) AS timestamp_rep
7336					FROM " . $table_events . "
7337					WHERE 1=1 ".$sql_post."
7338					GROUP BY to_char(evento), id_agentmodule) b
7339					WHERE a.id_evento=b.id_evento AND
7340						to_char(a.evento)=to_char(b.evento) AND
7341						a.id_agentmodule=b.id_agentmodule";
7342				$sql = oracle_recode_query ($sql, $set);
7343				break;
7344		}
7345
7346	}
7347
7348	if ($other['type'] == 'string') {
7349		if ($other['data'] != '') {
7350			returnError('error_parameter', 'Error in the parameters.');
7351			return;
7352		}
7353		else {//Default values
7354			$separator = ';';
7355		}
7356	}
7357	else if ($other['type'] == 'array') {
7358		$separator = $other['data'][0];
7359	}
7360	//html_debug_print($filter, true);
7361	$result = db_get_all_rows_sql ($sql);
7362	//html_debug_print($sql, true);
7363
7364	if (($result !== false) &&
7365		(!$filter['total']) &&
7366		(!$filter['more_criticity'])) {
7367
7368		$urlImage = ui_get_full_url(false);
7369
7370		//Add the description and image
7371		foreach ($result as $key => $row) {
7372			if (defined ('METACONSOLE')) {
7373				$row['agent_name'] = agents_meta_get_name (
7374					$row['id_agente'],
7375					"none", $row['server_id']);
7376
7377				$row['module_name'] = meta_modules_get_name(
7378					$row['id_agentmodule'], $row['server_id']);
7379			}
7380
7381			//FOR THE TEST THE API IN THE ANDROID
7382			//$row['evento'] = $row['id_evento'];
7383
7384			$row['description_event'] = events_print_type_description($row["event_type"], true);
7385			$row['img_description'] = events_print_type_img ($row["event_type"], true, true);
7386			$row['criticity_name'] = get_priority_name ($row["criticity"]);
7387
7388			switch ($row["criticity"]) {
7389				default:
7390				case EVENT_CRIT_MAINTENANCE:
7391					$img_sev = $urlImage .
7392						"/images/status_sets/default/severity_maintenance.png";
7393					break;
7394				case EVENT_CRIT_INFORMATIONAL:
7395					$img_sev = $urlImage .
7396						"/images/status_sets/default/severity_informational.png";
7397					break;
7398				case EVENT_CRIT_NORMAL:
7399					$img_sev = $urlImage .
7400						"/images/status_sets/default/severity_normal.png";
7401					break;
7402				case EVENT_CRIT_WARNING:
7403					$img_sev = $urlImage .
7404						"/images/status_sets/default/severity_warning.png";
7405					break;
7406				case EVENT_CRIT_CRITICAL:
7407					$img_sev = $urlImage .
7408						"/images/status_sets/default/severity_critical.png";
7409					break;
7410			}
7411			$row['img_criticy'] = $img_sev;
7412
7413
7414			$result[$key] = $row;
7415		}
7416	}
7417
7418	//html_debug_print($result);
7419
7420	$data['type'] = 'array';
7421	$data['data'] = $result;
7422
7423	returnData($returnType, $data, $separator);
7424
7425	if (empty($result))
7426		return false;
7427
7428	return true;
7429}
7430
7431/**
7432 *
7433 * @param $trash1
7434 * @param $trah2
7435 * @param $other
7436 * @param $returnType
7437 * @param $user_in_db
7438 */
7439function api_get_events($trash1, $trash2, $other, $returnType, $user_in_db = null) {
7440	if ($user_in_db !== null) {
7441		$correct = get_events_with_user($trash1, $trash2, $other,
7442			$returnType, $user_in_db);
7443
7444		$last_error = error_get_last();
7445		if (!$correct && !empty($last_error)) {
7446			$errors = array(E_ERROR, E_WARNING, E_USER_ERROR,
7447				E_USER_WARNING);
7448			if (in_array($last_error['type'], $errors)) {
7449				returnError('ERROR_API_PANDORAFMS', $returnType);
7450			}
7451		}
7452
7453		return;
7454	}
7455
7456
7457
7458	if ($other['type'] == 'string') {
7459		if ($other['data'] != '') {
7460			returnError('error_parameter', 'Error in the parameters.');
7461			return;
7462		}
7463		else {//Default values
7464			$separator = ';';
7465		}
7466	}
7467	else if ($other['type'] == 'array') {
7468		$separator = $other['data'][0];
7469
7470		$filterString = otherParameter2Filter($other);
7471	}
7472
7473
7474	if (defined ('METACONSOLE')) {
7475		$dataRows = db_get_all_rows_filter('tmetaconsole_event', $filterString);
7476	}
7477	else {
7478		$dataRows = db_get_all_rows_filter('tevento', $filterString);
7479	}
7480	$last_error = error_get_last();
7481	if (empty($dataRows)) {
7482		if (!empty($last_error)) {
7483			returnError('ERROR_API_PANDORAFMS', $returnType);
7484
7485			return;
7486		}
7487	}
7488
7489	$data['type'] = 'array';
7490	$data['data'] = $dataRows;
7491
7492	returnData($returnType, $data, $separator);
7493	return;
7494}
7495
7496/**
7497 * Delete user.
7498 *
7499 * @param $id string Username to delete.
7500 * @param $thrash1 Don't use.
7501 * @param $thrash2 Don't use.
7502 * @param $thrash3 Don't use.
7503 */
7504function api_set_delete_user($id, $thrash1, $thrash2, $thrash3) {
7505	if (defined ('METACONSOLE')) {
7506		return;
7507	}
7508
7509	if (!delete_user($id))
7510		returnError('error_delete_user', 'Error delete user');
7511	else
7512		returnData('string', array('type' => 'string', 'data' => __('Delete user.')));
7513}
7514
7515/**
7516 * Add user to profile and group.
7517 *
7518 * @param $id string Username to delete.
7519 * @param $thrash1 Don't use.
7520 * @param array $other it's array, $other as param is <group>;<profile> in this
7521 *  order and separator char (after text ; ) and separator (pass in param
7522 *  othermode as othermode=url_encode_separator_<separator>)
7523 *  example:
7524 *
7525 *  api.php?op=set&op2=add_user_profile&id=example_user_name&other=12|4&other_mode=url_encode_separator_|
7526 *
7527 * @param $thrash2 Don't use.
7528
7529 */
7530function api_set_add_user_profile($id, $thrash1, $other, $thrash2) {
7531	if (defined ('METACONSOLE')) {
7532		return;
7533	}
7534
7535	$group = $other['data'][0];
7536	$profile = $other['data'][1];
7537
7538	if (!profile_create_user_profile ($id, $profile, $group,'API'))
7539		returnError('error_add_user_profile', 'Error add user profile.');
7540	else
7541		returnData('string', array('type' => 'string', 'data' => __('Add user profile.')));
7542}
7543
7544/**
7545 * Deattach user from group and profile.
7546 *
7547 * @param $id string Username to delete.
7548 * @param $thrash1 Don't use.
7549 * @param array $other it's array, $other as param is <group>;<profile> in this
7550 *  order and separator char (after text ; ) and separator (pass in param
7551 *  othermode as othermode=url_encode_separator_<separator>)
7552 *  example:
7553 *
7554 *  api.php?op=set&op2=delete_user_profile&id=md&other=12|4&other_mode=url_encode_separator_|
7555 *
7556 * @param $thrash2 Don't use.
7557 */
7558function api_set_delete_user_profile($id, $thrash1, $other, $thrash2) {
7559	if (defined ('METACONSOLE')) {
7560		return;
7561	}
7562
7563	$group = $other['data'][0];
7564	$profile = $other['data'][1];
7565
7566	$where = array(
7567		'id_usuario' => $id,
7568		'id_perfil' => $profile,
7569		'id_grupo' => $group);
7570	$result = db_process_sql_delete('tusuario_perfil', $where);
7571	if ($return === false)
7572		returnError('error_delete_user_profile', 'Error delete user profile.');
7573	else
7574		returnData('string', array('type' => 'string', 'data' => __('Delete user profile.')));
7575}
7576
7577/**
7578 * Create new incident in Pandora.
7579 *
7580 * @param $thrash1 Don't use.
7581 * @param $thrash2 Don't use.
7582 * @param array $other it's array, $other as param is <title>;<description>;
7583 *  <origin>;<priority>;<state>;<group> in this order and separator char
7584 *  (after text ; ) and separator (pass in param othermode as
7585 *  othermode=url_encode_separator_<separator>)
7586 *  example:
7587 *
7588 *  api.php?op=set&op2=new_incident&other=titulo|descripcion%20texto|Logfiles|2|10|12&other_mode=url_encode_separator_|
7589 *
7590 * @param $thrash3 Don't use.
7591 */
7592function api_set_new_incident($thrash1, $thrash2, $other, $thrash3) {
7593	if (defined ('METACONSOLE')) {
7594		return;
7595	}
7596
7597	$title = $other['data'][0];
7598	$description = $other['data'][1];
7599	$origin = $other['data'][2];
7600	$priority = $other['data'][3];
7601	$id_creator = 'API';
7602	$state = $other['data'][4];
7603	$group = $other['data'][5];
7604
7605	$values = array(
7606		'inicio' => 'NOW()',
7607		'actualizacion' => 'NOW()',
7608		'titulo' => $title,
7609		'descripcion' => $description,
7610		'id_usuario' => 'API',
7611		'origen' => $origin,
7612		'estado' => $state,
7613		'prioridad' => $priority,
7614		'id_grupo' => $group,
7615		'id_creator' => $id_creator);
7616	$idIncident = db_process_sql_insert('tincidencia', $values);
7617
7618	if ($return === false)
7619		returnError('error_new_incident', 'Error create new incident.');
7620	else
7621		returnData('string', array('type' => 'string', 'data' => $idIncident));
7622}
7623
7624/**
7625 * Add note into a incident.
7626 *
7627 * @param $id string Username author of note.
7628 * @param $id2 integer ID of incident.
7629 * @param $other string Note.
7630 * @param $thrash2 Don't use.
7631 */
7632function api_set_new_note_incident($id, $id2, $other, $thrash2) {
7633	if (defined ('METACONSOLE')) {
7634		return;
7635	}
7636
7637	$values = array(
7638		'id_usuario' => $id,
7639		'id_incident' => $id2,
7640		'nota' => $other['data']);
7641
7642	$idNote = db_process_sql_insert('tnota', $values);
7643
7644	if ($idNote === false)
7645		returnError('error_new_incident', 'Error create new incident.');
7646	else
7647		returnData('string', array('type' => 'string', 'data' => $idNote));
7648}
7649
7650
7651/**
7652 * Disable a module, given agent and module name.
7653 *
7654 * @param string $agent_name Name of agent.
7655 * @param string $module_name Name of the module
7656 * @param $thrash3 Don't use.
7657 * @param $thrash4 Don't use.
7658// http://localhost/pandora_console/include/api.php?op=set&op2=enable_module&id=garfio&id2=Status
7659 */
7660
7661function api_set_disable_module ($agent_name, $module_name, $thrast3, $thrash4) {
7662	if (defined ('METACONSOLE')) {
7663		return;
7664	}
7665
7666	$id_agent = agents_get_agent_id($agent_name);
7667	$id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $id_agent, 'nombre' => $module_name));
7668
7669	$result = modules_change_disabled($id_agent_module, 1);
7670
7671	if ($result === NOERR) {
7672		returnData('string', array('type' => 'string', 'data' => __('Correct module disable')));
7673	}
7674	else {
7675		returnData('string', array('type' => 'string', 'data' => __('Error disabling module')));
7676	}
7677}
7678
7679
7680/**
7681 * Enable a module, given agent and module name.
7682 *
7683 * @param string $agent_name Name of agent.
7684 * @param string $module_name Name of the module
7685 * @param $thrash3 Don't use.
7686 * @param $thrash4 Don't use.
7687 */
7688
7689function api_set_enable_module ($agent_name, $module_name, $thrast3, $thrash4) {
7690
7691	if (defined ('METACONSOLE')) {
7692		return;
7693	}
7694
7695	$id_agent = agents_get_agent_id($agent_name);
7696	$id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $id_agent, 'nombre' => $module_name));
7697
7698	$result = modules_change_disabled($id_agent_module, 0);
7699
7700	if ($result === NOERR) {
7701		returnData('string', array('type' => 'string', 'data' => __('Correct module enable')));
7702	}
7703	else {
7704		returnData('string', array('type' => 'string', 'data' => __('Error enabling module')));
7705	}
7706}
7707
7708
7709/**
7710 * Disable an alert
7711 *
7712 * @param string $agent_name Name of agent (for example "myagent")
7713 * @param string $module_name Name of the module (for example "Host alive")
7714 * @param string $template_name Name of the alert template (for example, "Warning event")
7715 * @param $thrash4 Don't use.
7716
7717// http://localhost/pandora_console/include/api.php?op=set&op2=disable_alert&id=garfio&id2=Status&other=Warning%20condition
7718 */
7719
7720function api_set_disable_alert ($agent_name, $module_name, $template_name, $thrash4) {
7721	if (defined ('METACONSOLE')) {
7722		return;
7723	}
7724
7725	$id_agent = agents_get_agent_id($agent_name);
7726	$id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $id_agent, 'nombre' => $module_name));
7727	$id_template = db_get_value_filter('id', 'talert_templates', array('name' => $template_name["data"]));
7728
7729	db_process_sql("UPDATE talert_template_modules
7730		SET disabled = 1
7731		WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template");
7732
7733	returnData('string', array('type' => 'string', 'data' => "Correct alert disable"));
7734}
7735
7736/**
7737 * Enable an alert
7738 *
7739 * @param string $agent_name Name of agent (for example "myagent")
7740 * @param string $module_name Name of the module (for example "Host alive")
7741 * @param string $template_name Name of the alert template (for example, "Warning event")
7742 * @param $thrash4 Don't use.
7743
7744// http://localhost/pandora_console/include/api.php?op=set&op2=enable_alert&id=garfio&id2=Status&other=Warning%20condition
7745 */
7746
7747function api_set_enable_alert ($agent_name, $module_name, $template_name, $thrash4) {
7748
7749	if (defined ('METACONSOLE')) {
7750		return;
7751	}
7752
7753	$id_agent = agents_get_agent_id($agent_name);
7754	$id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $id_agent, 'nombre' => $module_name));
7755	$id_template = db_get_value_filter('id', 'talert_templates', array('name' => $template_name["data"]));
7756
7757	db_process_sql("UPDATE talert_template_modules
7758		SET disabled = 0
7759		WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template");
7760
7761	returnData('string', array('type' => 'string', 'data' => "Correct alert enable"));
7762}
7763
7764/**
7765 * Disable all the alerts of one module
7766 *
7767 * @param string $agent_name Name of agent (for example "myagent")
7768 * @param string $module_name Name of the module (for example "Host alive")
7769 * @param $thrash3 Don't use.
7770 * @param $thrash4 Don't use.
7771
7772// http://localhost/pandora_console/include/api.php?op=set&op2=disable_module_alerts&id=garfio&id2=Status
7773 */
7774
7775function api_set_disable_module_alerts ($agent_name, $module_name, $thrash3, $thrash4) {
7776
7777	if (defined ('METACONSOLE')) {
7778		return;
7779	}
7780
7781
7782	$id_agent = agents_get_agent_id($agent_name);
7783	$id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $id_agent, 'nombre' => $module_name));
7784
7785	db_process_sql("UPDATE talert_template_modules
7786		SET disabled = 1
7787		WHERE id_agent_module = $id_agent_module");
7788
7789	returnData('string', array('type' => 'string', 'data' => "Correct alerts disable"));
7790}
7791
7792/**
7793 * Enable all the alerts of one module
7794 *
7795 * @param string $agent_name Name of agent (for example "myagent")
7796 * @param string $module_name Name of the module (for example "Host alive")
7797 * @param $thrash3 Don't use.
7798 * @param $thrash4 Don't use.
7799
7800// http://localhost/pandora_console/include/api.php?op=set&op2=enable_module_alerts&id=garfio&id2=Status
7801 */
7802
7803function api_set_enable_module_alerts ($agent_name, $module_name, $thrash3, $thrash4) {
7804
7805	if (defined ('METACONSOLE')) {
7806		return;
7807	}
7808
7809	$id_agent = agents_get_agent_id($agent_name);
7810	$id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $id_agent, 'nombre' => $module_name));
7811
7812	db_process_sql("UPDATE talert_template_modules
7813		SET disabled = 0
7814		WHERE id_agent_module = $id_agent_module");
7815
7816	returnData('string', array('type' => 'string', 'data' => "Correct alerts enable"));
7817}
7818
7819function api_get_tags($thrash1, $thrash2, $other, $returnType, $user_in_db) {
7820	if (defined ('METACONSOLE')) {
7821		return;
7822	}
7823
7824	if ($other['type'] == 'string') {
7825		if ($other['data'] != '') {
7826			returnError('error_parameter', 'Error in the parameters.');
7827			return;
7828		}
7829		else {//Default values
7830			$separator = ';';
7831		}
7832	}
7833	else if ($other['type'] == 'array') {
7834		$separator = $other['data'][0];
7835	}
7836
7837	$tags = tags_get_all_tags();
7838
7839	$data_tags = array();
7840	foreach ($tags as $id => $tag) {
7841		$data_tags[] = array($id, $tag);
7842	}
7843
7844	$data['type'] = 'array';
7845	$data['data'] = $data_tags;
7846
7847	returnData($returnType, $data, $separator);
7848}
7849
7850/**
7851 * Total modules for a group given
7852 *
7853 * @param int $id_group
7854 *
7855**/
7856// http://localhost/pandora_console/include/api.php?op=get&op2=total_modules&id=1&apipass=1234&user=admin&pass=pandora
7857function api_get_total_modules($id_group, $trash1, $trash2, $returnType) {
7858	if (defined ('METACONSOLE')) {
7859		return;
7860	}
7861
7862	$sql = "SELECT COUNT(*)
7863		FROM tagente_modulo
7864		WHERE id_module_group=$id_group AND delete_pending = 0";
7865
7866	$total = db_get_value_sql($sql);
7867
7868	$data = array('type' => 'string', 'data' => $total);
7869
7870	returnData($returnType, $data);
7871}
7872
7873/**
7874 * Total modules for a given group
7875 *
7876 * @param int $id_group
7877 *
7878**/
7879// http://localhost/pandora_console/include/api.php?op=get&op2=total_agents&id=2&apipass=1234&user=admin&pass=pandora
7880function api_get_total_agents($id_group, $trash1, $trash2, $returnType) {
7881	if (defined ('METACONSOLE')) {
7882		return;
7883	}
7884
7885	$sql = sprintf('SELECT COUNT(*)
7886		FROM tagente
7887		WHERE id_grupo=%d AND disabled=0', $id_group);
7888	$total_agents = db_get_value_sql($sql);
7889
7890	$data = array('type' => 'string', 'data' => $total_agents);
7891	returnData($returnType, $data);
7892}
7893
7894/**
7895 * Agent name for a given id
7896 *
7897 * @param int $id_group
7898 *
7899**/
7900// http://localhost/pandora_console/include/api.php?op=get&op2=agent_name&id=1&apipass=1234&user=admin&pass=pandora
7901function api_get_agent_name($id_agent, $trash1, $trash2, $returnType) {
7902	if (defined ('METACONSOLE')) {
7903		return;
7904	}
7905
7906	$sql = sprintf('SELECT nombre
7907		FROM tagente
7908		WHERE id_agente = %d', $id_agent);
7909	$value = db_get_value_sql($sql);
7910	if ($value === false) {
7911		returnError('id_not_found', $returnType);
7912	}
7913
7914	$data = array('type' => 'string', 'data' => $value);
7915
7916	returnData($returnType, $data);
7917}
7918
7919/**
7920 * Module name for a given id
7921 *
7922 * @param int $id_group
7923 *
7924**/
7925// http://localhost/pandora_console/include/api.php?op=get&op2=module_name&id=20&apipass=1234&user=admin&pass=pandora
7926function api_get_module_name($id_module, $trash1, $trash2, $returnType) {
7927	if (defined ('METACONSOLE')) {
7928		return;
7929	}
7930
7931	$sql = sprintf('SELECT nombre
7932		FROM tagente_modulo
7933		WHERE id_agente_modulo = %d', $id_module);
7934
7935	$value = db_get_value_sql($sql);
7936
7937	if ($value === false) {
7938		returnError('id_not_found', $returnType);
7939	}
7940
7941	$data = array('type' => 'string', 'data' => $value);
7942
7943	returnData($returnType, $data);
7944}
7945
7946// http://localhost/pandora_console/include/api.php?op=get&op2=alert_action_by_group&id=3&id2=1&apipass=1234&user=admin&pass=pandora
7947function api_get_alert_action_by_group($id_group, $id_action, $trash2, $returnType) {
7948	if (defined ('METACONSOLE')) {
7949		return;
7950	}
7951
7952	$sql = "SELECT SUM(internal_counter)
7953		FROM talert_template_modules
7954		WHERE id_alert_template IN
7955			(SELECT id
7956			FROM talert_templates
7957			WHERE id_group=$id_group AND id_alert_action = $id_action)";
7958
7959	$value = db_get_value_sql($sql);
7960
7961	if ($value === false) {
7962		returnError('data_not_found', $returnType);
7963	}
7964	else if ($value == '') {
7965		$value = 0;
7966	}
7967
7968	$data = array('type' => 'string', 'data' => $value);
7969
7970	returnData($returnType, $data);
7971}
7972
7973// http://localhost/pandora_console/include/api.php?op=get&op2=event_info&id=58&apipass=1234&user=admin&pass=pandora
7974function api_get_event_info($id_event, $trash1, $trash, $returnType) {
7975
7976	$table_events = 'tevento';
7977	if (defined ('METACONSOLE')) {
7978		$table_events = 'tmetaconsole_event';
7979	}
7980
7981	$sql = "SELECT *
7982		FROM " . $table_events . "
7983		WHERE id_evento=$id_event";
7984	$event_data = db_get_row_sql($sql);
7985
7986	$i = 0;
7987	foreach ($event_data as $key => $data) {
7988		$data = strip_tags($data);
7989		$data = str_replace("\n",' ',$data);
7990		$data = str_replace(';',' ',$data);
7991		if ($i == 0)
7992			$result = $key.': '.$data.'<br>';
7993		else
7994			$result .= $key.': '.$data.'<br>';
7995		$i++;
7996	}
7997
7998	$data = array('type' => 'string', 'data' => $result);
7999
8000	returnData($returnType, $data);
8001	return;
8002}
8003
8004//http://127.0.0.1/pandora_console/include/api.php?op=set&op2=create_tag&other=tag_name|tag_description|tag_url|tag_email&other_mode=url_encode_separator_|&apipass=1234&user=admin&pass=pandora
8005function api_set_create_tag ($id, $trash1, $other, $returnType) {
8006
8007	if (defined ('METACONSOLE')) {
8008		return;
8009	}
8010
8011	$data = array();
8012
8013	if ($other['type'] == 'string') {
8014		$data["name"] = $other["data"];
8015	}
8016	else if ($other['type'] == 'array') {
8017
8018		$data['name'] = $other["data"][0];
8019
8020		if ($other["data"][1] != '') {
8021			$data['description'] = $other["data"][1];
8022		}
8023		else {
8024			$data['description'] = "";
8025		}
8026
8027		if ($other["data"][1] != '') {
8028			$data['url'] = $other["data"][2];
8029		}
8030		else {
8031			$data['url'] = "";
8032		}
8033
8034		if ($other["data"][1] != '') {
8035			$data['email'] = $other["data"][3];
8036		}
8037		else {
8038			$data['email'] = '';
8039		}
8040	}
8041
8042	if (tags_create_tag ($data)) {
8043		returnData('string',
8044			array('type' => 'string', 'data' => '1'));
8045	}
8046	else {
8047		returnError('error_set_tag_user_profile', 'Error create tag user profile.');
8048	}
8049}
8050
8051
8052//http://127.0.0.1/pandora_console/include/api.php?op=set&op2=create_event&id=name_event&other=2|system|3|admin|2|1|10|0|comments||Pandora||critical_inst|warning_inst|unknown_inst|other||&other_mode=url_encode_separator_|&apipass=1234&user=admin&pass=pandora
8053function api_set_create_event($id, $trash1, $other, $returnType) {
8054
8055	if ($other['type'] == 'string') {
8056		returnError('error_parameter', 'Error in the parameters.');
8057		return;
8058	}
8059	else if ($other['type'] == 'array') {
8060
8061		$values = array();
8062
8063		if ($other['data'][0] != '') {
8064			$values['event'] = $other['data'][0];
8065		}
8066		else {
8067			returnError('error_parameter', 'Event text required.');
8068			return;
8069		}
8070
8071		if ($other['data'][1] != '') {
8072			$values['id_grupo'] = $other['data'][1];
8073		}
8074		else {
8075			returnError('error_parameter', 'Group ID required.');
8076			return;
8077		}
8078
8079		if ($other['data'][2] != '') {
8080			$values['id_agente'] = $other['data'][2];
8081		}
8082		else {
8083			returnError('error_parameter', 'Agent ID required.');
8084			return;
8085		}
8086
8087		if ($other['data'][3] != '') {
8088			$values['status'] = $other['data'][3];
8089		}
8090		else {
8091			$values['status'] = 0;
8092		}
8093
8094		$values['id_usuario'] = $other['data'][4];
8095
8096		if ($other['data'][5] != '') {
8097			$values['event_type'] = $other['data'][5];
8098		}
8099		else {
8100			$values['event_type'] = "unknown";
8101		}
8102
8103		if ($other['data'][6] != '') {
8104			$values['priority'] = $other['data'][6];
8105		}
8106		else {
8107			$values['priority'] = 0;
8108		}
8109
8110		if ($other['data'][7] != '') {
8111			$values['id_agentmodule'] = $other['data'][7];
8112		}
8113		else {
8114			$value['id_agentmodule'] = 0;
8115		}
8116
8117		if ($other['data'][8] != '') {
8118			$values['id_alert_am'] = $other['data'][8];
8119		}
8120		else {
8121			$values['id_alert_am'] = 0;
8122		}
8123
8124		if ($other['data'][9] != '') {
8125			$values['critical_instructions'] = $other['data'][9];
8126		}
8127		else {
8128			$values['critical_instructions'] = '';
8129		}
8130
8131		if ($other['data'][10] != '') {
8132			$values['warning_instructions'] = $other['data'][10];
8133		}
8134		else {
8135			$values['warning_instructions'] = '';
8136		}
8137
8138		if ($other['data'][11] != '') {
8139			$values['unknown_instructions'] = $other['data'][11];
8140		}
8141		else {
8142			$values['unknown_instructions'] = '';
8143		}
8144
8145		if ($other['data'][14] != '') {
8146			$values['source'] = $other['data'][14];
8147		}
8148		else {
8149			$values['source'] = "Pandora";
8150		}
8151
8152		if ($other['data'][15] != '') {
8153			$values['tags'] = $other['data'][15];
8154		}
8155		else {
8156			$values['tags'] = "";
8157		}
8158
8159		if ($other['data'][16] != '') {
8160			$values['custom_data'] = $other['data'][16];
8161		}
8162		else {
8163			$values['custom_data'] = "";
8164		}
8165
8166		if ($other['data'][17] != '') {
8167			$values['server_id'] = $other['data'][17];
8168		}
8169		else {
8170			$values['server_id'] = 0;
8171		}
8172
8173		$return = events_create_event(
8174			$values['event'], $values['id_grupo'], $values['id_agente'],
8175			$values['status'], $values['id_usuario'],
8176			$values['event_type'], $values['priority'],
8177			$values['id_agentmodule'], $values['id_alert_am'],
8178			$values['critical_instructions'],
8179			$values['warning_instructions'],
8180			$values['unknown_instructions'], $values['source'],
8181			$values['tags'], $values['custom_data'],
8182			$values['server_id']);
8183
8184		if ($other['data'][12] != '') { //user comments
8185			if ($return !== false) { //event successfully created
8186				$user_comment = $other['data'][12];
8187				$res = events_comment ($return, $user_comment,
8188					'Added comment', defined ('METACONSOLE'),
8189					$config['history_db_enabled']);
8190				if ($other['data'][13] != '') { //owner user
8191					if ($res !== false) { //comment added
8192						$owner_user = $other['data'][13];
8193						events_change_owner ($return, $owner_user,
8194							true, defined ('METACONSOLE'),
8195							$config['history_db_enabled']);
8196					}
8197				}
8198			}
8199		}
8200
8201		$data['type'] = 'string';
8202		if ($return === false) {
8203			$data['data'] = 0;
8204		}
8205		else {
8206			$data['data'] = $return;
8207		}
8208
8209		returnData($returnType, $data);
8210		return;
8211	}
8212}
8213
8214/**
8215 * Add event commet.
8216 *
8217 * @param $id event id.
8218 * @param $thrash2 Don't use.
8219 * @param array $other it's array, but only <csv_separator> is available.
8220 * @param $thrash3 Don't use.
8221 *
8222 * example:
8223 *   http://127.0.0.1/pandora_console/include/api.php?op=set&op2=add_event_comment&id=event_id&other=string|&other_mode=url_encode_separator_|&apipass=1234&user=admin&pass=pandora
8224 */
8225function api_set_add_event_comment($id, $thrash2, $other, $thrash3) {
8226	if (defined ('METACONSOLE')) {
8227		return;
8228	}
8229
8230	if ($other['type'] == 'string') {
8231		returnError('error_parameter', 'Error in the parameters.');
8232		return;
8233	}
8234	else if ($other['type'] == 'array') {
8235		$comment = io_safe_input($other['data'][0]);
8236		$meta = $other['data'][1];
8237		$history = $other['data'][2];
8238
8239		$status = events_comment($id, $comment, 'Added comment', $meta,
8240			$history);
8241		if (is_error($status)) {
8242			returnError('error_add_event_comment',
8243				__('Error adding event comment.'));
8244			return;
8245		}
8246	}
8247
8248	returnData('string', array('type' => 'string', 'data' => $status));
8249	return;
8250}
8251
8252// http://localhost/pandora_console/include/api.php?op=get&op2=tactical_view&apipass=1234&user=admin&pass=pandora
8253function api_get_tactical_view($trash1, $trash2, $trash3, $returnType) {
8254	if (defined ('METACONSOLE')) {
8255		return;
8256	}
8257
8258	$tactical_info = reporting_get_group_stats();
8259
8260	switch ($returnType) {
8261		case 'string':
8262			$i = 0;
8263			foreach ($tactical_info as $key => $data) {
8264				if ($i == 0)
8265					$result = $key . ': ' . $data . '<br>';
8266				else
8267					$result .= $key . ': ' . $data . '<br>';
8268
8269				$i++;
8270			}
8271
8272			$data = array('type' => 'string', 'data' => $result);
8273			break;
8274		case 'csv':
8275			$data = array('type' => 'array', 'data' => array($tactical_info));
8276			break;
8277	}
8278
8279	returnData($returnType, $data);
8280	return;
8281
8282}
8283
8284// http://localhost/pandora_console/include/api.php?op=get&op2=netflow_get_data&other=1348562410|1348648810|0|base64_encode(json_encode($filter))|none|50|bytes&other_mode=url_encode_separator_|&apipass=pandora&user=pandora&pass=pandora'
8285function api_get_netflow_get_data ($discard_1, $discard_2, $params) {
8286	if (defined ('METACONSOLE')) {
8287		return;
8288	}
8289
8290	// Parse function parameters
8291	$start_date = $params['data'][0];
8292	$end_date = $params['data'][1];
8293	$interval_length = $params['data'][2];
8294	$filter = json_decode (base64_decode ($params['data'][3]), true);
8295	$aggregate = $params['data'][4];
8296	$max = $params['data'][5];
8297	$unit = $params['data'][6];
8298	$address_resolution = $params['data'][7];
8299
8300	// Get netflow data
8301	$data = netflow_get_data ($start_date, $end_date, $interval_length, $filter, $aggregate, $max, $unit, '', $address_resolution);
8302
8303	returnData('json', $data);
8304	return;
8305}
8306
8307// http://localhost/pandora_console/include/api.php?op=get&op2=netflow_get_stats&other=1348562410|1348648810|base64_encode(json_encode($filter))|none|50|bytes&other_mode=url_encode_separator_|&apipass=pandora&user=pandora&pass=pandora'
8308function api_get_netflow_get_stats ($discard_1, $discard_2, $params) {
8309	if (defined ('METACONSOLE')) {
8310		return;
8311	}
8312
8313	// Parse function parameters
8314	$start_date = $params['data'][0];
8315	$end_date = $params['data'][1];
8316	$filter = json_decode (base64_decode ($params['data'][2]), true);
8317	$aggregate = $params['data'][3];
8318	$max = $params['data'][4];
8319	$unit = $params['data'][5];
8320	$address_resolution = $params['data'][6];
8321
8322	// Get netflow data
8323	$data = netflow_get_stats ($start_date, $end_date, $filter, $aggregate, $max, $unit, '', $address_resolution);
8324
8325	returnData('json', $data);
8326	return;
8327}
8328
8329// http://localhost/pandora_console/include/api.php?op=get&op2=netflow_get_summary&other=1348562410|1348648810|_base64_encode(json_encode($filter))&other_mode=url_encode_separator_|&apipass=pandora&user=pandora&pass=pandora'
8330function api_get_netflow_get_summary ($discard_1, $discard_2, $params) {
8331	if (defined ('METACONSOLE')) {
8332		return;
8333	}
8334
8335	// Parse function parameters
8336	$start_date = $params['data'][0];
8337	$end_date = $params['data'][1];
8338	$filter = json_decode (base64_decode ($params['data'][2]), true);
8339
8340	// Get netflow data
8341	$data = netflow_get_summary ($start_date, $end_date, $filter);
8342	returnData('json', $data);
8343	return;
8344}
8345
8346//http://localhost/pandora_console/include/api.php?op=set&op2=validate_event_by_id&id=23&apipass=1234&user=admin&pass=pandora
8347function api_set_validate_event_by_id ($id, $trash1, $trash2, $returnType) {
8348	global $config;
8349
8350	$data['type'] = 'string';
8351	$check_id = db_get_value('id_evento', 'tevento', 'id_evento', $id);
8352
8353	if ($check_id) { //event exists
8354
8355		$status = db_get_value('estado', 'tevento', 'id_evento', $id);
8356		if ($status == 1) { //event already validated
8357			$data['data'] = "Event already validated";
8358		}
8359		else {
8360			$ack_utimestamp = time();
8361
8362			events_comment($id, '', "Change status to validated");
8363
8364			$values = array(
8365				'ack_utimestamp' => $ack_utimestamp,
8366				'estado' => 1
8367				);
8368
8369			$result = db_process_sql_update('tevento', $values, array('id_evento' => $id));
8370
8371			if ($result === false) {
8372				$data['data'] = "Error validating event";
8373			}
8374			else {
8375				$data['data'] = "Event validate";
8376			}
8377		}
8378
8379	}
8380	else {
8381		$data['data'] = "Event not exists";
8382	}
8383
8384	returnData($returnType, $data);
8385	return;
8386}
8387
8388/**
8389 *
8390 * @param $trash1
8391 * @param $trash2
8392 * @param array $other it's array, but only <csv_separator> is available.
8393 * @param $returnType
8394 *
8395 */
8396//  http://localhost/pandora_console/include/api.php?op=get&op2=pandora_servers&return_type=csv&apipass=1234&user=admin&pass=pandora
8397function api_get_pandora_servers($trash1, $trash2, $other, $returnType) {
8398	if (defined ('METACONSOLE')) {
8399		return;
8400	}
8401
8402	if (!isset($other['data'][0]))
8403		$separator = ';'; // by default
8404	else
8405		$separator = $other['data'][0];
8406
8407	$servers = servers_get_info ();
8408
8409	foreach ($servers as $server) {
8410		$dd = array (
8411			'name' => $server["name"],
8412			'status' => $server["status"],
8413			'type' => $server["type"],
8414			'master' => $server["master"],
8415			'modules' => $server["modules"],
8416			'modules_total' => $server["modules_total"],
8417			'lag' => $server["lag"],
8418			'module_lag' => $server["module_lag"],
8419			'threads' => $server["threads"],
8420			'queued_modules' => $server["queued_modules"],
8421			'keepalive' => $server['keepalive'],
8422			'id_server' => $server['id_server']
8423		);
8424
8425		// servers_get_info() returns "<a http:....>servername</a>" for recon server's name.
8426		// i don't know why and the following line is a temprary workaround...
8427		$dd["name"] = preg_replace( '/<[^>]*>/', "", $dd["name"]);
8428
8429		switch ($dd['type']) {
8430			case "snmp":
8431			case "event":
8432				$dd['modules'] = '';
8433				$dd['modules_total'] = '';
8434				$dd['lag'] = '';
8435				$dd['module_lag'] = '';
8436				break;
8437			case "export":
8438				$dd['lag'] = '';
8439				$dd['module_lag'] = '';
8440				break;
8441			default:
8442				break;
8443		}
8444
8445		$returnVar[] = $dd;
8446	}
8447
8448	$data = array('type' => 'array', 'data' => $returnVar);
8449
8450	returnData($returnType, $data, $separator);
8451	return;
8452}
8453
8454/**
8455 * Enable/Disable agent given an id
8456 *
8457 * @param string $id String Agent ID
8458 * @param $thrash2 not used.
8459 * @param array $other it's array, $other as param is <enable/disable value> in this order and separator char
8460 *  (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
8461 *  example:
8462 *
8463 * 	example 1 (Enable agent 'example_id')
8464 *
8465 *  api.php?op=set&op2=enable_disable_agent&id=example_id&other=0&other_mode=url_encode_separator_|
8466 *
8467 * 	example 2 (Disable agent 'example_id')
8468 *
8469 *  api.php?op=set&op2=enable_disable_agent&id=example_id16&other=1&other_mode=url_encode_separator_|
8470 *
8471 * @param $thrash3 Don't use.
8472 */
8473
8474function api_set_enable_disable_agent ($id, $thrash2, $other, $thrash3) {
8475
8476	if (defined ('METACONSOLE')) {
8477		return;
8478	}
8479
8480	if ($id == "") {
8481		returnError('error_enable_disable_agent',
8482			__('Error enable/disable agent. Id_agent cannot be left blank.'));
8483		return;
8484	}
8485
8486
8487	if ($other['data'][0] != "0" and $other['data'][0] != "1") {
8488		returnError('error_enable_disable_agent',
8489			__('Error enable/disable agent. Enable/disable value cannot be left blank.'));
8490		return;
8491	}
8492
8493	if (agents_get_name($id) == false) {
8494		returnError('error_enable_disable_agent',
8495			__('Error enable/disable agent. The agent doesn\'t exists.'));
8496		return;
8497	}
8498
8499	$disabled = ( $other['data'][0] ? 0 : 1 );
8500
8501	$result = db_process_sql_update('tagente',
8502		array('disabled' => $disabled), array('id_agente' => $id));
8503
8504	if (is_error($result)) {
8505		// TODO: Improve the error returning more info
8506		returnError('error_enable_disable_agent', __('Error in agent enabling/disabling.'));
8507	}
8508	else {
8509		if ($disabled == 0) {
8510			returnData('string',
8511				array('type' => 'string',
8512					'data' => __('Enabled agent.')));
8513		}
8514		else {
8515			returnData('string',
8516				array('type' => 'string',
8517					'data' => __('Disabled agent.')));
8518		}
8519	}
8520}
8521
8522/**
8523 * Validate alert from Pager Duty service. This call will be setted in PagerDuty's service as a Webhook to
8524 * validate the alerts of Pandora FMS previously linked to PagertDuty when its were validated from PagerDuty.
8525 *
8526 * This call only have a parameter: id=alert
8527 *
8528 * Call example:
8529 * 	http://127.0.0.1/pandora_console/include/api.php?op=set&op2=pagerduty_webhook&apipass=1234&user=admin&pass=pandora&id=alert
8530 *
8531 * TODO: Add support to events.
8532 *
8533 */
8534
8535function api_set_pagerduty_webhook($type, $matchup_path, $tresh2, $return_type) {
8536	global $config;
8537
8538	if (defined ('METACONSOLE')) {
8539		return;
8540	}
8541
8542	$pagerduty_data = json_decode(file_get_contents('php://input'), true);
8543
8544	foreach($pagerduty_data['messages'] as $pm) {
8545		$incident = $pm['data']['incident'];
8546		$incident_type = $pm['type'];
8547		// incident.acknowledge
8548		// incident.resolve
8549		// incident.trigger
8550
8551		switch($type) {
8552			case 'alert':
8553				// Get all the alerts that the user can see
8554				$id_groups = array_keys(users_get_groups($config["id_user"], 'AR', false));
8555				$alerts = get_group_alerts($id_groups);
8556
8557				// When an alert is resolved, the Pandoras alert will be validated
8558				if ($incident_type != 'incident.resolve') {
8559					break;
8560				}
8561
8562				$alert_id = 0;
8563				foreach($alerts as $al) {
8564	    				$key = file_get_contents($matchup_path . '/.pandora_pagerduty_id_' . $al['id']);
8565					if ($key == $incident['incident_key']) {
8566						$alert_id = $al['id'];
8567						break;
8568					}
8569				}
8570
8571				if ($alert_id != 0) {
8572					alerts_validate_alert_agent_module($alert_id);
8573				}
8574				break;
8575			case 'event':
8576				break;
8577		}
8578	}
8579}
8580
8581/**
8582 * Get special days, and print all the result like a csv.
8583 *
8584 * @param $thrash1 Don't use.
8585 * @param $thrash2 Don't use.
8586 * @param array $other it's array, but only <csv_separator> is available.
8587 * @param $thrash3 Don't use.
8588 *
8589 * example:
8590 *  api.php?op=get&op2=special_days&other=,;
8591 *
8592 */
8593function api_get_special_days($thrash1, $thrash2, $other, $thrash3) {
8594	if (defined ('METACONSOLE')) {
8595		return;
8596	}
8597
8598	if (!isset($other['data'][0]))
8599		$separator = ';'; // by default
8600	else
8601		$separator = $other['data'][0];
8602
8603	$filter = false;
8604
8605	$special_days = @db_get_all_rows_filter ('talert_special_days', $filter);
8606
8607	if ($special_days !== false) {
8608		$data['type'] = 'array';
8609		$data['data'] = $special_days;
8610	}
8611
8612	if (!$special_days) {
8613		returnError('error_get_special_days', __('Error getting special_days.'));
8614	}
8615	else {
8616		returnData('csv', $data, $separator);
8617	}
8618}
8619
8620/**
8621 * Create a special day. And return the id if new special day.
8622 *
8623 * @param $thrash1 Don't use.
8624 * @param $thrash2 Don't use.
8625 * @param array $other it's array, $other as param is <special_day>;<same_day>;<description>;<id_group>; in this order
8626 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
8627 * @param $thrash3 Don't use
8628 *
8629 * example:
8630 *  api.php?op=set&op2=create_special_day&other=2014-05-03|sunday|text|0&other_mode=url_encode_separator_|
8631 *
8632 */
8633function api_set_create_special_day($thrash1, $thrash2, $other, $thrash3) {
8634	global $config;
8635
8636	if (defined ('METACONSOLE')) {
8637		return;
8638	}
8639
8640	$special_day = $other['data'][0];
8641	$same_day = $other['data'][1];
8642	$description = $other['data'][2];
8643	$idGroup = $other['data'][3];
8644
8645	$check_id_special_day = db_get_value ('id', 'talert_special_days', 'date', $special_day);
8646
8647	if ($check_id_special_day) {
8648		returnError('error_create_special_day', __('Error creating special day. Specified day already exists.'));
8649		return;
8650	}
8651
8652	if (!preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $special_day)) {
8653		returnError('error_create_special_day', __('Error creating special day. Invalid date format.'));
8654		return;
8655	}
8656
8657	$values = array(
8658		'description' => $other['data'][2],
8659		'id_group' => $other['data'][3],
8660	);
8661
8662	$idSpecialDay = alerts_create_alert_special_day($special_day, $same_day, $values);
8663
8664	if (is_error($idSpecialDay)) {
8665		returnError('error_create_special_day', __('Error in creation special day.'));
8666	}
8667	else {
8668		returnData('string', array('type' => 'string', 'data' => $idSpecialDay));
8669	}
8670}
8671
8672/**
8673 * Update a special day. And return a message with the result of the operation.
8674 *
8675 * @param string $id Id of the special day to update.
8676 * @param $thrash2 Don't use.
8677 * @param array $other it's array, $other as param is <special_day>;<same_day>;<description>;<id_group>; in this order
8678 *  and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_<separator>)
8679 * @param $thrash3 Don't use
8680 *
8681 * example:
8682 *  api.php?op=set&op2=update_special_day&id=1&other=2014-05-03|sunday|text|0&other_mode=url_encode_separator_|
8683 *
8684 */
8685function api_set_update_special_day($id_special_day, $thrash2, $other, $thrash3) {
8686	global $config;
8687
8688	if (defined ('METACONSOLE')) {
8689		return;
8690	}
8691
8692	$special_day = $other['data'][0];
8693	$same_day = $other['data'][1];
8694	$description = $other['data'][2];
8695	$idGroup = $other['data'][3];
8696
8697	if ($id_special_day == "") {
8698		returnError('error_update_special_day', __('Error updating special day. Id cannot be left blank.'));
8699		return;
8700		}
8701
8702	$check_id_special_day = db_get_value ('id', 'talert_special_days', 'id', $id_special_day);
8703
8704	if (!$check_id_special_day) {
8705		returnError('error_update_special_day', __('Error updating special day. Id doesn\'t exists.'));
8706		return;
8707	}
8708
8709	if (!preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $special_day)) {
8710		returnError('error_update_special_day', __('Error updating special day. Invalid date format.'));
8711		return;
8712	}
8713
8714	$return = db_process_sql_update('talert_special_days',
8715		array(
8716			'date' => $special_day,
8717			'same_day' => $same_day,
8718			'description' => $description,
8719			'id_group' => $idGroup),
8720		array('id' => $id_special_day));
8721
8722	returnData('string',
8723		array('type' => 'string', 'data' => (int)((bool)$return)));
8724}
8725
8726/**
8727 * Delete a special day. And return a message with the result of the operation.
8728 *
8729 * @param string $id Id of the special day to delete.
8730 * @param $thrash2 Don't use.
8731 * @param $thrash3 Don't use.
8732 * @param $thrash4 Don't use.
8733 *
8734 * example:
8735 *  api.php?op=set&op2=delete_special_day&id=1
8736 *
8737 */
8738function api_set_delete_special_day($id_special_day, $thrash2, $thrash3, $thrash4) {
8739	if (defined ('METACONSOLE')) {
8740		return;
8741	}
8742
8743	if ($id_special_day == "") {
8744		returnError('error_update_special_day', __('Error deleting special day. Id cannot be left blank.'));
8745		return;
8746	}
8747
8748	$check_id_special_day = db_get_value ('id', 'talert_special_days', 'id', $id_special_day);
8749
8750	if (!$check_id_special_day) {
8751		returnError('error_delete_special_day', __('Error deleting special day. Id doesn\'t exists.'));
8752		return;
8753	}
8754
8755	$return = alerts_delete_alert_special_day ($id_special_day);
8756
8757	if (is_error($return)) {
8758		returnError('error_delete_special_day', __('Error in deletion special day.'));
8759	}
8760	else {
8761		returnData('string', array('type' => 'string', 'data' => $return));
8762	}
8763}
8764
8765/**
8766 * Get a module graph image encoded with base64.
8767 * The value returned by this function will be always a string.
8768 *
8769 * @param int $id Id of the module.
8770 * @param $thrash2 Don't use.
8771 * @param array $other Array array('type' => 'string', 'data' => '<Graph seconds>').
8772 * @param $thrash4 Don't use.
8773 *
8774 * example:
8775 *  api.php?op=get&op2=module_graph&id=1&other=3600
8776 *
8777 */
8778function api_get_module_graph($id_module, $thrash2, $other, $thrash4) {
8779	if (defined ('METACONSOLE')) {
8780		return;
8781	}
8782
8783	if (is_nan($id_module) || $id_module <= 0) {
8784		returnError('error_module_graph', __(''));
8785		return;
8786	}
8787
8788	$id_exist = (bool) db_get_value ('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module);
8789
8790	if (!$id_exist) {
8791		// returnError('id_not_found');
8792		return;
8793	}
8794
8795	$graph_seconds =
8796		(!empty($other) && isset($other['data']))
8797		?
8798		$other['data']
8799		:
8800		SECONDS_1HOUR; // 1 hour by default
8801
8802	if (is_nan($graph_seconds) || $graph_seconds <= 0) {
8803		// returnError('error_module_graph', __(''));
8804		return;
8805	}
8806
8807	// Get the html item
8808	$graph_html = grafico_modulo_sparse(
8809		$id_module, $graph_seconds, false, 600, 300, '',
8810		'', false, false, true, time(), '', 0, 0, true, true,
8811		ui_get_full_url(false) . '/', 1, false, '', false, true);
8812
8813	$graph_image_file_encoded = false;
8814
8815	// Get the src of the html item
8816	if (preg_match("/<img src='(.+)'>/", $graph_html, $matches)) {
8817		if (isset($matches) && isset($matches[1])) {
8818			$file_url = $matches[1];
8819			// Get the file
8820			$graph_image_file = file_get_contents($file_url);
8821
8822			if ($graph_image_file !== false) {
8823				// Encode the file
8824				$graph_image_file_encoded = base64_encode($graph_image_file);
8825				unset($graph_image_file);
8826			}
8827		}
8828	}
8829
8830	if (empty($graph_image_file_encoded)) {
8831		// returnError('error_module_graph', __(''));
8832	}
8833	else {
8834		returnData('string', array('type' => 'string', 'data' => $graph_image_file_encoded));
8835	}
8836}
8837
8838?>
8839