1<?php
2/*
3 +-------------------------------------------------------------------------+
4 | Copyright (C) 2004-2021 The Cacti Group                                 |
5 |                                                                         |
6 | This program is free software; you can redistribute it and/or           |
7 | modify it under the terms of the GNU General Public License             |
8 | as published by the Free Software Foundation; either version 2          |
9 | of the License, or (at your option) any later version.                  |
10 |                                                                         |
11 | This program is distributed in the hope that it will be useful,         |
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of          |
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           |
14 | GNU General Public License for more details.                            |
15 +-------------------------------------------------------------------------+
16 | Cacti: The Complete RRDtool-based Graphing Solution                     |
17 +-------------------------------------------------------------------------+
18 | This code is designed, written, and maintained by the Cacti Group. See  |
19 | about.php and/or the AUTHORS file for specific developer information.   |
20 +-------------------------------------------------------------------------+
21 | http://www.cacti.net/                                                   |
22 +-------------------------------------------------------------------------+
23*/
24
25include('./include/auth.php');
26include_once('./lib/api_data_source.php');
27include_once('./lib/poller.php');
28include_once('./lib/template.php');
29include_once('./lib/utility.php');
30
31$di_actions = array(
32	1 => __('Delete'),
33	2 => __('Duplicate')
34);
35
36/* set default action */
37set_default_action();
38
39switch (get_request_var('action')) {
40	case 'save':
41		form_save();
42
43		break;
44	case 'actions':
45		form_actions();
46
47		break;
48	case 'field_remove_confirm':
49		field_remove_confirm();
50
51		break;
52	case 'field_remove':
53		field_remove();
54
55		header('Location: data_input.php?header=false&action=edit&id=' . get_filter_request_var('data_input_id'));
56		break;
57	case 'field_edit':
58		top_header();
59
60		field_edit();
61
62		bottom_footer();
63		break;
64	case 'edit':
65		top_header();
66
67		data_edit();
68
69		bottom_footer();
70		break;
71	default:
72		top_header();
73
74		data();
75
76		bottom_footer();
77		break;
78}
79
80/* --------------------------
81    The Save Function
82   -------------------------- */
83
84function duplicate_data_input($_data_input_id, $input_title) {
85	$orig_input = db_fetch_row_prepared('SELECT *
86		FROM data_input
87		WHERE id = ?',
88		array($_data_input_id));
89
90	if (cacti_sizeof($orig_input)) {
91		unset($save);
92		$save['id']           = 0;
93		$save['hash']         = get_hash_data_input(0);
94		$save['name']         = str_replace('<input_title>', $orig_input['name'], $input_title);
95		$save['input_string'] = $orig_input['input_string'];
96		$save['type_id']      = $orig_input['type_id'];
97
98		$data_input_id = sql_save($save, 'data_input');
99
100		if (!empty($data_input_id)) {
101			$data_input_fields = db_fetch_assoc_prepared('SELECT *
102				FROM data_input_fields
103				WHERE data_input_id = ?',
104				array($_data_input_id));
105
106			if (cacti_sizeof($data_input_fields)) {
107				foreach($data_input_fields as $dif) {
108					unset($save);
109					$save['id']            = 0;
110					$save['hash']          = get_hash_data_input(0, 'data_input_field');
111					$save['data_input_id'] = $data_input_id;
112					$save['name']          = $dif['name'];
113					$save['data_name']     = $dif['data_name'];
114					$save['input_output']  = $dif['input_output'];
115					$save['update_rra']    = $dif['update_rra'];
116					$save['sequence']      = $dif['sequence'];
117					$save['type_code']     = $dif['type_code'];
118					$save['regexp_match']  = $dif['regexp_match'];
119					$save['allow_nulls']   = $dif['allow_nulls'];
120
121					$data_input_field_id = sql_save($save, 'data_input_fields');
122				}
123			}
124		}
125	}
126}
127
128function form_save() {
129	global $registered_cacti_names;
130
131	if (isset_request_var('save_component_data_input')) {
132		/* ================= input validation ================= */
133		get_filter_request_var('id');
134		/* ==================================================== */
135
136		$save['id']           = get_nfilter_request_var('id');
137		$save['hash']         = get_hash_data_input(get_nfilter_request_var('id'));
138		$save['name']         = form_input_validate(get_nfilter_request_var('name'), 'name', '', false, 3);
139		$save['input_string'] = form_input_validate(get_nfilter_request_var('input_string'), 'input_string', '', true, 3);
140		$save['type_id']      = form_input_validate(get_nfilter_request_var('type_id'), 'type_id', '^[0-9]+$', true, 3);
141
142		if (!is_error_message()) {
143			$data_input_id = sql_save($save, 'data_input');
144
145			if ($data_input_id) {
146				data_input_save_message($data_input_id);
147
148				/* get a list of each field so we can note their sequence of occurrence in the database */
149				if (!isempty_request_var('id')) {
150					db_execute_prepared('UPDATE data_input_fields SET sequence = 0 WHERE data_input_id = ?', array(get_nfilter_request_var('id')));
151
152					generate_data_input_field_sequences(get_nfilter_request_var('input_string'), get_nfilter_request_var('id'));
153
154					update_replication_crc(0, 'poller_replicate_data_input_fields_crc');
155				}
156
157				push_out_data_input_method($data_input_id);
158			} else {
159				raise_message(2);
160			}
161		}
162
163		header('Location: data_input.php?header=false&action=edit&id=' . (empty($data_input_id) ? get_nfilter_request_var('id') : $data_input_id));
164	} elseif (isset_request_var('save_component_field')) {
165		/* ================= input validation ================= */
166		get_filter_request_var('id');
167		get_filter_request_var('data_input_id');
168		get_filter_request_var('sequence');
169		get_filter_request_var('input_output', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^(in|out)$/')));
170		/* ==================================================== */
171
172		$save['id']            = get_request_var('id');
173		$save['hash']          = get_hash_data_input(get_nfilter_request_var('id'), 'data_input_field');
174		$save['data_input_id'] = get_request_var('data_input_id');
175		$save['name']          = form_input_validate(get_nfilter_request_var('fname'), 'fname', '', false, 3);
176		$save['data_name']     = form_input_validate(get_nfilter_request_var('data_name'), 'data_name', '', false, 3);
177		$save['input_output']  = get_nfilter_request_var('input_output');
178		$save['update_rra']    = form_input_validate((isset_request_var('update_rra') ? get_nfilter_request_var('update_rra') : ''), 'update_rra', '', true, 3);
179		$save['sequence']      = get_request_var('sequence');
180		$save['type_code']     = form_input_validate((isset_request_var('type_code') ? get_nfilter_request_var('type_code') : ''), 'type_code', '', true, 3);
181		$save['regexp_match']  = form_input_validate((isset_request_var('regexp_match') ? get_nfilter_request_var('regexp_match') : ''), 'regexp_match', '', true, 3);
182		$save['allow_nulls']   = form_input_validate((isset_request_var('allow_nulls') ? get_nfilter_request_var('allow_nulls') : ''), 'allow_nulls', '', true, 3);
183
184		if (!is_error_message()) {
185			$data_input_field_id = sql_save($save, 'data_input_fields');
186
187			if ($data_input_field_id) {
188				data_input_save_message(get_request_var('data_input_id'), 'field');
189
190				if ((!empty($data_input_field_id)) && (get_request_var('input_output') == 'in')) {
191					generate_data_input_field_sequences(db_fetch_cell_prepared('SELECT input_string FROM data_input WHERE id = ?', array(get_request_var('data_input_id'))), get_request_var('data_input_id'));
192				}
193
194				update_replication_crc(0, 'poller_replicate_data_input_fields_crc');
195			} else {
196				raise_message(2);
197			}
198		}
199
200		if (is_error_message()) {
201			header('Location: data_input.php?header=false&action=field_edit&data_input_id=' . get_request_var('data_input_id') . '&id=' . (empty($data_input_field_id) ? get_request_var('id') : $data_input_field_id) . (!isempty_request_var('input_output') ? '&type=' . get_request_var('input_output') : ''));
202		} else {
203			header('Location: data_input.php?header=false&action=edit&id=' . get_request_var('data_input_id'));
204		}
205	}
206}
207
208function data_input_save_message($data_input_id, $type = 'input') {
209	$counts = db_fetch_row_prepared("SELECT
210		SUM(CASE WHEN dtd.local_data_id=0 THEN 1 ELSE 0 END) AS templates,
211		SUM(CASE WHEN dtd.local_data_id>0 THEN 1 ELSE 0 END) AS data_sources
212		FROM data_input AS di
213		LEFT JOIN data_template_data AS dtd
214		ON di.id=dtd.data_input_id
215		WHERE di.id = ?",
216		array($data_input_id));
217
218	if ($counts['templates'] == 0 && $counts['data_sources'] == 0) {
219		raise_message(1);
220	} elseif ($counts['templates'] > 0 && $counts['data_sources'] == 0) {
221		if ($type == 'input') {
222			raise_message('input_save_wo_ds');
223		} else {
224			raise_message('input_field_save_wo_ds');
225		}
226	} else {
227		if ($type == 'input') {
228			raise_message('input_save_w_ds');
229		} else {
230			raise_message('input_field_save_w_ds');
231		}
232	}
233}
234
235function form_actions() {
236	global $di_actions;
237
238	/* ================= input validation ================= */
239	get_filter_request_var('drp_action', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^([a-zA-Z0-9_]+)$/')));
240	/* ==================================================== */
241
242	/* if we are to save this form, instead of display it */
243	if (isset_request_var('selected_items')) {
244		$selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items'));
245
246		if ($selected_items != false) {
247			if (get_request_var('drp_action') == '1') { // delete
248				for ($i=0;($i<cacti_count($selected_items));$i++) {
249					data_remove($selected_items[$i]);
250				}
251			} elseif (get_request_var('drp_action') == '2') { // duplicate
252				for ($i=0;($i<cacti_count($selected_items));$i++) {
253					duplicate_data_input($selected_items[$i], get_nfilter_request_var('input_title'));
254				}
255			}
256		}
257
258		header('Location: data_input.php?header=false');
259		exit;
260	}
261
262	/* setup some variables */
263	$di_list = ''; $i = 0;
264
265	/* loop through each of the data inputs and process them */
266	foreach ($_POST as $var => $val) {
267		if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) {
268			/* ================= input validation ================= */
269			input_validate_input_number($matches[1]);
270			/* ==================================================== */
271
272			$di_list .= '<li>' . html_escape(db_fetch_cell_prepared('SELECT name FROM data_input WHERE id = ?', array($matches[1]))) . '</li>';
273			$di_array[$i] = $matches[1];
274
275			$i++;
276		}
277	}
278
279	top_header();
280
281	form_start('data_input.php');
282
283	html_start_box($di_actions[get_nfilter_request_var('drp_action')], '60%', '', '3', 'center', '');
284
285	if (isset($di_array) && cacti_sizeof($di_array)) {
286		if (get_request_var('drp_action') == '1') { // delete
287			$graphs = array();
288
289			print "<tr>
290				<td class='textArea' class='odd'>
291					<p>" . __n('Click \'Continue\' to delete the following Data Input Method', 'Click \'Continue\' to delete the following Data Input Method', cacti_sizeof($di_array)) . "</p>
292					<div class='itemlist'><ul>$di_list</ul></div>
293				</td>
294			</tr>\n";
295		} elseif (get_request_var('drp_action') == '2') { // duplicate
296			print "<tr>
297				<td class='textArea'>
298					<p>" . __('Click \'Continue\' to duplicate the following Data Input Method(s). You can optionally change the title format for the new Data Input Method(s).') . "</p>
299                    <div class='itemlist'><ul>$di_list</ul></div>
300                    <p><strong>" . __('Input Name:'). "</strong><br>"; form_text_box('input_title', '<input_title> (1)', '', '255', '30', 'text'); print "</p>
301                </td>
302			</tr>\n";
303		}
304
305		$save_html = "<input type='button' class='ui-button ui-corner-all ui-widget' value='" . __esc('Cancel') . "' onClick='cactiReturnTo()'>&nbsp;<input type='submit' class='ui-button ui-corner-all ui-widget' value='" . __esc('Continue') . "' title='" . __n('Delete Data Input Method', 'Delete Data Input Methods', cacti_sizeof($di_array)) . "'>";
306	} else {
307		raise_message(40);
308		header('Location: data_input.php?header=none');
309		exit;
310	}
311
312	print "<tr>
313		<td class='saveRow'>
314			<input type='hidden' name='action' value='actions'>
315			<input type='hidden' name='selected_items' value='" . (isset($di_array) ? serialize($di_array) : '') . "'>
316			<input type='hidden' name='drp_action' value='" . html_escape(get_nfilter_request_var('drp_action')) . "'>
317			$save_html
318		</td>
319	</tr>\n";
320
321	html_end_box();
322
323	form_end();
324
325	bottom_footer();
326}
327
328/* --------------------------
329    CDEF Item Functions
330   -------------------------- */
331
332function field_remove_confirm() {
333	/* ================= input validation ================= */
334	get_filter_request_var('id');
335	get_filter_request_var('data_input_id');
336	/* ==================================================== */
337
338	form_start('data_intput.php?action=edit&id' . get_request_var('data_input_id'));
339
340	html_start_box('', '100%', '', '3', 'center', '');
341
342	$field = db_fetch_row_prepared('SELECT *
343		FROM data_input_fields
344		WHERE id = ?',
345		array(get_request_var('id')));
346
347	?>
348	<tr>
349		<td class='topBoxAlt'>
350			<p><?php print __('Click \'Continue\' to delete the following Data Input Field.');?></p>
351			<p><?php print __esc('Field Name: %s', $field['data_name']);?><br>
352			<p><?php print __esc('Friendly Name: %s', $field['name']);?><br>
353		</td>
354	</tr>
355	<tr>
356		<td class='right'>
357			<input type='button' class='ui-button ui-corner-all ui-widget' id='cancel' value='<?php print __esc('Cancel');?>' name='cancel'>
358			<input type='button' class='ui-button ui-corner-all ui-widget' id='continue' value='<?php print __esc('Continue');?>' name='continue' title='<?php print __esc('Remove Data Input Field');?>'>
359		</td>
360	</tr>
361	<?php
362
363	html_end_box();
364
365	form_end();
366
367	?>
368	<script type='text/javascript'>
369	$(function() {
370		$('#continue').unbind('click').click(function(data) {
371			$.post('data_input.php?action=field_remove', {
372				__csrf_magic: csrfMagicToken,
373				data_input_id: <?php print get_request_var('data_input_id');?>,
374				id: <?php print get_request_var('id');?>
375			}, function(data) {
376				loadPageNoHeader('data_input.php?action=edit&header=false&id=<?php print get_request_var('data_input_id');?>');
377			});
378		});
379	});
380	</script>
381	<?php
382}
383
384function field_remove() {
385	global $registered_cacti_names;
386
387	/* ================= input validation ================= */
388	get_filter_request_var('id');
389	get_filter_request_var('data_input_id');
390	/* ==================================================== */
391
392	/* get information about the field we're going to delete so we can re-order the seqs */
393	$field = db_fetch_row_prepared('SELECT input_output,data_input_id FROM data_input_fields WHERE id = ?', array(get_request_var('id')));
394
395	db_execute_prepared('DELETE FROM data_input_fields WHERE id = ?', array(get_request_var('id')));
396	db_execute_prepared('DELETE FROM data_input_data WHERE data_input_field_id = ?', array(get_request_var('id')));
397
398	/* when a field is deleted; we need to re-order the field sequences */
399	if (($field['input_output'] == 'in') && (preg_match_all('/<([_a-zA-Z0-9]+)>/', db_fetch_cell_prepared('SELECT input_string FROM data_input WHERE id = ?', array($field['data_input_id'])), $matches))) {
400		$j = 0;
401		for ($i=0; ($i < cacti_count($matches[1])); $i++) {
402			if (in_array($matches[1][$i], $registered_cacti_names) == false) {
403				$j++;
404				db_execute_prepared("UPDATE data_input_fields SET sequence = ? WHERE data_input_id = ? AND input_output = 'in' AND data_name = ?", array($j, $field['data_input_id'], $matches[1][$i]));
405			}
406		}
407	}
408
409	update_replication_crc(0, 'poller_replicate_data_input_fields_crc');
410}
411
412function field_edit() {
413	global $registered_cacti_names, $fields_data_input_field_edit_1, $fields_data_input_field_edit_2, $fields_data_input_field_edit;
414
415	/* ================= input validation ================= */
416	get_filter_request_var('id');
417	get_filter_request_var('data_input_id');
418	get_filter_request_var('type', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^(in|out)$/')));
419	/* ==================================================== */
420
421	$array_field_names = array();
422
423	if (!isempty_request_var('id')) {
424		$field = db_fetch_row_prepared('SELECT *
425			FROM data_input_fields
426			WHERE id = ?',
427			array(get_request_var('id')));
428	}
429
430	if (!isempty_request_var('type')) {
431		$current_field_type = get_request_var('type');
432	} else {
433		$current_field_type = $field['input_output'];
434	}
435
436	$data_input = db_fetch_row_prepared('SELECT type_id, name
437		FROM data_input
438		WHERE id = ?',
439		array(get_request_var('data_input_id')));
440
441	/* obtain a list of available fields for this given field type (input/output) */
442	if (($current_field_type == 'in') && (preg_match_all('/<([_a-zA-Z0-9]+)>/', db_fetch_cell_prepared('SELECT input_string FROM data_input WHERE id = ?', array(!isempty_request_var('data_input_id') ? get_request_var('data_input_id') : $field['data_input_id'])), $matches))) {
443		for ($i=0; ($i < cacti_count($matches[1])); $i++) {
444			if (in_array($matches[1][$i], $registered_cacti_names) == false) {
445				$current_field_name = $matches[1][$i];
446				$array_field_names[$current_field_name] = $current_field_name;
447				if (!isset($field)) {
448					$field_id = db_fetch_cell_prepared('SELECT id FROM data_input_fields
449						WHERE data_name = ?
450						AND data_input_id = ?',
451						array($current_field_name, get_filter_request_var('data_input_id')));
452					if (!$field_id > 0) {
453						$field = array();
454						$field['name'] = ucwords($current_field_name);
455						$field['data_name'] = $current_field_name;
456					}
457				}
458			}
459		}
460	}
461
462	/* if there are no input fields to choose from, complain */
463	if ((!isset($array_field_names)) && (isset_request_var('type') ? get_request_var('type') == 'in' : false) && ($data_input['type_id'] == '1')) {
464		display_custom_error_message(__('This script appears to have no input values, therefore there is nothing to add.'));
465		header('Location: data_input.php?header=false&action=edit&id=' . get_filter_request_var('data_input_id'));
466		exit;
467	}
468
469	if ($current_field_type == 'out') {
470		$header_name = __esc('Output Fields [edit: %s]', $data_input['name']);
471		$dfield      = __('Output Field');
472	} elseif ($current_field_type == 'in') {
473		$header_name = __esc('Input Fields [edit: %s]', $data_input['name']);
474		$dfield      = __('Input Field');
475	}
476
477	if (isset($field)) {
478		$dfield .= ' ' . html_escape($field['data_name']);
479	}
480	form_start('data_input.php', 'data_input');
481
482	html_start_box($header_name, '100%', true, '3', 'center', '');
483
484	$form_array = array();
485
486	/* field name */
487	if ((($data_input['type_id'] == '1') || ($data_input['type_id'] == '5')) && ($current_field_type == 'in')) { /* script */
488		$form_array = inject_form_variables($fields_data_input_field_edit_1, $dfield, $array_field_names, (isset($field) ? $field : array()));
489	} elseif ($current_field_type == 'out' || ($data_input['type_id'] != 1 && $data_input['type_id'] != 5)) {
490		$form_array = inject_form_variables($fields_data_input_field_edit_2, $dfield, (isset($field) ? $field : array()));
491	}
492
493	/* ONLY if the field is an input */
494	if ($current_field_type == 'in') {
495		unset($fields_data_input_field_edit['update_rra']);
496	} elseif ($current_field_type == 'out') {
497		unset($fields_data_input_field_edit['regexp_match']);
498		unset($fields_data_input_field_edit['allow_nulls']);
499		unset($fields_data_input_field_edit['type_code']);
500	}
501
502	draw_edit_form(
503		array(
504			'config' => array('no_form_tag' => true),
505			'fields' => $form_array + inject_form_variables($fields_data_input_field_edit, (isset($field) ? $field : array()), $current_field_type, $_REQUEST)
506		)
507	);
508
509	html_end_box(true, true);
510
511	form_save_button('data_input.php?action=edit&id=' . get_request_var('data_input_id'));
512}
513
514/* -----------------------
515    Data Input Functions
516   ----------------------- */
517
518function data_remove($id) {
519	$data_input_fields = db_fetch_assoc_prepared('SELECT id
520		FROM data_input_fields
521		WHERE data_input_id = ?',
522		array($id));
523
524	if (is_array($data_input_fields)) {
525		foreach ($data_input_fields as $data_input_field) {
526			db_execute_prepared('DELETE FROM data_input_data WHERE data_input_field_id = ?', array($data_input_field['id']));
527		}
528	}
529
530	db_execute_prepared('DELETE FROM data_input WHERE id = ?', array($id));
531	db_execute_prepared('DELETE FROM data_input_fields WHERE data_input_id = ?', array($id));
532
533	update_replication_crc(0, 'poller_replicate_data_input_fields_crc');
534	update_replication_crc(0, 'poller_replicate_data_input_crc');
535}
536
537function data_input_more_inputs($id, $input_string) {
538	$input_string = str_replace('<path_cacti>', '', $input_string);
539	$inputs = substr_count($input_string, '<');
540
541	$existing = db_fetch_cell_prepared('SELECT COUNT(*)
542		FROM data_input_fields
543		WHERE data_input_id = ?
544		AND input_output = "in"',
545		array($id));
546
547	if ($inputs > $existing) {
548		return true;
549	} else {
550		return false;
551	}
552}
553
554function data_edit() {
555	global $config, $fields_data_input_edit;
556
557	/* ================= input validation ================= */
558	get_filter_request_var('id');
559	/* ==================================================== */
560
561	if (!isempty_request_var('id')) {
562		$data_id = get_nonsystem_data_input(get_request_var('id'));
563		if ($data_id == 0 || $data_id == NULL) {
564			header('Location: data_input.php');
565			return;
566		}
567
568		$data_input = db_fetch_row_prepared('SELECT *
569			FROM data_input
570			WHERE id = ?',
571			array(get_request_var('id')));
572
573		$header_label = __esc('Data Input Method [edit: %s]', $data_input['name']);
574	} else {
575		$data_input = array();
576
577		$header_label = __('Data Input Method [new]');
578	}
579
580	if (!isset($config['input_whitelist'])) {
581		unset($fields_data_input_edit['whitelist_verification']);
582	}
583
584	form_start('data_input.php', 'data_input');
585
586	html_start_box($header_label, '100%', true, '3', 'center', '');
587
588	if (cacti_sizeof($data_input)) {
589		switch ($data_input['type_id']) {
590		case DATA_INPUT_TYPE_SNMP:
591			$fields_data_input_edit['type_id']['array'][DATA_INPUT_TYPE_SNMP] = __('SNMP Get');
592			break;
593		case DATA_INPUT_TYPE_SNMP_QUERY:
594			$fields_data_input_edit['type_id']['array'][DATA_INPUT_TYPE_SNMP_QUERY] = __('SNMP Query');
595			break;
596		case DATA_INPUT_TYPE_SCRIPT_QUERY:
597			$fields_data_input_edit['type_id']['array'][DATA_INPUT_TYPE_SCRIPT_QUERY] = __('Script Query');
598			break;
599		case DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER:
600			$fields_data_input_edit['type_id']['array'][DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER] = __('Script Server Query');
601			break;
602		}
603
604		if (isset($config['input_whitelist']) && isset($data_input['hash'])) {
605			$aud = verify_data_input_whitelist($data_input['hash'], $data_input['input_string']);
606
607			if ($aud === true) {
608				$fields_data_input_edit['whitelist_verification']['value'] = __('White List Verification Succeeded.');
609			} elseif ($aud == false) {
610				$fields_data_input_edit['whitelist_verification']['value'] = __('White List Verification Failed.  Run CLI script input_whitelist.php to correct.');
611			} elseif ($aud == '-1') {
612				$fields_data_input_edit['whitelist_verification']['value'] = __('Input String does not exist in White List.  Run CLI script input_whitelist.php to correct.');
613			}
614		}
615	}
616
617	draw_edit_form(
618		array(
619			'config' => array('no_form_tag' => true),
620			'fields' => inject_form_variables($fields_data_input_edit, $data_input)
621		)
622	);
623
624	html_end_box(true, true);
625
626	if (!isempty_request_var('id')) {
627		if (data_input_more_inputs(get_request_var('id'), $data_input['input_string'])) {
628			$url = 'data_input.php?action=field_edit&type=in&data_input_id=' . get_request_var('id');
629		} else {
630			$url = '';
631		}
632
633		html_start_box(__('Input Fields'), '100%', '', '3', 'center', $url);
634
635		print "<tr class='tableHeader'>";
636		DrawMatrixHeaderItem(__('Name'), '', 1);
637		DrawMatrixHeaderItem(__('Friendly Name'), '', 1);
638		DrawMatrixHeaderItem(__('Field Order'), '', 2);
639		print '</tr>';
640
641		$fields = db_fetch_assoc_prepared("SELECT id, data_name, name, sequence
642			FROM data_input_fields
643			WHERE data_input_id = ?
644			AND input_output = 'in'
645			ORDER BY sequence, data_name",
646			array(get_request_var('id')));
647
648		$counts = db_fetch_row_prepared("SELECT
649			SUM(CASE WHEN dtd.local_data_id=0 THEN 1 ELSE 0 END) AS templates,
650			SUM(CASE WHEN dtd.local_data_id>0 THEN 1 ELSE 0 END) AS data_sources
651			FROM data_input AS di
652			LEFT JOIN data_template_data AS dtd
653			ON di.id=dtd.data_input_id
654			WHERE di.id = ?",
655			array(get_request_var('id')));
656
657		$output_disabled  = false;
658		$save_alt_message = false;
659		if (!cacti_sizeof($counts)) {
660			$output_disabled  = false;
661			$save_alt_message = false;
662		} elseif ($counts['data_sources'] > 0) {
663			$output_disabled  = true;
664			$save_alt_message = true;
665		} elseif ($counts['templates'] > 0) {
666			$output_disabled  = false;
667			$save_alt_message = true;
668		}
669
670		$i = 0;
671		if (cacti_sizeof($fields)) {
672			foreach ($fields as $field) {
673				form_alternate_row('', true);
674				?>
675				<td>
676					<a class="linkEditMain" href="<?php print html_escape('data_input.php?action=field_edit&id=' . $field['id'] . '&data_input_id=' . get_request_var('id'));?>"><?php print html_escape($field['data_name']);?></a>
677				</td>
678				<td>
679					<?php print html_escape($field['name']);?>
680				</td>
681				<td>
682					<?php print $field['sequence']; if ($field['sequence'] == '0') { print ' ' . __('(Not In Use)'); }?>
683				</td>
684				<td class="right">
685					<a class='delete deleteMarker fa fa-times' href='<?php print html_escape('data_input.php?action=field_remove_confirm&id=' . $field['id'] . '&data_input_id=' . get_request_var('id'));?>' title='<?php print __esc('Delete');?>'></a>
686				</td>
687				<?php
688				form_end_row();
689			}
690		} else {
691			print '<tr><td colspan="4"><em>' . __('No Input Fields') . '</em></td></tr>';
692		}
693		html_end_box();
694
695		html_start_box(__('Output Fields'), '100%', '', '3', 'center', 'data_input.php?action=field_edit&type=out&data_input_id=' . get_request_var('id'));
696		print "<tr class='tableHeader'>";
697		DrawMatrixHeaderItem(__('Name'),'',1);
698		DrawMatrixHeaderItem(__('Friendly Name'),'',1);
699		DrawMatrixHeaderItem(__('Update RRA'),'',2);
700		print '</tr>';
701
702		$fields = db_fetch_assoc_prepared("SELECT id, name, data_name, update_rra, sequence
703			FROM data_input_fields
704			WHERE data_input_id = ?
705			AND input_output = 'out'
706			ORDER BY sequence, data_name",
707			array(get_request_var('id')));
708
709		$i = 0;
710		if (cacti_sizeof($fields)) {
711			foreach ($fields as $field) {
712				form_alternate_row('', true);
713				?>
714				<td>
715					<a class='linkEditMain' href='<?php print html_escape('data_input.php?action=field_edit&id=' . $field['id'] . '&data_input_id=' . get_request_var('id'));?>'><?php print html_escape($field['data_name']);?></a>
716				</td>
717				<td>
718					<?php print html_escape($field['name']);?>
719				</td>
720				<td>
721					<?php print html_boolean_friendly($field['update_rra']);?>
722				</td>
723				<td class='right'>
724					<?php if ($output_disabled) {?>
725					<a class='deleteMarkerDisabled fa fa-times' href='#' title='<?php print __esc('Output Fields can not be removed when Data Sources are present');?>'></a>
726					<?php } else { ?>
727					<a class='delete deleteMarker fa fa-times' href='<?php print html_escape('data_input.php?action=field_remove_confirm&id=' . $field['id'] . '&data_input_id=' . get_request_var('id'));?>' title='<?php print __esc('Delete');?>'></a>
728					<?php } ?>
729				</td>
730				<?php
731				form_end_row();
732			}
733		} else {
734			print '<tr><td colspan="4"><em>' . __('No Output Fields') . '</em></td></tr>';
735		}
736
737		html_end_box();
738	}
739
740	form_save_button('data_input.php', 'return');
741
742	?>
743	<script type='text/javascript'>
744
745	$(function() {
746		$('.cdialog').remove();
747		$('#main').append("<div id='cdialog' class='cdialog'></div>");
748
749		$('.delete').unbind().click(function (event) {
750			event.preventDefault();
751
752			request = $(this).attr('href');
753			$.get(request)
754				.done(function(data) {
755					$('#cdialog').html(data);
756
757					applySkin();
758
759					$('#cdialog').dialog({
760						title: '<?php print __('Delete Data Input Field');?>',
761						close: function () { $('.delete').blur(); $('.selectable').removeClass('selected'); },
762						modal: false,
763						minHeight: 80,
764						minWidth: 500
765					});
766				})
767				.fail(function(data) {
768					getPresentHTTPError(data);
769				});
770		}).css('cursor', 'pointer');
771	});
772
773	</script>
774	<?php
775}
776
777function data() {
778	global $input_types, $di_actions, $item_rows;
779
780	/* ================= input validation and session storage ================= */
781	$filters = array(
782		'rows' => array(
783			'filter' => FILTER_VALIDATE_INT,
784			'pageset' => true,
785			'default' => '-1'
786			),
787		'page' => array(
788			'filter' => FILTER_VALIDATE_INT,
789			'default' => '1'
790			),
791		'filter' => array(
792			'filter' => FILTER_DEFAULT,
793			'pageset' => true,
794			'default' => ''
795			),
796		'sort_column' => array(
797			'filter' => FILTER_CALLBACK,
798			'default' => 'name',
799			'options' => array('options' => 'sanitize_search_string')
800			),
801		'sort_direction' => array(
802			'filter' => FILTER_CALLBACK,
803			'default' => 'ASC',
804			'options' => array('options' => 'sanitize_search_string')
805			)
806	);
807
808	validate_store_request_vars($filters, 'sess_data_input');
809	/* ================= input validation ================= */
810
811	if (get_request_var('rows') == '-1') {
812		$rows = read_config_option('num_rows_table');
813	} else {
814		$rows = get_request_var('rows');
815	}
816
817	html_start_box(__('Data Input Methods'), '100%', '', '3', 'center', 'data_input.php?action=edit');
818
819	?>
820	<tr class='even noprint'>
821		<td class='noprint'>
822		<form id='form_data_input' method='get' action='data_input.php'>
823			<table class='filterTable'>
824				<tr class='noprint'>
825					<td>
826						<?php print __('Search');?>
827					</td>
828					<td>
829						<input type='text' class='ui-state-default ui-corner-all' id='filter' name='filter' size='25' value='<?php print html_escape_request_var('filter');?>'>
830					</td>
831					<td>
832						<?php print __('Input Methods');?>
833					</td>
834					<td>
835						<select id='rows' name='rows' onChange='applyFilter()'>
836							<option value='-1'<?php print (get_request_var('rows') == '-1' ? ' selected>':'>') . __('Default');?></option>
837							<?php
838							if (cacti_sizeof($item_rows) > 0) {
839								foreach ($item_rows as $key => $value) {
840									print "<option value='" . $key . "'"; if (get_request_var('rows') == $key) { print ' selected'; } print '>' . html_escape($value) . "</option>\n";
841								}
842							}
843							?>
844						</select>
845					</td>
846					<td>
847						<span>
848							<input type='button' class='ui-button ui-corner-all ui-widget' id='refresh' value='<?php print __esc('Go');?>' title='<?php __esc('Set/Refresh Filters');?>'>
849							<input type='button' class='ui-button ui-corner-all ui-widget' id='clear' value='<?php print __esc('Clear');?>' title='<?php __esc('Clear Filters');?>'>
850						</span>
851					</td>
852				</tr>
853			</table>
854		</form>
855		<script type='text/javascript'>
856
857		function applyFilter() {
858			strURL  = 'data_input.php?header=false';
859			strURL += '&filter='+$('#filter').val();
860			strURL += '&rows='+$('#rows').val();
861			loadPageNoHeader(strURL);
862		}
863
864		function clearFilter() {
865			strURL = 'data_input.php?clear=1&header=false';
866			loadPageNoHeader(strURL);
867		}
868
869		$(function() {
870			$('#refresh').click(function() {
871				applyFilter();
872			});
873
874			$('#clear').click(function() {
875				clearFilter();
876			});
877
878			$('#form_data_input').submit(function(event) {
879				event.preventDefault();
880				applyFilter();
881			});
882		});
883
884		</script>
885		</td>
886	</tr>
887	<?php
888
889	html_end_box();
890
891	/* form the 'where' clause for our main sql query */
892	if (get_request_var('filter') != '') {
893		$sql_where = 'WHERE (di.name LIKE ' . db_qstr('%' . get_request_var('filter') . '%') . ')';
894	} else {
895		$sql_where = '';
896	}
897
898	$sql_where .= ($sql_where != '' ? ' AND' : 'WHERE') . " (di.hash NOT IN ('3eb92bb845b9660a7445cf9740726522', 'bf566c869ac6443b0c75d1c32b5a350e', '80e9e4c4191a5da189ae26d0e237f015', '332111d8b54ac8ce939af87a7eac0c06'))";
899
900	$sql_where  = api_plugin_hook_function('data_input_sql_where', $sql_where);
901
902	$total_rows = db_fetch_cell("SELECT count(*)
903		FROM data_input AS di
904		$sql_where");
905
906	$sql_order = get_order_string();
907	$sql_limit = ' LIMIT ' . ($rows*(get_request_var('page')-1)) . ',' . $rows;
908
909	$data_inputs = db_fetch_assoc("SELECT di.*,
910		SUM(CASE WHEN dtd.local_data_id=0 THEN 1 ELSE 0 END) AS templates,
911		SUM(CASE WHEN dtd.local_data_id>0 THEN 1 ELSE 0 END) AS data_sources
912		FROM data_input AS di
913		LEFT JOIN data_template_data AS dtd
914		ON di.id=dtd.data_input_id
915		$sql_where
916		GROUP BY di.id
917		$sql_order
918		$sql_limit");
919
920	$nav = html_nav_bar('data_input.php?filter=' . get_request_var('filter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, 6, __('Input Methods'), 'page', 'main');
921
922	form_start('data_input.php', 'chk');
923
924	print $nav;
925
926	html_start_box('', '100%', '', '3', 'center', '');
927
928	$display_text = array(
929		'name'         => array('display' => __('Data Input Name'),    'align' => 'left', 'sort' => 'ASC', 'tip' => __('The name of this Data Input Method.')),
930		'id' => array(
931			'display' => __('ID'),
932			'align'   => 'right',
933			'sort'    => 'ASC',
934			'tip'     => __('The internal database ID for this Data Input Method.  Useful when performing automation or debugging.')
935		),
936		'nosort' => array(
937			'display' => __('Deletable'),
938			'align'   => 'right',
939			'tip'     => __('Data Inputs that are in use cannot be Deleted. In use is defined as being referenced either by a Data Source or a Data Template.')
940		),
941		'data_sources' => array(
942			'display' => __('Data Sources Using'),
943			'align'   => 'right',
944			'sort'    => 'DESC',
945			'tip'     => __('The number of Data Sources that use this Data Input Method.')
946		),
947		'templates' => array(
948			'display' => __('Templates Using'),
949			'align'   => 'right',
950			'sort'    => 'DESC',
951			'tip'     => __('The number of Data Templates that use this Data Input Method.')
952		),
953		'type_id' => array(
954			'display' => __('Data Input Method'),
955			'align'   => 'right',
956			'sort'    => 'ASC',
957			'tip'     => __('The method used to gather information for this Data Input Method.')
958		)
959	);
960
961	html_header_sort_checkbox($display_text, get_request_var('sort_column'), get_request_var('sort_direction'), false);
962
963	$i = 0;
964	if (cacti_sizeof($data_inputs)) {
965		foreach ($data_inputs as $data_input) {
966			/* hide system types */
967			if ($data_input['templates'] > 0 || $data_input['data_sources'] > 0) {
968				$disabled = true;
969			} else {
970				$disabled = false;
971			}
972			form_alternate_row('line' . $data_input['id'], true, $disabled);
973			form_selectable_cell(filter_value($data_input['name'], get_request_var('filter'), 'data_input.php?action=edit&id=' . $data_input['id']), $data_input['id']);
974			form_selectable_cell($data_input['id'], $data_input['id'], '', 'right');
975			form_selectable_cell($disabled ? __('No'):__('Yes'), $data_input['id'], '', 'right');
976			form_selectable_cell(number_format_i18n($data_input['data_sources'], '-1'), $data_input['id'],'', 'right');
977			form_selectable_cell(number_format_i18n($data_input['templates'], '-1'), $data_input['id'],'', 'right');
978			form_selectable_cell($input_types[$data_input['type_id']], $data_input['id'], '', 'right');
979			form_checkbox_cell($data_input['name'], $data_input['id'], $disabled);
980			form_end_row();
981		}
982	} else {
983		print '<tr class="tableRow"><td colspan="' . (cacti_sizeof($display_text)+1) . '"><em>' . __('No Data Input Methods Found') . '</em></td></tr>';
984	}
985
986	html_end_box(false);
987
988	if (cacti_sizeof($data_inputs)) {
989		print $nav;
990	}
991
992	/* draw the dropdown containing a list of available actions for this form */
993	draw_actions_dropdown($di_actions);
994
995	form_end();
996}
997
998