Project

General

Profile

Download (42 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * pkg_edit.php
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2023 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * Licensed under the Apache License, Version 2.0 (the "License");
12
 * you may not use this file except in compliance with the License.
13
 * You may obtain a copy of the License at
14
 *
15
 * http://www.apache.org/licenses/LICENSE-2.0
16
 *
17
 * Unless required by applicable law or agreed to in writing, software
18
 * distributed under the License is distributed on an "AS IS" BASIS,
19
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
 * See the License for the specific language governing permissions and
21
 * limitations under the License.
22
 */
23

    
24
##|+PRIV
25
##|*IDENT=page-package-edit
26
##|*NAME=Package: Edit
27
##|*DESCR=Allow access to the 'Package: Edit' page.
28
##|*MATCH=pkg_edit.php*
29
##|-PRIV
30

    
31
ini_set('max_execution_time', '0');
32

    
33
require_once("filter.inc");
34
require_once("functions.inc");
35
require_once("guiconfig.inc");
36
require_once("shaper.inc");
37
require_once("pkg-utils.inc");
38
require_once("pfsense-utils.inc");
39
require_once("util.inc");
40

    
41
$xml = htmlspecialchars($_REQUEST['xml']);
42

    
43
$xml_fullpath = realpath('/usr/local/pkg/' . $xml);
44

    
45
if ($xml == "" || $xml_fullpath === false || substr($xml_fullpath, 0, strlen('/usr/local/pkg/')) != '/usr/local/pkg/') {
46
	$pgtitle = array(gettext("Package"), gettext("Editor"));
47
	$pglinks = array("", "@self");
48
	include("head.inc");
49
	print_info_box(gettext("No valid package defined."), 'danger', false);
50
	include("foot.inc");
51
	die;
52
} else {
53
	$pkg = parse_xml_config_pkg($xml_fullpath, "packagegui");
54
}
55

    
56
if ($pkg['include_file'] != "") {
57
	require_once($pkg['include_file']);
58
}
59

    
60
if (!isset($pkg['adddeleteeditpagefields'])) {
61
	$only_edit = true;
62
} else {
63
	$only_edit = false;
64
}
65

    
66
$id = $_REQUEST['id'];
67
if (isset($_POST['id'])) {
68
	$id = htmlspecialchars($_POST['id']);
69
}
70

    
71
// Not posting?	 Then user is editing a record. There must be a valid id
72
// when editing a record.
73
if (!$id && !$_POST) {
74
	$id = "0";
75
}
76

    
77
if (!is_numeric($id)) {
78
	header("Location: /");
79
	exit;
80
}
81

    
82
if ($pkg['custom_php_global_functions'] != "") {
83
	eval($pkg['custom_php_global_functions']);
84
}
85

    
86
// grab the installedpackages->package_name section.
87
if ($config['installedpackages'] && !is_array($config['installedpackages'][xml_safe_fieldname($pkg['name'])])) {
88
	$config['installedpackages'][xml_safe_fieldname($pkg['name'])] = array();
89
}
90

    
91
if ($config['installedpackages'] && !is_array($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'])) {
92
	$config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'] = array();
93
}
94

    
95
/* If the first entry in the array is an empty <config/> tag, kill it.
96
 * See the following tickets for more:
97
 *  https://redmine.pfsense.org/issues/7624
98
 *  https://redmine.pfsense.org/issues/476
99
 */
100

    
101
init_config_arr(array('installedpackages', xml_safe_fieldname($pkg['name']), 'config'));
102
if ((count($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config']) > 0) &&
103
    (empty($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'][0])) &&
104
    is_array($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'])) {
105
	array_shift($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config']);
106
}
107

    
108
$a_pkg = &$config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'];
109

    
110
if ($_REQUEST['savemsg'] != "") {
111
	$savemsg = htmlspecialchars($_REQUEST['savemsg']);
112
}
113

    
114
if ($pkg['custom_php_command_before_form'] != "") {
115
	eval($pkg['custom_php_command_before_form']);
116
}
117

    
118
if ($_POST) {
119
	$rows = 0;
120

    
121
	$input_errors = array();
122
	$reqfields = array();
123
	$reqfieldsn = array();
124
	foreach ($pkg['fields']['field'] as $field) {
125
		if (isset($field['required'])) {
126
			if ($field['fieldname']) {
127
				$reqfields[] = $field['fieldname'];
128
			}
129
			if ($field['fielddescr']) {
130
				$reqfieldsn[] = $field['fielddescr'];
131
			}
132
		}
133
	}
134
	do_input_validation($_POST, $reqfields, $reqfieldsn, $input_errors);
135

    
136
	if ($pkg['custom_php_validation_command']) {
137
		eval($pkg['custom_php_validation_command']);
138
	}
139

    
140
	if ($_POST['act'] == "del") {
141
		if ($pkg['custom_delete_php_command']) {
142
			if ($pkg['custom_php_command_before_form'] != "") {
143
				eval($pkg['custom_php_command_before_form']);
144
			}
145
			eval($pkg['custom_delete_php_command']);
146
		}
147
		write_config($pkg['delete_string']);
148
		// resync the configuration file code if defined.
149
		if ($pkg['custom_php_resync_config_command'] != "") {
150
			if ($pkg['custom_php_command_before_form'] != "") {
151
				eval($pkg['custom_php_command_before_form']);
152
			}
153
			eval($pkg['custom_php_resync_config_command']);
154
		}
155
	} else {
156
		if (!$input_errors && $pkg['custom_add_php_command']) {
157
			if ($pkg['donotsave'] != "" or $pkg['preoutput'] != "") {
158
				include("head.inc");
159
			}
160

    
161
			if ($pkg['preoutput']) {
162
				echo "<pre>";
163
			}
164
			eval($pkg['custom_add_php_command']);
165
			if ($pkg['preoutput']) {
166
				echo "</pre>";
167
			}
168
		}
169
	}
170

    
171
	if (empty($pkg['donotsave'])) {
172

    
173
		// store values in xml configuration file.
174
		if (!$input_errors) {
175
			$pkgarr = array();
176
			foreach ($pkg['fields']['field'] as $fields) {
177
				switch ($fields['type']) {
178
					case "rowhelper":
179
						// save rowhelper items.
180
						#$rowhelpername=($fields['fieldname'] ? $fields['fieldname'] : "row");
181
						$rowhelpername="row";
182
						foreach ($fields['rowhelper']['rowhelperfield'] as $rowhelperfield) {
183
							foreach ($_POST as $key => $value) {
184
								$matches = array();
185
								if (preg_match("/^{$rowhelperfield['fieldname']}(\d+)$/", $key, $matches)) {
186
									if ($rowhelperfield['type'] == "textarea") {
187
										$pkgarr[$rowhelpername][$matches[1]][$rowhelperfield['fieldname']] = unixnewlines($value);
188
									} else {
189
										$pkgarr[$rowhelpername][$matches[1]][$rowhelperfield['fieldname']] = $value;
190
									}
191
								}
192
							}
193
						}
194
						break;
195
					case "textarea":
196
						$fieldname = $fields['fieldname'];
197
						$fieldvalue = unixnewlines(trim($_POST[$fieldname]));
198
						if ($fields['encoding'] == 'base64') {
199
							$fieldvalue = base64_encode($fieldvalue);
200
						}
201
						if ($fieldname) {
202
							$pkgarr[$fieldname] = $fieldvalue;
203
						}
204
					default:
205
						$fieldname = $fields['fieldname'];
206
						if ($fieldname == "interface_array") {
207
							$fieldvalue = $_POST[$fieldname];
208
						} elseif (is_array($_POST[$fieldname])) {
209
							$fieldvalue = implode(',', $_POST[$fieldname]);
210
						} else {
211
							$fieldvalue = trim($_POST[$fieldname]);
212
							if ($fields['encoding'] == 'base64') {
213
								$fieldvalue = base64_encode($fieldvalue);
214
							}
215
						}
216
						if ($fieldname) {
217
							$pkgarr[$fieldname] = $fieldvalue;
218
						}
219
					}
220
			}
221

    
222
			/* If the user supplied an ID and it exists, or if id=0
223
			 * and the settings are invalid, overwrite.
224
			 * See https://redmine.pfsense.org/issues/7624
225
			 */
226
			if (isset($id) && ($a_pkg[$id] ||
227
			   (($id == 0) && !is_array($a_pkg[$id])) )) {
228
				$a_pkg[$id] = $pkgarr;
229
			} else {
230
				$a_pkg[] = $pkgarr;
231
			}
232

    
233
			write_config($pkg['addedit_string']);
234
			// late running code
235
			if ($pkg['custom_add_php_command_late'] != "") {
236
				eval($pkg['custom_add_php_command_late']);
237
			}
238

    
239
			if (isset($pkg['filter_rules_needed'])) {
240
				filter_configure();
241
			}
242

    
243
			// resync the configuration file code if defined.
244
			if ($pkg['custom_php_resync_config_command'] != "") {
245
				eval($pkg['custom_php_resync_config_command']);
246
			}
247

    
248
			parse_package_templates();
249

    
250
			/* if start_command is defined, restart w/ this */
251
			if ($pkg['start_command'] != "") {
252
				exec($pkg['start_command'] . ">/dev/null 2&>1");
253
			}
254

    
255
			/* if restart_command is defined, restart w/ this */
256
			if ($pkg['restart_command'] != "") {
257
				exec($pkg['restart_command'] . ">/dev/null 2&>1");
258
			}
259

    
260
			if ($pkg['aftersaveredirect'] != "") {
261
				pfSenseHeader($pkg['aftersaveredirect']);
262
			} elseif (!$pkg['adddeleteeditpagefields']) {
263
				pfSenseHeader("pkg_edit.php?xml={$xml}&id=0");
264
			} elseif (!$pkg['preoutput']) {
265
				pfSenseHeader("pkg.php?xml=" . $xml);
266
			}
267
			exit;
268
		} else {
269
			$get_from_post = true;
270
		}
271
	} elseif (!$input_errors) {
272
		// donotsave is enabled.  lets simply exit.
273
		exit;
274
	}
275
}
276

    
277

    
278
// Turn an embedded table into a bootstrap class table. This is for backward compatibility.
279
// We remove any table attributes in the XML and replace them with Bootstrap table classes
280
function bootstrapTable($text) {
281
	$t = strpos($text, '<table') + strlen('<table');	// Find the <table tag
282
	$c = strpos($text, '>', $t);						// And its closing bracket
283

    
284
	// Substitute everything inbetween with our new classes
285
	if ($t && $c && (($c - $t) < 200)) {
286
		return(substr_replace($text, ' class="table table-striped table-hover table-condensed"', $t, ($c - $t)));
287
	}
288
}
289

    
290
/*
291
 * ROW helper function. Creates one element in the row from a PHP table by adding
292
 * the specified element to $group
293
 */
294
function display_row($trc, $value, $fieldname, $type, $rowhelper, $description, $ewidth = null) {
295
	global $text, $group, $config;
296

    
297
	switch ($type) {
298
		case "input":
299
			$inpt = new Form_Input(
300
				$fieldname . $trc,
301
				null,
302
				'text',
303
				$value
304
			);
305

    
306
			$inpt->setHelp($description);
307

    
308
			if ($ewidth) {
309
				$inpt->setWidth($ewidth);
310
			}
311

    
312
			$group->add($inpt);
313
			break;
314
		case "checkbox":
315
			$group->add(new Form_Checkbox(
316
				$fieldname . $trc,
317
				null,
318
				null,
319
				$value,
320
				'ON'
321
			))->setHelp($description);
322

    
323
			break;
324
		case "password":
325
			$group->add(new Form_Input(
326
				$fieldname . $trc,
327
				null,
328
				'password',
329
				$value
330
			))->setHelp($description)->setAttribute('autocomplete', 'new-password');
331
			break;
332
		case "textarea":
333
			$group->add(new Form_Textarea(
334
				$fieldname . $trc,
335
				null,
336
				$value
337
			))->setHelp($description);
338

    
339
			break;
340
		case "select":
341
			$options = array();
342
			foreach ($rowhelper['options']['option'] as $rowopt) {
343
				$options[$rowopt['value']] = $rowopt['name'];
344
			}
345

    
346
			$grp = new Form_Select(
347
				$fieldname . $trc,
348
				null,
349
				$value,
350
				$options
351
			);
352

    
353
			$grp->setHelp($description);
354

    
355
			if ($ewidth) {
356
				$grp->setWidth($ewidth);
357
			}
358

    
359
			$group->add($grp);
360

    
361
			break;
362
		case "interfaces_selection":
363
			$size = ($size ? "size=\"{$size}\"" : '');
364
			$multiple = '';
365
			if (isset($rowhelper['multiple'])) {
366
				$multiple = "multiple";
367
			}
368
			echo "<select style='height:22px;' id='{$fieldname}{$trc}' name='{$fieldname}{$trc}' {$size} {$multiple}>\n";
369
			$ifaces = get_configured_interface_with_descr();
370
			$additional_ifaces = $rowhelper['add_to_interfaces_selection'];
371
			if (!empty($additional_ifaces)) {
372
				$ifaces = array_merge($ifaces, explode(',', $additional_ifaces));
373
			}
374

    
375
			if (is_array($value)) {
376
				$values = $value;
377
			} else {
378
				$values = explode(',', $value);
379
			}
380

    
381
			$ifaces["lo0"] = "loopback";
382
			$options = array();
383
			$selected = array();
384

    
385
			foreach ($ifaces as $ifname => $iface) {
386
				$options[$ifname] = $iface;
387

    
388
				if (in_array($ifname, $values)) {
389
					array_push($selected, $ifname);
390
				}
391
			}
392

    
393
			$group->add(new Form_Select(
394
				$fieldname . $trc,
395
				null,
396
				($multiple) ? $selected:$selected[0],
397
				$options,
398
				$multiple
399
			))->setHelp($description);
400

    
401
			//echo "</select>\n";
402
			break;
403
		case "select_source":
404
			$options = array();
405
			$selected = array();
406

    
407
			if (isset($rowhelper['show_disable_value'])) {
408
				$options[$rowhelper['show_disable_value']] = $rowhelper['show_disable_value'];
409
			}
410

    
411
			$source_url = $rowhelper['source'];
412
			eval("\$pkg_source_txt = &$source_url;");
413

    
414
			foreach ($pkg_source_txt as $opt) {
415
				$source_name = ($rowhelper['source_name'] ? $opt[$rowhelper['source_name']] : $opt[$rowhelper['name']]);
416
				$source_value = ($rowhelper['source_value'] ? $opt[$rowhelper['source_value']] : $opt[$rowhelper['value']]);
417
				$options[$source_value] = $source_name;
418

    
419
				if ($source_value == $value) {
420
					array_push($selected, $value);
421
				}
422
			}
423

    
424
			$group->add(new Form_Select(
425
				$fieldname . $trc,
426
				null,
427
				($multiple) ? $selected:$selected[0],
428
				$options,
429
				$multiple
430
			))->setHelp($description);
431

    
432
			break;
433
	}
434
}
435

    
436
function fixup_string($string) {
437
	global $config;
438
	// fixup #1: $myurl -> http[s]://ip_address:port/
439
	$https = "";
440
	$port = config_get_path('system/webguiport');
441
	if ($port != "443" and $port != "80") {
442
		$urlport = ":" . $port;
443
	} else {
444
		$urlport = "";
445
	}
446

    
447
	if ($config['system']['webgui']['protocol'] == "https") {
448
		$https = "s";
449
	}
450
	$myurl = "http" . $https . "://" . getenv("HTTP_HOST") . $urlport;
451
	$newstring = str_replace("\$myurl", $myurl, $string);
452
	$string = $newstring;
453
	// fixup #2: $wanip
454
	$curwanip = get_interface_ip();
455
	$newstring = str_replace("\$wanip", $curwanip, $string);
456
	$string = $newstring;
457
	// fixup #3: $lanip
458
	$lancfg = config_get_path('interfaces/lan');
459
	$lanip = $lancfg['ipaddr'];
460
	$newstring = str_replace("\$lanip", $lanip, $string);
461
	$string = $newstring;
462
	// fixup #4: fix'r'up here.
463
	return $newstring;
464
}
465

    
466
/*
467
 *	Parse templates if they are defined
468
 */
469
function parse_package_templates() {
470
	global $pkg;
471
	if ($pkg['templates']['template'] != "") {
472
		foreach ($pkg['templates']['template'] as $pkg_template_row) {
473
			$filename = $pkg_template_row['filename'];
474
			$template_text = $pkg_template_row['templatecontents'];
475
			/* calculate total row helpers count and */
476
			/* change fields defined as fieldname_fieldvalue to their value */
477
			foreach ($pkg['fields']['field'] as $fields) {
478
				switch ($fields['type']) {
479
					case "rowhelper":
480
						// save rowhelper items.
481
						$row_helper_total_rows = 0;
482
						$row_helper_data = "";
483
						foreach ($fields['rowhelper']['rowhelperfield'] as $rowhelperfield) {
484
							foreach ($_POST as $key => $value) {
485
								if (preg_match("/^{$rowhelperfield['fieldname']}(\d+)$/", $key, $matches)) {
486
									$row_helper_total_rows++;
487
									$row_helper_data .= $value;
488
									$sep = "";
489
									ereg($rowhelperfield['fieldname'] . "_fieldvalue\[(.*)\]", $template_text, $sep);
490
									foreach ($sep as $se) {
491
										$separator = $se;
492
									}
493
									if ($separator != "") {
494
										$row_helper_data = ereg_replace("  ", $separator, $row_helper_data);
495
										$template_text = ereg_replace("\[{$separator}\]", "", $template_text);
496
									}
497
									$template_text = str_replace($rowhelperfield['fieldname'] . "_fieldvalue", $row_helper_data, $template_text);
498
								}
499
							}
500
						}
501
						break;
502
					default:
503
						$fieldname = $fields['fieldname'];
504
						$fieldvalue = $_POST[$fieldname];
505
						$template_text = str_replace($fieldname . "_fieldvalue", $fieldvalue, $template_text);
506
				}
507
			}
508
			/* replace $domain_total_rows with total rows */
509
			$template_text = str_replace("$domain_total_rows", $row_helper_total_rows, $template_text);
510

    
511
			/* replace cr's */
512
			$template_text = str_replace("\\n", "\n", $template_text);
513

    
514
			/* write out new template file */
515
			$fout = fopen($filename, "w");
516
			fwrite($fout, $template_text);
517
			fclose($fout);
518
		}
519
	}
520
}
521

    
522
//breadcrumb
523
if ($pkg['title'] != "") {
524
	if (!$only_edit) {
525
		$pkg['title'] = $pkg['title'] . '/Edit';
526
	}
527

    
528
	if (strpos($pkg['title'], '/')) {
529
		$title = explode('/', $pkg['title']);
530

    
531
		foreach ($title as $subtitle) {
532
			$pgtitle[] = gettext($subtitle);
533
			$pglinks[] = ((($subtitle == "Edit") || (strlen($pkg['menu'][0]['url']) == 0)) ? "@self" : $pkg['menu'][0]['url']);
534
		}
535
	} else {
536
		$pgtitle = array(gettext("Package"), gettext($pkg['title']));
537
		$pglinks = array("", ((($subtitle == "Edit") || (strlen($pkg['menu'][0]['url']) == 0)) ? "@self" : $pkg['menu'][0]['url']));
538
	}
539
} else {
540
	$pgtitle = array(gettext("Package"), gettext("Editor"));
541
	$pglinks = array("", "@self");
542
}
543

    
544
// Create any required tabs
545
if ($pkg['tabs'] != "") {
546
	$tab_array = array();
547
	foreach ($pkg['tabs']['tab'] as $tab) {
548
		if ($tab['tab_level']) {
549
			$tab_level = $tab['tab_level'];
550
		} else {
551
			$tab_level = 1;
552
		}
553

    
554
		if (isset($tab['active'])) {
555
			$active = true;
556
			$pgtitle[] = $tab['text'] ;
557
			$pglinks[] = ((strlen($tab['url']) > 0) ? $tab['url'] : "@self");
558
		} else {
559
			$active = false;
560
		}
561

    
562
		$urltmp = "";
563
		if ($tab['url'] != "") {
564
			$urltmp = $tab['url'];
565
		}
566

    
567
		if ($tab['xml'] != "") {
568
			$urltmp = "pkg_edit.php?xml=" . $tab['xml'];
569
		}
570

    
571
		$addresswithport = getenv("HTTP_HOST");
572
		$colonpos = strpos($addresswithport, ":");
573

    
574
		if ($colonpos !== False) {
575
			//my url is actually just the IP address of the pfsense box
576
			$myurl = substr($addresswithport, 0, $colonpos);
577
		} else {
578
			$myurl = $addresswithport;
579
		}
580

    
581
		// eval url so that above $myurl item can be processed if need be.
582
		$url = str_replace('$myurl', $myurl, $urltmp);
583

    
584
		$tab_array[$tab_level][] = array(
585
			$tab['text'],
586
			$active,
587
			$url
588
		);
589
	}
590

    
591
	ksort($tab_array);
592
}
593
if (!empty($pkg['tabs'])) {
594
	$shortcut_section = $pkg['shortcut_section'];
595
}
596

    
597
include("head.inc");
598
if ($pkg['custom_php_after_head_command']) {
599
	eval($pkg['custom_php_after_head_command']);
600
}
601
if (isset($tab_array)) {
602
	foreach ($tab_array as $tab) {
603
		display_top_tabs($tab);
604
	}
605
}
606

    
607
// Start of page display
608
if ($input_errors) {
609
	print_input_errors($input_errors);
610
}
611

    
612
if ($savemsg) {
613
	print_info_box($savemsg, 'success');
614
}
615

    
616
$cols = 0;
617
$savevalue = gettext("Save");
618
if ($pkg['savetext'] != "") {
619
	$savevalue = $pkg['savetext'];
620
}
621

    
622
$savehelp = "";
623
if ($pkg['savehelp'] != "") {
624
	$savehelp = $pkg['savehelp'];
625
}
626

    
627
$saveicon = "fa-save";
628
if ($pkg['saveicon'] != "") {
629
	$saveicon = $pkg['saveicon'];
630
}
631

    
632
$savebtnclass = "btn-primary";
633
if ($pkg['savebtnclass'] != "") {
634
	$savebtnclass = $pkg['savebtnclass'];
635
}
636

    
637
$grouping = false; // Indicates the elements we are composing are part of a combined group
638

    
639
$savebutton = new Form_Button(
640
	'submit',
641
	$savevalue,
642
	null,
643
	$saveicon
644
);
645
$savebutton->addClass($savebtnclass);
646

    
647
if ($savehelp) {
648
	$savebutton->setHelp($savehelp);
649
}
650

    
651
$form = new Form($savebutton);
652

    
653
$form->addGlobal(new Form_Input(
654
	'xml',
655
	null,
656
	'hidden',
657
	$xml
658
));
659

    
660
/* If a package's XML has <advanced_options/> configured, then setup
661
 * the section for the fields that have <advancedfield/> set.
662
 * These fields will be placed below other fields in a separate area titled 'Advanced Features'.
663
 * These advanced fields are not normally configured and generally left to default to 'default settings'.
664
 */
665

    
666
if ($pkg['advanced_options'] == "enabled") {
667
	$advfield_count = 0;
668
	$advanced = new Form_Section("Advanced Features");
669
	$advanced->addClass('advancedoptions');
670
}
671

    
672
$js_array = array();
673

    
674
// Now loop through all of the fields defined in the XML
675
if (!is_array($pkg['fields']['field'])) {
676
	$pkg['fields']['field'] = array();
677
}
678
foreach ($pkg['fields']['field'] as $pkga) {
679

    
680
	$action = "";
681
	$uid = "";
682

    
683
	if ($pkga['type'] == "sorting") {
684
		continue;
685
	}
686

    
687
	// Generate a new section
688
	if ($pkga['type'] == "listtopic") {
689
		if (isset($pkga['advancedfield']) && isset($advfield_count)) {
690
			$advanced->addInput(new Form_StaticText(
691
				strip_tags($pkga['name']),
692
				null
693
			));
694

    
695
			$advfield_count++;
696
		} else {
697
			if (isset($section)) {
698
				$form->add($section);
699
			}
700

    
701
			if (isset($pkga['collapse'])) {
702
				$uid = uniqid("section");
703

    
704
				$action = COLLAPSIBLE;
705

    
706
				if ($pkga['collapse'] == "open") {
707
					$action |= SEC_OPEN;
708
				} else {
709
					$action |= SEC_CLOSED;
710
				}
711
			}
712

    
713
			$section = new Form_Section(strip_tags($pkga['name']), $uid, $action);
714
		}
715

    
716
		continue;
717
	}
718

    
719
	// 'begin' starts a form group. ('end' ends it)
720
	if ($pkga['combinefields'] == "begin") {
721
		$group = new Form_Group(strip_tags($pkga['fielddescr']));
722
		$grouping = true;
723
	}
724

    
725
	$size = "";
726
	$colspan="";
727

    
728
	// if user is editing a record, load in the data.
729
	$fieldname = $pkga['fieldname'];
730
	unset($value);
731
	if ($get_from_post) {
732
		$value = $_POST[$fieldname];
733
		if (is_array($value)) {
734
			$value = implode(',', $value);
735
		}
736
	} else {
737
		if (isset($id) && isset($a_pkg[$id][$fieldname])) {
738
			$value = $a_pkg[$id][$fieldname];
739
		} else {
740
			if (isset($pkga['default_value'])) {
741
				$value = $pkga['default_value'];
742
			}
743
		}
744
	}
745

    
746
	// If we get here but have no $section, the package config file probably had no listtopic field
747
	// We can create a section with a generic name to fix that
748
	if (!$section) {
749
		$section = new Form_Section('General Options');
750
	}
751

    
752
	// If this is a required field, pre-pend a "*" to the field description
753
	// This tells the system to add "element-required" class text decoration to the field label
754
	if (isset($pkga['required'])) {
755
		$pkga['fielddescr'] = "*" . $pkga['fielddescr'];
756
	}
757

    
758
	switch ($pkga['type']) {
759
		// Create an input element. The format is slightly different depending on whether we are composing a group,
760
		// section, or advanced section. This is true for every element type
761
		case "input":
762
			if (($pkga['encoding'] == 'base64') && !$get_from_post && !empty($value)) {
763
				$value = base64_decode($value);
764
			}
765

    
766
			$grp = new Form_Input(
767
					$pkga['fieldname'],
768
					$pkga['fielddescr'],
769
					'text',
770
					$value
771
				);
772

    
773
			$grp->setHelp($pkga['description']);
774

    
775
			if ($pkga['width']) {
776
				$grp->setWidth($pkga['width']);
777
			}
778

    
779
			if ($grouping) {
780
				$group->add($grp);
781
			} else {
782
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
783
					$advanced->addInput($grp);
784
				} else {
785
					$section->addInput($grp);
786
				}
787
			}
788

    
789
			break;
790

    
791
		case "password":
792
			if (($pkga['encoding'] == 'base64') && !$get_from_post && !empty($value)) {
793
				$value = base64_decode($value);
794
			}
795

    
796
			// Create a password element
797
			if ($grouping) {
798
				$group->add(new Form_Input(
799
					$pkga['fieldname'],
800
					$pkga['fielddescr'],
801
					'password',
802
					$value
803
				))->setHelp($pkga['description'])->setAttribute('autocomplete', 'new-password');
804
			} else {
805
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
806
					$advanced->addInput(new Form_Input(
807
						$pkga['fieldname'],
808
						$pkga['fielddescr'],
809
						'password',
810
						$value
811
					))->setHelp($pkga['description'])->setAttribute('autocomplete', 'new-password');
812
				} else {
813
					$section->addInput(new Form_Input(
814
						$pkga['fieldname'],
815
						$pkga['fielddescr'],
816
						'password',
817
						$value
818
					))->setHelp($pkga['description'])->setAttribute('autocomplete', 'new-password');
819
				}
820
			}
821

    
822
			break;
823

    
824
		case "info":
825
			// If the info contains a table we should detect and Bootstrap it
826

    
827
			if (strpos($pkga['description'], '<table') !== FALSE) {
828
				$info = bootstrapTable($pkga['description']);
829
			} else {
830
				$info = $pkga['description'];
831
			}
832

    
833
			if (isset($pkga['advancedfield']) && isset($advfield_count)) {
834
				$advanced->addInput(new Form_StaticText(
835
					strip_tags($pkga['fielddescr']),
836
					$info
837
				));
838
			} else {
839
				$section->addInput(new Form_StaticText(
840
					strip_tags($pkga['fielddescr']),
841
					$info
842
				));
843
			}
844

    
845
			break;
846

    
847
		case "select":
848
			// Create a select element
849
			$optionlist = array();
850
			$selectedlist = array();
851

    
852
			$fieldname = $pkga['fieldname'];
853

    
854
			if (isset($pkga['multiple'])) {
855
				$multiple = 'multiple';
856
				$items = explode(',', $value);
857
				$fieldname .= "[]";
858
			} else {
859
				$multiple = '';
860
				$items = array($value);
861
			}
862

    
863
			$onchange = (isset($pkga['onchange']) ? "{$pkga['onchange']}" : '');
864

    
865
			foreach ($pkga['options']['option'] as $opt) {
866
				$optionlist[$opt['value']] = $opt['name'];
867

    
868
				if (in_array($opt['value'], $items)) {
869
					array_push($selectedlist, $opt['value']);
870
				}
871
			}
872

    
873
			if (isset($pkga['advancedfield']) && isset($advfield_count)) {
874
				$function = $grouping ? $advanced->add:$advanced->addInput;
875
			} else {
876
				$function = ($grouping) ? $section->add:$section->addInput;
877
			}
878

    
879
			$grp = new Form_Select(
880
						$pkga['fieldname'],
881
						strip_tags($pkga['fielddescr']),
882
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
883
						$optionlist,
884
						isset($pkga['multiple'])
885
					);
886

    
887
			$grp ->setHelp($pkga['description'])->setOnchange($onchange)->setAttribute('size', $pkga['size']);
888

    
889
			if ($pkga['width']) {
890
				$grp->setWidth($pkga['width']);
891
			}
892

    
893
			if ($grouping) {
894
				$group->add($grp);
895
			} else {
896
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
897
					$advanced->addInput($grp);
898
				} else {
899
					$section->addInput($grp);
900
				}
901
			}
902

    
903
			break;
904

    
905
		case "select_source":
906

    
907
			if (isset($pkga['multiple'])) {
908
				$items = explode(',', $value);
909
				$fieldname .= "[]";
910
			} else {
911
				$items = array($value);
912
			}
913

    
914
			$onchange = (isset($pkga['onchange']) ? "{$pkga['onchange']}" : '');
915

    
916
			$source_url = $pkga['source'];
917
			try{
918
				@eval("\$pkg_source_txt = &$source_url;");
919
			} catch (\Throwable | \Error | \Exception $e) {
920
				//do nothing
921
			}
922
			#check if show disable option is present on xml
923
			if (!is_array($pkg_source_txt)) {
924
				$pkg_source_txt = array();
925
			}
926
			if (isset($pkga['show_disable_value'])) {
927
				array_push($pkg_source_txt,
928
					array(($pkga['source_name']? $pkga['source_name'] : $pkga['name'])=> $pkga['show_disable_value'], ($pkga['source_value']? $pkga['source_value'] : $pkga['value'])=> $pkga['show_disable_value']));
929
			}
930

    
931
			$srcoptions = array();
932
			$srcselected = array();
933

    
934
			foreach ($pkg_source_txt as $opt) {
935
				$source_name =($pkga['source_name']? $opt[$pkga['source_name']] : $opt[$pkga['name']]);
936
				$source_value =($pkga['source_value'] ? $opt[$pkga['source_value']] : $opt[$pkga['value']]);
937
				$srcoptions[$source_value] = $source_name;
938

    
939
				if (in_array($source_value, $items)) {
940
					array_push($srcselected, $source_value);
941
				}
942
			}
943

    
944
			$descr = (isset($pkga['description'])) ? $pkga['description'] : "";
945
			if ($grouping) {
946
				$group->add(new Form_Select(
947
					$pkga['fieldname'],
948
					strip_tags($pkga['fielddescr']),
949
					isset($pkga['multiple']) ? $srcselected:$srcselected[0],
950
					$srcoptions,
951
					isset($pkga['multiple'])
952
				))->setHelp($descr)->setOnchange($onchange);
953
			} else {
954
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
955
					$advanced->addInput(new Form_Select(
956
						$pkga['fieldname'],
957
						strip_tags($pkga['fielddescr']),
958
						isset($pkga['multiple']) ? $srcselected:$srcselected[0],
959
						$srcoptions,
960
						isset($pkga['multiple'])
961
					))->setHelp($descr)->setOnchange($onchange);
962
				} else {
963
					$section->addInput(new Form_Select(
964
						$pkga['fieldname'],
965
						strip_tags($pkga['fielddescr']),
966
						isset($pkga['multiple']) ? $srcselected:$srcselected[0],
967
						$srcoptions,
968
						isset($pkga['multiple'])
969
					))->setHelp($descr)->setOnchange($onchange);
970
				}
971
			}
972

    
973
			break;
974

    
975
		case "vpn_selection" :
976
			$vpnlist = array();
977

    
978
			foreach ($config['ipsec']['phase1'] as $vpn) {
979
				$vpnlist[$vpn['descr']] = $vpn['descr'];
980

    
981
			}
982

    
983
			if ($grouping) {
984
				$group->add(new Form_Select(
985
					$pkga['fieldname'],
986
					null,
987
					false,
988
					$vpnlist
989
				))->setHelp(fixup_string($pkga['description']));
990
			} else {
991
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
992
					$advanced->addInput(new Form_Select(
993
						$pkga['fieldname'],
994
						null,
995
						false,
996
						$vpnlist
997
					))->setHelp(fixup_string($pkga['description']));
998
				} else {
999
					$section->addInput(new Form_Select(
1000
						$pkga['fieldname'],
1001
						null,
1002
						false,
1003
						$vpnlist
1004
					))->setHelp(fixup_string($pkga['description']));
1005
				}
1006
			}
1007

    
1008
			break;
1009

    
1010
		// Create a checkbox element
1011
		case "checkbox":
1012
			$onchange = (isset($pkga['onchange']) ? "{$pkga['onchange']}" : '');
1013
			if (isset($pkga['enablefields']) || isset($pkga['checkenablefields'])) {
1014
				$onclick = 'javascript:enablechange();';
1015
			} else {
1016
				$onclick = '';
1017
			}
1018

    
1019
			if ($grouping) {
1020
				$group->add(new Form_Checkbox(
1021
					$pkga['fieldname'],
1022
					$pkga['fielddescr'],
1023
					fixup_string($pkga['description']),
1024
					($value == "on"),
1025
					'on'
1026
				))->setOnclick($onclick)
1027
				  ->setOnchange($onchange)
1028
				  ->setHelp($pkga['sethelp']);
1029
			} else {
1030
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1031
					$advanced->addInput(new Form_Checkbox(
1032
						$pkga['fieldname'],
1033
						$pkga['fielddescr'],
1034
						fixup_string($pkga['description']),
1035
						($value == "on"),
1036
						'on'
1037
					))->setOnclick($onclick)
1038
					  ->setOnchange($onchange)
1039
					  ->setHelp($pkga['sethelp']);
1040
				} else {
1041
					$section->addInput(new Form_Checkbox(
1042
						$pkga['fieldname'],
1043
						$pkga['fielddescr'],
1044
						fixup_string($pkga['description']),
1045
						($value == "on"),
1046
						'on'
1047
					))->setOnclick($onclick)
1048
					  ->setOnchange($onchange)
1049
					  ->setHelp($pkga['sethelp']);
1050
				}
1051
			}
1052

    
1053
			break;
1054

    
1055
		// Create a textarea element
1056
		case "textarea":
1057
			$rows = $cols = 0;
1058

    
1059
			if ($pkga['rows']) {
1060
				$rows = $pkga['rows'];
1061
			}
1062
			if ($pkga['cols']) {
1063
				$cols = $pkga['cols'];
1064
			}
1065

    
1066
			if (($pkga['encoding'] == 'base64') && !$get_from_post && !empty($value)) {
1067
				$value = base64_decode($value);
1068
			}
1069

    
1070
			$grp = new Form_Textarea(
1071
					$pkga['fieldname'],
1072
					$pkga['fielddescr'],
1073
					$value
1074
			);
1075

    
1076
			$grp->setHelp(fixup_string($pkga['description']));
1077

    
1078
			if ($rows > 0) {
1079
				$grp->setRows($rows);
1080
			}
1081

    
1082
			if ($cols > 0) {
1083
				$grp->setCols($cols);
1084
			}
1085

    
1086
			if ($pkga['wrap'] == "off") {
1087
				$grp->setAttribute("wrap", "off");
1088
				$grp->setAttribute("style", "white-space:nowrap; width: auto;");
1089
			} else {
1090
				$grp->setAttribute("style", "width: auto;");
1091
			}
1092

    
1093
			if ($grouping) {
1094
				$group->add($grp);
1095
			} else {
1096
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1097
					$advanced->addInput($grp);
1098
				} else {
1099
					$section->addInput($grp);
1100
				}
1101
			}
1102

    
1103
			break;
1104

    
1105
		case "aliases":
1106

    
1107
			// Use xml tag <typealiases> to filter type aliases
1108
			$size = ($pkga['size'] ? "size=\"{$pkga['size']}\"" : '');
1109
			$fieldname = $pkga['fieldname'];
1110

    
1111
			init_config_arr(array('aliases', 'alias'));
1112
			$a_aliases = &$config['aliases']['alias'];
1113
			$addrisfirst = 0;
1114
			$aliasesaddr = "";
1115

    
1116
			if (isset($a_aliases)) {
1117
				if (!empty($pkga['typealiases'])) {
1118
					foreach ($a_aliases as $alias) {
1119
						if ($alias['type'] == $pkga['typealiases']) {
1120
							if ($addrisfirst == 1) {
1121
								$aliasesaddr .= ",";
1122
							}
1123
							$aliasesaddr .= "'" . $alias['name'] . "'";
1124
							$addrisfirst = 1;
1125
						}
1126
					}
1127
				} else {
1128
					foreach ($a_aliases as $alias) {
1129
						if ($addrisfirst == 1) {
1130
							$aliasesaddr .= ",";
1131
						}
1132
						$aliasesaddr .= "'" . $alias['name'] . "'";
1133
						$addrisfirst = 1;
1134
					}
1135
				}
1136
			}
1137

    
1138
			$grp = new Form_Input(
1139
					$pkga['fieldname'],
1140
					$pkga['fielddescr'],
1141
					'text',
1142
					$value
1143
				);
1144

    
1145
			$grp->setHelp($pkga['description']);
1146

    
1147
			if ($pkga['width']) {
1148
				$grp->setWidth($pkga['width']);
1149
			}
1150

    
1151
			if ($grouping) {
1152
				$group->add($grp);
1153
			} else {
1154
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1155
					$advanced->addInput($grp);
1156
				} else {
1157
					$section->addInput($grp);
1158
				}
1159
			}
1160

    
1161
			$script = "<script type='text/javascript'>\n";
1162
			$script .= "//<![CDATA[\n";
1163
			$script .= "events.push(function(){\n";
1164
			$script .= "	var aliasarray = new Array({$aliasesaddr})\n";
1165
			$script .= "	$('#' + '{$fieldname}').autocomplete({\n";
1166
			$script .= "		source: aliasarray\n";
1167
			$script .= "	})\n";
1168
			$script .= "});\n";
1169
			$script .= "//]]>\n";
1170
			$script .= "</script>";
1171

    
1172
			echo $script;
1173

    
1174
			break;
1175

    
1176
		case "interfaces_selection":
1177
			$ips = array();
1178
			$interface_regex=(isset($pkga['hideinterfaceregex']) ? $pkga['hideinterfaceregex'] : "nointerfacestohide");
1179
			if (is_array($config['interfaces'])) {
1180
				foreach ($config['interfaces'] as $iface_key=>$iface_value) {
1181
					if (isset($iface_value['enable']) && !preg_match("/$interface_regex/", $iface_key)) {
1182
						$iface_description=($iface_value['descr'] !="" ? strtoupper($iface_value['descr']) : strtoupper($iface_key));
1183
						if (isset($pkga['showips'])) {
1184
							$iface_description .= " address";
1185
						}
1186
						$ips[] = array('ip'=> $iface_key, 'description'=> $iface_description);
1187
					}
1188
				}
1189
			}
1190

    
1191
			if (is_array($config['virtualip']) && isset($pkga['showvirtualips'])) {
1192
				foreach ($config['virtualip']['vip'] as $vip) {
1193
					if (!preg_match("/$interface_regex/", $vip['interface'])) {
1194
						$vip_description=($vip['descr'] !="" ? " ({$vip['descr']}) " : " ");
1195
					}
1196
					switch ($vip['mode']) {
1197
						case "ipalias":
1198
						case "carp":
1199
							$ips[] = array('ip' => $vip['subnet'], 'description' => "{$vip['subnet']} $vip_description");
1200
							break;
1201
						case "proxyarp":
1202
							if ($vip['type'] == "network") {
1203
								$start = ip2long32(gen_subnet($vip['subnet'], $vip['subnet_bits']));
1204
								$end = ip2long32(gen_subnet_max($vip['subnet'], $vip['subnet_bits']));
1205
								$len = $end - $start;
1206
								for ($i = 0; $i <= $len; $i++) {
1207
									$ips[]= array('ip' => long2ip32($start+$i), 'description' => long2ip32($start+$i)." from {$vip['subnet']}/{$vip['subnet_bits']} {$vip_description}");
1208
								}
1209
							} else {
1210
								$ips[]= array('ip' => $vip['subnet'], 'description' => "{$vip['subnet']} $vip_description");
1211
							}
1212
							break;
1213
					}
1214
				}
1215
			}
1216

    
1217
			sort($ips);
1218
			if (isset($pkga['showlistenall'])) {
1219
				array_unshift($ips, array('ip' => gettext('All'), 'description' => gettext('Listen on All interfaces/ip addresses ')));
1220
			}
1221

    
1222
			if (!preg_match("/$interface_regex/", "loopback")) {
1223
				$loopback_text = gettext("loopback");
1224
				$iface_description=(isset($pkga['showips']) ? "127.0.0.1 (" . $loopback_text . ")" : $loopback_text);
1225
				array_push($ips, array('ip' => 'lo0', 'description' => $iface_description));
1226
			}
1227

    
1228
			#show interfaces array on gui
1229
			$size = ($pkga['size'] ? "size=\"{$pkga['size']}\"" : '');
1230
			$multiple = '';
1231
			$fieldname = $pkga['fieldname'];
1232
			if (isset($pkga['multiple'])) {
1233
				$fieldname .= '[]';
1234
				$multiple = 'multiple';
1235
			}
1236

    
1237
			$selectedlist = array();
1238
			$optionlist = array();
1239

    
1240
			if (is_array($value)) {
1241
				$values = $value;
1242
			} else {
1243
				$values = explode(',', $value);
1244
			}
1245

    
1246
			foreach ($ips as $iface) {
1247
				if (in_array($iface['ip'], $values)) {
1248
					array_push($selectedlist, $iface['ip']);
1249
				}
1250

    
1251
				$optionlist[$iface['ip']] = $iface['description'];
1252
			}
1253

    
1254
			if ($grouping) {
1255
				$group->add(new Form_Select(
1256
					$pkga['fieldname'],
1257
					$pkga['fielddescr'],
1258
					isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
1259
					$optionlist,
1260
					isset($pkga['multiple'])
1261
				))->setHelp($pkga['description']);
1262
			} else {
1263
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1264
					$advanced->addInput(new Form_Select(
1265
						$pkga['fieldname'],
1266
						$pkga['fielddescr'],
1267
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
1268
						$optionlist,
1269
						isset($pkga['multiple'])
1270
					))->setHelp($pkga['description']);
1271
				} else {
1272
					$section->addInput(new Form_Select(
1273
						$pkga['fieldname'],
1274
						$pkga['fielddescr'],
1275
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
1276
						$optionlist,
1277
						isset($pkga['multiple'])
1278
					))->setHelp($pkga['description']);
1279
				}
1280
			}
1281

    
1282
			break;
1283

    
1284
		// Create radio button
1285
		case "radio":
1286
			if ($grouping) {
1287
				$group->add(new Form_Checkbox(
1288
					$pkga['fieldname'],
1289
					$pkga['fielddescr'],
1290
					fixup_string($pkga['description']),
1291
					($value == "on"),
1292
					'on'
1293
				))->displayAsRadio();
1294
			} else {
1295
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1296
					$advanced->addInput(new Form_Checkbox(
1297
						$pkga['fieldname'],
1298
						$pkga['fielddescr'],
1299
						fixup_string($pkga['description']),
1300
						($value == "on"),
1301
						'on'
1302
					))->displayAsRadio();
1303
				} else {
1304
					$section->addInput(new Form_Checkbox(
1305
						$pkga['fieldname'],
1306
						$pkga['fielddescr'],
1307
						fixup_string($pkga['description']),
1308
						($value == "on"),
1309
						'on'
1310
					))->displayAsRadio();
1311
				}
1312
			}
1313

    
1314
			break;
1315

    
1316
		// Create form button
1317
		case "button":
1318
			$newbtnicon = "fa-save";
1319
			if ($pkga['buttonicon'] != "") {
1320
				$newbtnicon = $pkga['buttonicon'];
1321
			}
1322
			$newbtnclass = "btn-primary";
1323
			if ($pkga['buttonclass'] != "") {
1324
				$newbtnclass = $pkga['buttonclass'];
1325
			}
1326

    
1327
			$newbtn = new Form_Button(
1328
				$pkga['fieldname'],
1329
				$pkga['fielddescr'],
1330
				null,
1331
				$newbtnicon
1332
			);
1333
			$newbtn->addClass($newbtnclass);
1334

    
1335
			if ($grouping) {
1336
				$group->add(new Form_StaticText(
1337
					null,
1338
					$newbtn . '<br />' . '<div class="help-block">' . fixup_string($pkga['description']) . '</div>'
1339
				));
1340
			} else {
1341
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1342
					$advanced->addInput(new Form_StaticText(
1343
						null,
1344
						$newbtn . '<br />' . '<div class="help-block">' . fixup_string($pkga['description']) . '</div>'
1345
					));
1346
				} else {
1347
					$section->addInput(new Form_StaticText(
1348
						null,
1349
						$newbtn . '<br />' . '<div class="help-block">' . fixup_string($pkga['description']) . '</div>'
1350
					));
1351
				}
1352
			}
1353

    
1354
			break;
1355

    
1356
		case "schedule_selection":
1357

    
1358
			$input = "<select id='{$pkga['fieldname']}' name='{$pkga['fieldname']}'>\n";
1359
			$schedules = array();
1360
			$schedules[] = "none";
1361
			if (is_array($config['schedules']['schedule'])) {
1362
				foreach ($config['schedules']['schedule'] as $schedule) {
1363
					if ($schedule['name'] != "") {
1364
						$schedules[] = $schedule['name'];
1365
					}
1366
				}
1367
			}
1368

    
1369
			foreach ($schedules as $schedule) {
1370
				if ($schedule == "none") {
1371
					$schedlist[""] = $schedule;
1372
				} else {
1373
					$schedlist[$schedule] = $schedule;
1374
				}
1375
			}
1376

    
1377
			if ($grouping) {
1378
				$group->add(new Form_Select(
1379
					$pkga['fieldname'],
1380
					$pkga['fielddescr'],
1381
					$value,
1382
					$schedlist
1383
				))->setHelp(fixup_string($pkga['description']));
1384
			} else {
1385
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1386
					$advanced->addInput(new Form_Select(
1387
						$pkga['fieldname'],
1388
						$pkga['fielddescr'],
1389
						$value,
1390
						$schedlist
1391
					))->setHelp(fixup_string($pkga['description']));
1392
				} else {
1393
					$section->addInput(new Form_Select(
1394
						$pkga['fieldname'],
1395
						$pkga['fielddescr'],
1396
						$value,
1397
						$schedlist
1398
					))->setHelp(fixup_string($pkga['description']));
1399
				}
1400
			}
1401

    
1402
			break;
1403

    
1404
		case "rowhelper":
1405

    
1406
			$rowhelpername="row";
1407

    
1408
				$rowcounter = 0;
1409
				$trc = 0;
1410

    
1411
				//Use assigned $a_pkg or create an empty array to enter loop
1412
				if (isset($a_pkg[$id][$rowhelpername])) {
1413
					$saved_rows=$a_pkg[$id][$rowhelpername];
1414
				} else {
1415
					$saved_rows[] = array();
1416
				}
1417

    
1418
				$numrows = count($saved_rows) - 1;
1419

    
1420
				foreach ($saved_rows as $row) {
1421
					$group = new Form_Group(($rowcounter == 0) ? $pkga['fielddescr']:null);
1422
					$group->addClass('repeatable');
1423

    
1424
					foreach ($pkga['rowhelper']['rowhelperfield'] as $rowhelper) {
1425
						unset($value);
1426
						$width = null;
1427

    
1428
						$fieldname = $rowhelper['fieldname'];
1429
						$fielddescr = $rowhelper['fielddescr'];
1430

    
1431
						// If input validation failed, read the value from the POST data so that the user's input is not lost
1432
						if ($get_from_post && isset($_POST[$fieldname.$rowcounter])) {
1433
							$value = $_POST[$fieldname.$rowcounter];
1434
						} elseif (isset($id) && $a_pkg[$id]) {
1435
							$value = $row[$fieldname];
1436
						} elseif ($rowhelper['value'] != "") {
1437
							$value = $rowhelper['value'];
1438
						}
1439

    
1440
						$type = $rowhelper['type'];
1441
						if ($type == "input" || $type == "password" || $type == "textarea") {
1442
							if (($rowhelper['encoding'] == 'base64') && !$get_from_post && !empty($value)) {
1443
								$value = base64_decode($value);
1444
							}
1445
						}
1446

    
1447

    
1448
						if ($rowhelper['size']) {
1449
							$size = $rowhelper['size'];
1450
						} else if ($pkga['size']) {
1451
							$size = $pkga['size'];
1452
						} else {
1453
							$size = "8";
1454
						}
1455

    
1456
						if ($rowhelper['width']) {
1457
							$width = $rowhelper['width'];
1458
						}
1459

    
1460
						display_row($rowcounter, $value, $fieldname, $type, $rowhelper, ($numrows == $rowcounter) ? $fielddescr:null, $width);
1461

    
1462
						$text = "";
1463
						$trc++;
1464
					}
1465

    
1466
					// Delete row button
1467
					$group->add(new Form_Button(
1468
						'deleterow' . $rowcounter,
1469
						'Delete',
1470
						null,
1471
						'fa-trash'
1472
					))->removeClass('btn-primary')->addClass('btn-warning btn-sm');
1473

    
1474
					$rowcounter++;
1475
					$section->add($group);
1476
				}
1477

    
1478
			// Add row button
1479
			$section->addInput(new Form_Button(
1480
				'addrow',
1481
				'Add',
1482
				null,
1483
				'fa-plus'
1484
			))->addClass('btn-success');
1485

    
1486
			break;
1487

    
1488
	}
1489

    
1490
		if ($pkga['combinefields'] == "end") {
1491
			$group->add(new Form_StaticText(
1492
				null,
1493
				null
1494
			));
1495

    
1496
			if ($advanced) {
1497
				$advanced->add($group);
1498
			} else {
1499
				$section->add($group);
1500
			}
1501

    
1502
			$grouping = false;
1503
		}
1504

    
1505
	#increment counter
1506
	$i++;
1507
} // e-o-foreach field described in the XML
1508

    
1509
if ($section) {
1510
	$form->add($section);
1511
}
1512

    
1513
$form->addGlobal(new Form_Input(
1514
	'id',
1515
	null,
1516
	'hidden',
1517
	$id
1518
));
1519

    
1520
// If we created an advanced section, add it (and a button) to the form here
1521
if (!empty($advanced)) {
1522
	$form->addGlobal(new Form_Button(
1523
		'showadv',
1524
		'Show Advanced Options',
1525
		null,
1526
		'fa-cog'
1527
	))->setAttribute('type','button')->addClass('btn-info');
1528

    
1529
	$form->add($advanced);
1530
}
1531

    
1532
print($form);
1533

    
1534
if ($pkg['note'] != "") {
1535
	print_info_box($pkg['note'], 'info');
1536
}
1537

    
1538
if ($pkg['custom_php_after_form_command']) {
1539
	eval($pkg['custom_php_after_form_command']);
1540
}
1541

    
1542

    
1543
$hidemsg = gettext("Show Advanced Options");
1544
$showmsg = gettext("Hide Advanced Options");
1545

    
1546
if ($pkg['fields']['field'] != "") { ?>
1547
<script type="text/javascript">
1548
//<![CDATA[
1549
	events.push(function() {
1550

    
1551
	// Hide the advanced section
1552
	var advanced_visible = false;
1553

    
1554
	// Hide on page load
1555
	$('.advancedoptions').hide();
1556

    
1557
	// Suppress "Delete row" button if there are fewer than two rows
1558
	checkLastRow();
1559

    
1560
	// Show advanced section if you click the showadv button
1561
	$("#showadv").click(function() {
1562
		advanced_visible = !advanced_visible;
1563

    
1564
		if (advanced_visible) {
1565
			$('.advancedoptions').show();
1566
			$("#showadv").html('<i class="fa fa-cog icon-embed-btn"></i>' + "<?=$showmsg?>");
1567
		} else {
1568
			$('.advancedoptions').hide();
1569
			$("#showadv").html('<i class="fa fa-cog icon-embed-btn"></i>' + "<?=$hidemsg?>");
1570
		}
1571
	});
1572

    
1573
	// Call enablechange function
1574
	enablechange();
1575
});
1576

    
1577
	function enablechange() {
1578
<?php
1579
	foreach ($pkg['fields']['field'] as $field) {
1580
		if (isset($field['enablefields']) or isset($field['checkenablefields'])) {
1581
			echo "\tif ($('input[name=\"{$field['fieldname']}\"]').prop('checked') == false) {\n";
1582

    
1583
			if (isset($field['enablefields'])) {
1584
				foreach (explode(',', $field['enablefields']) as $enablefield) {
1585
					echo "\t\tif ($('input[name=\"{$enablefield}\"]').length > 0) {\n";
1586
					echo "\t\t\t$('input[name=\"{$enablefield}\"]').prop('disabled',true);\n";
1587
					echo "\t\t}\n";
1588
				}
1589
			}
1590

    
1591
			if (isset($field['checkenablefields'])) {
1592
				foreach (explode(',', $field['checkenablefields']) as $checkenablefield) {
1593
					echo "\t\tif ($('input[name=\"{$checkenablefield}\"]').length > 0) {\n";
1594
					echo "\t\t\t$('input[name=\"{$checkenablefield}\"]').prop('checked',true);\n";
1595
					echo "\t\t}\n";
1596
				}
1597
			}
1598

    
1599
			echo "\t}\n\telse {\n";
1600

    
1601
			if (isset($field['enablefields'])) {
1602
				foreach (explode(',', $field['enablefields']) as $enablefield) {
1603
					echo "\t\tif ($('input[name=\"{$enablefield}\"]').length > 0) {\n";
1604
					echo "\t\t\t$('input[name=\"{$enablefield}\"]').prop('disabled',false);\n";
1605
					echo "\t\t}\n";
1606
				}
1607
			}
1608

    
1609
			if (isset($field['checkenablefields'])) {
1610
				foreach (explode(',', $field['checkenablefields']) as $checkenablefield) {
1611
					echo "\t\tif ($('input[name=\"{$checkenablefield}\"]').length > 0) {\n";
1612
					echo "\t\t\t$('input[name=\"{$checkenablefield}\"]').prop('checked',false);\n";
1613
					echo "\t\t}\n";
1614
				}
1615
			}
1616

    
1617
			echo "\t}\n";
1618
		}
1619
	}
1620
	?>
1621
	}
1622
//]]>
1623
</script>
1624

    
1625
<?php
1626
}
1627

    
1628
include("foot.inc");
(95-95/228)