Project

General

Profile

Download (44.7 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	pkg_edit.php
5
*//* ====================================================================
6
 *	Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
7
 *	Copyright (c)  2004, 2005 Scott Ullrich
8
 *
9
 *	Redistribution and use in source and binary forms, with or without modification,
10
 *	are permitted provided that the following conditions are met:
11
 *
12
 *	1. Redistributions of source code must retain the above copyright notice,
13
 *		this list of conditions and the following disclaimer.
14
 *
15
 *	2. Redistributions in binary form must reproduce the above copyright
16
 *		notice, this list of conditions and the following disclaimer in
17
 *		the documentation and/or other materials provided with the
18
 *		distribution.
19
 *
20
 *	3. All advertising materials mentioning features or use of this software
21
 *		must display the following acknowledgment:
22
 *		"This product includes software developed by the pfSense Project
23
 *		 for use in the pfSense software distribution. (http://www.pfsense.org/).
24
 *
25
 *	4. The names "pfSense" and "pfSense Project" must not be used to
26
 *		 endorse or promote products derived from this software without
27
 *		 prior written permission. For written permission, please contact
28
 *		 coreteam@pfsense.org.
29
 *
30
 *	5. Products derived from this software may not be called "pfSense"
31
 *		nor may "pfSense" appear in their names without prior written
32
 *		permission of the Electric Sheep Fencing, LLC.
33
 *
34
 *	6. Redistributions of any form whatsoever must retain the following
35
 *		acknowledgment:
36
 *
37
 *	"This product includes software developed by the pfSense Project
38
 *	for use in the pfSense software distribution (http://www.pfsense.org/).
39
 *
40
 *	THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
41
 *	EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
 *	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43
 *	PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
44
 *	ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45
 *	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46
 *	NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47
 *	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48
 *	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49
 *	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50
 *	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51
 *	OF THE POSSIBILITY OF SUCH DAMAGE.
52
 *
53
 *	====================================================================
54
 *
55
 */
56
/*
57
	pfSense_BUILDER_BINARIES:	/sbin/ifconfig
58
	pfSense_MODULE: pkgs
59
*/
60

    
61
##|+PRIV
62
##|*IDENT=page-package-edit
63
##|*NAME=Package: Edit page
64
##|*DESCR=Allow access to the 'Package: Edit' page.
65
##|*MATCH=pkg_edit.php*
66
##|-PRIV
67

    
68
ini_set('max_execution_time', '0');
69

    
70
require("guiconfig.inc");
71
require_once("functions.inc");
72
require_once("filter.inc");
73
require_once("shaper.inc");
74
require_once("pkg-utils.inc");
75

    
76
/* dummy stubs needed by some code that was MFC'd */
77
function pfSenseHeader($location) {
78
	header("Location: " . $location);
79
}
80

    
81
$xml = htmlspecialchars($_GET['xml']);
82
if ($_POST['xml']) {
83
	$xml = htmlspecialchars($_POST['xml']);
84
}
85

    
86
$xml_fullpath = realpath('/usr/local/pkg/' . $xml);
87

    
88
if ($xml == "" || $xml_fullpath === false || substr($xml_fullpath, 0, strlen('/usr/local/pkg/')) != '/usr/local/pkg/') {
89
	include("head.inc");
90
	print_info_box_np(gettext("ERROR: No valid package defined."));
91
	include("foot.inc");
92
	die;
93
} else {
94
	$pkg = parse_xml_config_pkg($xml_fullpath, "packagegui");
95
}
96

    
97
if ($pkg['include_file'] != "") {
98
	require_once($pkg['include_file']);
99
}
100

    
101
if (!isset($pkg['adddeleteeditpagefields'])) {
102
	$only_edit = true;
103
} else {
104
	$only_edit = false;
105
}
106

    
107
$id = $_GET['id'];
108
if (isset($_POST['id'])) {
109
	$id = htmlspecialchars($_POST['id']);
110
}
111

    
112
// Not posting?	 Then user is editing a record. There must be a valid id
113
// when editing a record.
114
if (!$id && !$_POST) {
115
	$id = "0";
116
}
117

    
118
if (!is_numeric($id)) {
119
	header("Location: /");
120
	exit;
121
}
122

    
123
if ($pkg['custom_php_global_functions'] != "") {
124
	eval($pkg['custom_php_global_functions']);
125
}
126

    
127
// grab the installedpackages->package_name section.
128
if ($config['installedpackages'] && !is_array($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'])) {
129
	$config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'] = array();
130
}
131

    
132
// If the first entry in the array is an empty <config/> tag, kill it.
133
if ($config['installedpackages'] && (count($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config']) > 0)
134
	&& ($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'][0] == "")) {
135
	array_shift($config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config']);
136
}
137

    
138
$a_pkg = &$config['installedpackages'][xml_safe_fieldname($pkg['name'])]['config'];
139

    
140
if ($_GET['savemsg'] != "") {
141
	$savemsg = htmlspecialchars($_GET['savemsg']);
142
}
143

    
144
if ($pkg['custom_php_command_before_form'] != "") {
145
	eval($pkg['custom_php_command_before_form']);
146
}
147

    
148
if ($_POST) {
149
	$rows = 0;
150

    
151
	$input_errors = array();
152
	$reqfields = array();
153
	$reqfieldsn = array();
154
	foreach ($pkg['fields']['field'] as $field) {
155
		if (($field['type'] == 'input') && isset($field['required'])) {
156
			if ($field['fieldname']) {
157
				$reqfields[] = $field['fieldname'];
158
			}
159
			if ($field['fielddescr']) {
160
				$reqfieldsn[] = $field['fielddescr'];
161
			}
162
		}
163
	}
164
	do_input_validation($_POST, $reqfields, $reqfieldsn, $input_errors);
165

    
166
	if ($pkg['custom_php_validation_command']) {
167
		eval($pkg['custom_php_validation_command']);
168
	}
169

    
170
	if ($_POST['act'] == "del") {
171
		if ($pkg['custom_delete_php_command']) {
172
			if ($pkg['custom_php_command_before_form'] != "") {
173
				eval($pkg['custom_php_command_before_form']);
174
			}
175
			eval($pkg['custom_delete_php_command']);
176
		}
177
		write_config($pkg['delete_string']);
178
		// resync the configuration file code if defined.
179
		if ($pkg['custom_php_resync_config_command'] != "") {
180
			if ($pkg['custom_php_command_before_form'] != "") {
181
				eval($pkg['custom_php_command_before_form']);
182
			}
183
			eval($pkg['custom_php_resync_config_command']);
184
		}
185
	} else {
186
		if (!$input_errors && $pkg['custom_add_php_command']) {
187
			if ($pkg['donotsave'] != "" or $pkg['preoutput'] != "") {
188
				include("head.inc");
189
			}
190

    
191
			if ($pkg['preoutput']) {
192
				echo "<pre>";
193
			}
194
			eval($pkg['custom_add_php_command']);
195
			if ($pkg['preoutput']) {
196
				echo "</pre>";
197
			}
198
		}
199
	}
200

    
201
	// donotsave is enabled.  lets simply exit.
202
	if (empty($pkg['donotsave'])) {
203

    
204
		// store values in xml configuration file.
205
		if (!$input_errors) {
206
			$pkgarr = array();
207
			foreach ($pkg['fields']['field'] as $fields) {
208
				switch ($fields['type']) {
209
					case "rowhelper":
210
						// save rowhelper items.
211
						#$rowhelpername=($fields['fieldname'] ? $fields['fieldname'] : "row");
212
						$rowhelpername="row";
213
						foreach ($fields['rowhelper']['rowhelperfield'] as $rowhelperfield) {
214
							foreach ($_POST as $key => $value) {
215
								$matches = array();
216
								if (preg_match("/^{$rowhelperfield['fieldname']}(\d+)$/", $key, $matches)) {
217
									$pkgarr[$rowhelpername][$matches[1]][$rowhelperfield['fieldname']] = $value;
218
								}
219
							}
220
						}
221
						break;
222
					default:
223
						$fieldname = $fields['fieldname'];
224
						if ($fieldname == "interface_array") {
225
							$fieldvalue = $_POST[$fieldname];
226
						} elseif (is_array($_POST[$fieldname])) {
227
							$fieldvalue = implode(',', $_POST[$fieldname]);
228
						} else {
229
							$fieldvalue = trim($_POST[$fieldname]);
230
							if ($fields['encoding'] == 'base64') {
231
								$fieldvalue = base64_encode($fieldvalue);
232
							}
233
						}
234
						if ($fieldname) {
235
							$pkgarr[$fieldname] = $fieldvalue;
236
						}
237
					}
238
			}
239

    
240
			if (isset($id) && $a_pkg[$id]) {
241
				$a_pkg[$id] = $pkgarr;
242
			} else {
243
				$a_pkg[] = $pkgarr;
244
			}
245

    
246
			write_config($pkg['addedit_string']);
247
			// late running code
248
			if ($pkg['custom_add_php_command_late'] != "") {
249
				eval($pkg['custom_add_php_command_late']);
250
			}
251

    
252
			if (isset($pkg['filter_rules_needed'])) {
253
				filter_configure();
254
			}
255

    
256
			// resync the configuration file code if defined.
257
			if ($pkg['custom_php_resync_config_command'] != "") {
258
				eval($pkg['custom_php_resync_config_command']);
259
			}
260

    
261
			parse_package_templates();
262

    
263
			/* if start_command is defined, restart w/ this */
264
			if ($pkg['start_command'] != "") {
265
				exec($pkg['start_command'] . ">/dev/null 2&>1");
266
			}
267

    
268
			/* if restart_command is defined, restart w/ this */
269
			if ($pkg['restart_command'] != "") {
270
				exec($pkg['restart_command'] . ">/dev/null 2&>1");
271
			}
272

    
273
			if ($pkg['aftersaveredirect'] != "") {
274
				pfSenseHeader($pkg['aftersaveredirect']);
275
			} elseif (!$pkg['adddeleteeditpagefields']) {
276
				pfSenseHeader("pkg_edit.php?xml={$xml}&amp;id=0");
277
			} elseif (!$pkg['preoutput']) {
278
				pfSenseHeader("pkg.php?xml=" . $xml);
279
			}
280
			exit;
281
		} else {
282
			$get_from_post = true;
283
		}
284
	} elseif (!$input_errors) {
285
		exit;
286
	}
287
}
288

    
289
if ($pkg['title'] != "") {
290
	$edit = ($only_edit ? '' : ": " . gettext("Edit"));
291
	$pgtitle = $pkg['title'] . $edit;
292
} else {
293
	$pgtitle = gettext("Package Editor");
294
}
295

    
296
if ($pkg['custom_php_after_head_command']) {
297
	$closehead = false;
298
	include("head.inc");
299
	eval($pkg['custom_php_after_head_command']);
300
} else {
301
	include("head.inc");
302
}
303

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

    
310
	// Substitute everything inbetween with our new classes
311
	if($t && $c && (($c - $t) < 200) ) {
312
		return(substr_replace($text, ' class="table table-striped table-hover table-condensed"', $t, ($c - $t)));
313
	}
314
}
315

    
316
/*
317
 * ROW helper function. Creates one element in the row from a PHP table by adding
318
 * the specified element to $group
319
 */
320
function display_row($trc, $value, $fieldname, $type, $rowhelper, $description) {
321
	global $text, $group;
322

    
323
	switch ($type) {
324
		case "input":
325
			$group->add(new Form_Input(
326
				$fieldname . $trc,
327
				null,
328
				'text',
329
				$value
330
			))->setHelp($description);
331

    
332
			break;
333
		case "checkbox":
334
			$group->add(new Form_Checkbox(
335
				$fieldname . $trc,
336
				null,
337
				null,
338
				$value,
339
				'ON'
340
			))->setHelp($description);
341

    
342
			break;
343
		case "password":
344
			$group->add(new Form_Input(
345
				$fieldname . $trc,
346
				null,
347
				'password',
348
				$value
349
			))->setHelp($description);
350
			break;
351
		case "textarea":
352
			$group->add(new Form_TextArea(
353
				$fieldname . $trc,
354
				null,
355
				$value
356
			))->setHelp($description);
357

    
358
			break;
359
		case "select":
360
			$options = array();
361
			foreach ($rowhelper['options']['option'] as $rowopt) {
362
				$options[$rowopt['value']] = $rowopt['name'];
363
			}
364

    
365
			$group->add(new Form_Select(
366
				$fieldname . $trc,
367
				null,
368
				$value,
369
				$options
370
			))->setHelp($description);
371

    
372
			break;
373
		case "interfaces_selection":
374
			$size = ($size ? "size=\"{$size}\"" : '');
375
			$multiple = '';
376
			if (isset($rowhelper['multiple'])) {
377
				$multiple = "multiple=\"multiple\"";
378
			}
379
			echo "<select style='height:22px;' id='{$fieldname}{$trc}' name='{$fieldname}{$trc}' {$size} {$multiple}>\n";
380
			$ifaces = get_configured_interface_with_descr();
381
			$additional_ifaces = $rowhelper['add_to_interfaces_selection'];
382
			if (!empty($additional_ifaces)) {
383
				$ifaces = array_merge($ifaces, explode(',', $additional_ifaces));
384
			}
385

    
386
			if (is_array($value)) {
387
				$values = $value;
388
			} else {
389
				$values = explode(',', $value);
390
			}
391

    
392
			$ifaces["lo0"] = "loopback";
393
			$options = array();
394
			$selected = array();
395

    
396
			foreach ($ifaces as $ifname => $iface) {
397
				$options[$ifname] = $iface;
398

    
399
				if(in_array($ifname, $values)) {
400
					array_push($selected, $ifname);
401
				}
402
			}
403

    
404
			$group->add(new Form_Select(
405
				$fieldname . $trc,
406
				null,
407
				($multiple) ? $selected:$selected[0],
408
				$options,
409
				$multiple
410
			))->setHelp($description);
411

    
412
			//echo "</select>\n";
413
			break;
414
		case "select_source":
415
			$options = array();
416
			$selected = array();
417

    
418
			if (isset($rowhelper['show_disable_value'])) {
419
				$options[$rowhelper['show_disable_value']] = $rowhelper['show_disable_value'];
420
			}
421

    
422
			$source_url = $rowhelper['source'];
423
			eval("\$pkg_source_txt = &$source_url;");
424

    
425
			foreach ($pkg_source_txt as $opt) {
426
				$source_name = ($rowhelper['source_name'] ? $opt[$rowhelper['source_name']] : $opt[$rowhelper['name']]);
427
				$source_value = ($rowhelper['source_value'] ? $opt[$rowhelper['source_value']] : $opt[$rowhelper['value']]);
428
				$options[$source_value] = $source_name;
429

    
430
				if($source_value == $value) {
431
					array_push($selected, $value);
432
				}
433
			}
434

    
435
			$group->add(new Form_Select(
436
				$fieldname . $trc,
437
				null,
438
				($multiple) ? $selected:$selected[0],
439
				$options,
440
				$multiple
441
			))->setHelp($description);
442

    
443
			break;
444
	}
445
}
446

    
447
function fixup_string($string) {
448
	global $config;
449
	// fixup #1: $myurl -> http[s]://ip_address:port/
450
	$https = "";
451
	$port = $config['system']['webguiport'];
452
	if ($port != "443" and $port != "80") {
453
		$urlport = ":" . $port;
454
	} else {
455
		$urlport = "";
456
	}
457

    
458
	if ($config['system']['webgui']['protocol'] == "https") {
459
		$https = "s";
460
	}
461
	$myurl = "http" . $https . "://" . getenv("HTTP_HOST") . $urlport;
462
	$newstring = str_replace("\$myurl", $myurl, $string);
463
	$string = $newstring;
464
	// fixup #2: $wanip
465
	$curwanip = get_interface_ip();
466
	$newstring = str_replace("\$wanip", $curwanip, $string);
467
	$string = $newstring;
468
	// fixup #3: $lanip
469
	$lancfg = $config['interfaces']['lan'];
470
	$lanip = $lancfg['ipaddr'];
471
	$newstring = str_replace("\$lanip", $lanip, $string);
472
	$string = $newstring;
473
	// fixup #4: fix'r'up here.
474
	return $newstring;
475
}
476

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

    
522
			/* replace cr's */
523
			$template_text = str_replace("\\n", "\n", $template_text);
524

    
525
			/* write out new template file */
526
			$fout = fopen($filename, "w");
527
			fwrite($fout, $template_text);
528
			fclose($fout);
529
		}
530
	}
531
}
532

    
533
// Start of page display
534
require_once('classes/Form.class.php');
535

    
536
if ($input_errors)
537
	print_input_errors($input_errors);
538

    
539
if ($savemsg)
540
	print_info_box($savemsg, 'success');
541

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

    
552
		if (isset($tab['active'])) {
553
			$active = true;
554
		} else {
555
			$active = false;
556
		}
557

    
558
		if (isset($tab['no_drop_down'])) {
559
			$no_drop_down = true;
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
	foreach ($tab_array as $tabid => $tab) {
594
		display_top_tabs($tab); //, $no_drop_down, $tabid);
595
	}
596
}
597

    
598
$cols = 0;
599
$savevalue = gettext("Save");
600
if ($pkg['savetext'] != "") {
601
	$savevalue = $pkg['savetext'];
602
}
603

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

    
606
$form = new Form(new Form_Button(
607
	'submit',
608
	$savevalue
609
));
610

    
611
$form->addGlobal(new Form_Input(
612
	'xml',
613
	null,
614
	'hidden',
615
	$xml
616
));
617

    
618
/* If a package's XML has <advanced_options/> configured, then setup
619
 * ta section for the fields that have <advancedfield/> set.
620
 * These fields will be placed below other fields in a separate area titled 'Advanced Features'.
621
 * These advanced fields are not normally configured and generally left to default to 'default settings'.
622
 */
623

    
624
if ($pkg['advanced_options'] == "enabled") {
625
	$advfield_count = 0;
626
	$advanced = new Form_Section(gettext("Advanced features"));
627
	$advanced->addClass('advancedoptions');
628
}
629

    
630
$js_array = array();
631

    
632
// Now loop through all of hte fields defined in the XML
633
foreach ($pkg['fields']['field'] as $pkga) {
634

    
635
	if ($pkga['type'] == "sorting") {
636
		continue;
637
	}
638

    
639
	// Generate a new section
640
	if ($pkga['type'] == "listtopic") {
641
		if (isset($pkga['advancedfield']) && isset($advfield_count)) {
642
			$advanced->addInput(new Form_StaticText(
643
				strip_tags($pkga['name']),
644
				null
645
			));
646

    
647
			$advfield_count++;
648
		}  else {
649
			if(isset($section))
650
				$form->add($section);
651

    
652
			$section = new Form_Section(strip_tags($pkga['name']));
653
		}
654

    
655
		continue;
656
	}
657

    
658
	// 'begin' starts a form group. ('end' ends it)
659
	if ($pkga['combinefields'] == "begin") {
660
		$group = new Form_Group(strip_tags($pkga['fielddescr']));
661
		$grouping = true;
662
	}
663

    
664
	$size = "";
665
	$colspan="";
666

    
667
	// if user is editing a record, load in the data.
668
	$fieldname = $pkga['fieldname'];
669
	unset($value);
670
	if ($get_from_post) {
671
		$value = $_POST[$fieldname];
672
		if (is_array($value)) {
673
			$value = implode(',', $value);
674
		}
675
	} else {
676
		if (isset($id) && isset($a_pkg[$id][$fieldname])) {
677
			$value = $a_pkg[$id][$fieldname];
678
		} else {
679
			if (isset($pkga['default_value'])) {
680
				$value = $pkga['default_value'];
681
			}
682
		}
683
	}
684

    
685
	switch ($pkga['type']) {
686
		// Creat an input element. The format is slightly different depending on whether we are composing a group,
687
		// section, or advanced section. This is true for every element type
688
		case "input":
689
			if($grouping) {
690
				$group->add(new Form_Input(
691
					$pkga['fieldname'],
692
					$pkga['fielddescr'],
693
					'text',
694
					$value
695
				))->setHelp($pkga['description']);
696
			} else {
697
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
698
					$advanced->addInput(new Form_Input(
699
						$pkga['fieldname'],
700
						$pkga['fielddescr'],
701
						'text',
702
						$value
703
					))->setHelp($pkga['description']);
704
				} else {
705
					$section->addInput(new Form_Input(
706
						$pkga['fieldname'],
707
						$pkga['fielddescr'],
708
						'text',
709
						$value
710
					))->setHelp($pkga['description']);
711
				}
712
			}
713

    
714
			break;
715

    
716
		case "password":
717
		// Creat a password element
718
			if($grouping) {
719
				$group->add(new Form_Input(
720
					$pkga['fieldname'],
721
					$pkga['fielddescr'],
722
					'password',
723
					$value
724
				))->setHelp($pkga['description']);
725
			} else {
726
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
727
					$advanced->addInput(new Form_Input(
728
						$pkga['fieldname'],
729
						$pkga['fielddescr'],
730
						'password',
731
						$value
732
					))->setHelp($pkga['description']);
733
				} else {
734
					$section->addInput(new Form_Input(
735
						$pkga['fieldname'],
736
						$pkga['fielddescr'],
737
						'password',
738
						$value
739
					))->setHelp($pkga['description']);
740
				}
741
			}
742

    
743
			break;
744

    
745
		case "info":
746
			// If the info containe a table we should detect and Bootstrap it
747

    
748
			if (strpos($pkga['description'], '<table') !== FALSE)
749
				$info = bootstrapTable($pkga['description']);
750
			else
751
				$info = $pkga['description'];
752

    
753
			if (isset($pkga['advancedfield']) && isset($advfield_count)) {
754
				$advanced->addInput(new Form_StaticText(
755
					strip_tags($pkga['fielddescr']),
756
					$info
757
				));
758
			} else {
759
				$section->addInput(new Form_StaticText(
760
					strip_tags($pkga['fielddescr']),
761
					$info
762
				));
763
			}
764

    
765
			break;
766

    
767
		case "select":
768
			// Create a select element
769
			$optionlist = array();
770
			$selectedlist = array();
771

    
772
			$fieldname = $pkga['fieldname'];
773

    
774
			if (isset($pkga['multiple'])) {
775
				$multiple = 'multiple="multiple"';
776
				$items = explode(',', $value);
777
				$fieldname .= "[]";
778
			} else {
779
				$multiple = '';
780
				$items = array($value);
781
			}
782

    
783
			$onchange = (isset($pkga['onchange']) ? "onchange=\"{$pkga['onchange']}\"" : '');
784

    
785
			foreach ($pkga['options']['option'] as $opt) {
786
				$optionlist[$opt['value']] = $opt['name'];
787

    
788
				if (in_array($opt['value'], $items)) {
789
					array_push($selectedlist, $opt['value']);
790
				}
791
			}
792

    
793
			if (isset($pkga['advancedfield']) && isset($advfield_count))
794
				$function = $grouping ? $advanced->add:$advanced->addInput;
795
			else
796
				$function = ($grouping) ? $section->add:$section->addInput;
797

    
798
			if($grouping) {
799
					$group->add(new Form_Select(
800
						$pkga['fieldname'],
801
						strip_tags($pkga['fielddescr']),
802
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
803
						$optionlist,
804
						isset($pkga['multiple'])
805
					))->setHelp($pkga['description'])->setOnchange($onchange)->setAttribute('size', $pkga['size']);
806
			} else {
807
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
808
					$advanced->addInput(new Form_Select(
809
						$pkga['fieldname'],
810
						$pkga['fielddescr'],
811
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
812
						$optionlist,
813
						isset($pkga['multiple'])
814
					))->setHelp($pkga['description'])->setOnchange($onchange)->setAttribute('size', $pkga['size']);
815
				} else {
816
					$section->addInput(new Form_Select(
817
						$pkga['fieldname'],
818
						strip_tags($pkga['fielddescr']),
819
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
820
						$optionlist,
821
						isset($pkga['multiple'])
822
					))->setHelp($pkga['description'])->setOnchange($onchange)->setAttribute('size', $pkga['size']);
823
				}
824
			}
825

    
826
			break;
827

    
828
		case "select_source":
829

    
830
			if (isset($pkga['multiple'])) {
831
				$items = explode(',', $value);
832
				$fieldname .= "[]";
833
			} else {
834
				$items = array($value);
835
			}
836

    
837
			$onchange = (isset($pkga['onchange']) ? "onchange=\"{$pkga['onchange']}\"" : '');
838

    
839
			$source_url = $pkga['source'];
840
			eval("\$pkg_source_txt = &$source_url;");
841

    
842
			#check if show disable option is present on xml
843
			if (isset($pkga['show_disable_value'])) {
844
				array_push($pkg_source_txt,
845
					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']));
846
			}
847

    
848
			$srcoptions = array();
849
			$srcselected = array();
850

    
851
			foreach ($pkg_source_txt as $opt) {
852
				$source_name =($pkga['source_name']? $opt[$pkga['source_name']] : $opt[$pkga['name']]);
853
				$source_value =($pkga['source_value'] ? $opt[$pkga['source_value']] : $opt[$pkga['value']]);
854
				$srcoptions[$source_value] = $source_name;
855

    
856
				if(in_array($source_value, $items))
857
					array_push($srcselected, $source_value);
858
			}
859

    
860
			if($grouping) {
861
				$group->add(new Form_Select(
862
					$pkga['fieldname'],
863
					$pkga['name'],
864
					isset($pkga['multiple']) ? $srcselected:$srcselected[0],
865
					$srcoptions,
866
					isset($pkga['multiple'])
867
				))->setOnchange($onchange);
868
			} else {
869
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
870
					$advanced->addInput(new Form_Select(
871
						$pkga['fieldname'],
872
						$pkga['name'],
873
						isset($pkga['multiple']) ? $srcselected:$srcselected[0],
874
						$srcoptions,
875
						isset($pkga['multiple'])
876
					))->setOnchange($onchange);
877
				} else {
878
					$section->addInput(new Form_Select(
879
						$pkga['fieldname'],
880
						$pkga['name'],
881
						isset($pkga['multiple']) ? $srcselected:$srcselected[0],
882
						$srcoptions,
883
						isset($pkga['multiple'])
884
					))->setOnchange($onchange);
885
				}
886
			}
887

    
888
			break;
889

    
890
		case "vpn_selection" :
891
			$vpnlist = array();
892

    
893
			foreach ($config['ipsec']['phase1'] as $vpn) {
894
				$vpnlist[$vpn['descr']] = $vpn['descr'];
895

    
896
			}
897

    
898
			if($grouping) {
899
				$group->add(new Form_Select(
900
					$pkga['fieldname'],
901
					null,
902
					false,
903
					$vpnlist
904
				))->setHelp(fixup_string($pkga['description']));
905
			} else {
906
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
907
					$advanced->addInput(new Form_Select(
908
						$pkga['fieldname'],
909
						null,
910
						false,
911
						$vpnlist
912
					))->setHelp(fixup_string($pkga['description']));
913
				} else {
914
					$section->addInput(new Form_Select(
915
						$pkga['fieldname'],
916
						null,
917
						false,
918
						$vpnlist
919
					))->setHelp(fixup_string($pkga['description']));
920
				}
921
			}
922

    
923
			break;
924

    
925
		// Create a checkbox element
926
		case "checkbox":
927
			$onchange = (isset($pkga['onchange']) ? "{$pkga['onchange']}" : '');
928
			if (isset($pkga['enablefields']) || isset($pkga['checkenablefields']))
929
				$onclick = 'javascript:enablechange();';
930
			else
931
				$onclick = '';
932

    
933
			if($grouping) {
934
				$group->add(new Form_Checkbox(
935
					$pkga['fieldname'],
936
					$pkga['fielddescr'],
937
					'Show log entries in reverse order (newest entries on top)',
938
					($value == "on"),
939
					'on'
940
				))->setHelp(fixup_string($pkga['description']))
941
				  ->setOnclick($onclick)
942
				  ->setOnchange($onchange);
943
			} else {
944
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
945
					$advanced->addInput(new Form_Checkbox(
946
						$pkga['fieldname'],
947
						$pkga['fielddescr'],
948
						'Show log entries in reverse order (newest entries on top)',
949
						($value == "on"),
950
						'on'
951
					))->setHelp(fixup_string($pkga['description']))
952
					  ->setOnclick($onclick)
953
					  ->setOnchange($onchange);
954
				} else {
955
					$section->addInput(new Form_Checkbox(
956
						$pkga['fieldname'],
957
						$pkga['fielddescr'],
958
						'Show log entries in reverse order (newest entries on top)',
959
						($value == "on"),
960
						'on'
961
					))->setHelp(fixup_string($pkga['description']))
962
					  ->setOnclick($onclick)
963
					  ->setOnchange($onchange);
964
				}
965
			}
966

    
967
			break;
968

    
969
		// Creat textarea element
970
		case "textarea":
971
			if ($pkga['rows']) {
972
				$rows = " rows='{$pkga['rows']}' ";
973
			}
974
			if ($pkga['cols']) {
975
				$cols = " cols='{$pkga['cols']}' ";
976
			}
977
			if (($pkga['encoding'] == 'base64') && !$get_from_post && !empty($value)) {
978
				$value = base64_decode($value);
979
			}
980

    
981
			$wrap =($pkga['wrap'] == "off" ? 'wrap="off" style="white-space:nowrap;"' : '');
982

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

    
1005
			break;
1006

    
1007
		case "aliases":
1008

    
1009
			// Use xml tag <typealiases> to filter type aliases
1010
			$size = ($pkga['size'] ? "size=\"{$pkga['size']}\"" : '');
1011
			$fieldname = $pkga['fieldname'];
1012
			$a_aliases = &$config['aliases']['alias'];
1013
			$addrisfirst = 0;
1014
			$aliasesaddr = "";
1015
			$value = "value='{$value}'";
1016

    
1017
			if (isset($a_aliases)) {
1018
				if (!empty($pkga['typealiases'])) {
1019
					foreach ($a_aliases as $alias) {
1020
						if ($alias['type'] == $pkga['typealiases']) {
1021
							if ($addrisfirst == 1) {
1022
								$aliasesaddr .= ",";
1023
							}
1024
							$aliasesaddr .= "'" . $alias['name'] . "'";
1025
							$addrisfirst = 1;
1026
						}
1027
					}
1028
				} else {
1029
					foreach ($a_aliases as $alias) {
1030
						if ($addrisfirst == 1) {
1031
							$aliasesaddr .= ",";
1032
						}
1033
						$aliasesaddr .= "'" . $alias['name'] . "'";
1034
						$addrisfirst = 1;
1035
					}
1036
				}
1037
			}
1038

    
1039
			if(grouping) {
1040
				$group->add(new Form_Input(
1041
					$pkga['fieldname'],
1042
					$pkga['fielddescr'],
1043
					'text',
1044
					$value
1045
				))->setHelp($pkga['description']);
1046
			} else {
1047
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1048
					$advanced->addInput(new Form_Input(
1049
						$pkga['fieldname'],
1050
						$pkga['fielddescr'],
1051
						'text',
1052
						$value
1053
					))->setHelp($pkga['description']);
1054
				} else {
1055
					$section->addInput(new Form_Input(
1056
						$pkga['fieldname'],
1057
						$pkga['fielddescr'],
1058
						'text',
1059
						$value
1060
					))->setHelp($pkga['description']);
1061
				}
1062
			}
1063

    
1064
			$script = "<script type='text/javascript'>\n";
1065
			$script .= "//<![CDATA[\n";
1066
			$script .= "events.push(function(){\n";
1067
			$script .= "	var aliasarray = new Array({$aliasesaddr})\n";
1068
			$script .= "	$('#' + '{$fieldname}').autocomplete({\n";
1069
			$script .= "		source: aliasarray\n";
1070
			$script .= "	})\n";
1071
			$script .= "});\n";
1072
			$script .= "//]]>\n";
1073
			$script .= "</script>";
1074

    
1075
			echo $script;
1076

    
1077
			break;
1078

    
1079
		case "interfaces_selection":
1080
			$ips = array();
1081
			$interface_regex=(isset($pkga['hideinterfaceregex']) ? $pkga['hideinterfaceregex'] : "nointerfacestohide");
1082
			if (is_array($config['interfaces'])) {
1083
				foreach ($config['interfaces'] as $iface_key=>$iface_value) {
1084
					if (isset($iface_value['enable']) && !preg_match("/$interface_regex/", $iface_key)) {
1085
						$iface_description=($iface_value['descr'] !="" ? strtoupper($iface_value['descr']) : strtoupper($iface_key));
1086
						if (isset($pkga['showips'])) {
1087
							$iface_description .= " address";
1088
						}
1089
						$ips[] = array('ip'=> $iface_key, 'description'=> $iface_description);
1090
					}
1091
				}
1092
			}
1093

    
1094
			if (is_array($config['virtualip']) && isset($pkga['showvirtualips'])) {
1095
				foreach ($config['virtualip']['vip'] as $vip) {
1096
					if (!preg_match("/$interface_regex/", $vip['interface'])) {
1097
						$vip_description=($vip['descr'] !="" ? " ({$vip['descr']}) " : " ");
1098
					}
1099
					switch ($vip['mode']) {
1100
						case "ipalias":
1101
						case "carp":
1102
							$ips[] = array('ip' => $vip['subnet'], 'description' => "{$vip['subnet']} $vip_description");
1103
							break;
1104
						case "proxyarp":
1105
							if ($vip['type'] == "network") {
1106
								$start = ip2long32(gen_subnet($vip['subnet'], $vip['subnet_bits']));
1107
								$end = ip2long32(gen_subnet_max($vip['subnet'], $vip['subnet_bits']));
1108
								$len = $end - $start;
1109
								for ($i = 0; $i <= $len; $i++) {
1110
									$ips[]= array('ip' => long2ip32($start+$i), 'description' => long2ip32($start+$i)." from {$vip['subnet']}/{$vip['subnet_bits']} {$vip_description}");
1111
								}
1112
							} else {
1113
								$ips[]= array('ip' => $vip['subnet'], 'description' => "{$vip['subnet']} $vip_description");
1114
							}
1115
							break;
1116
					}
1117
				}
1118
			}
1119

    
1120
			sort($ips);
1121
			if (isset($pkga['showlistenall'])) {
1122
				array_unshift($ips, array('ip' => 'All', 'description' => 'Listen on All interfaces/ip addresses '));
1123
			}
1124

    
1125
			if (!preg_match("/$interface_regex/", "loopback")) {
1126
				$iface_description=(isset($pkga['showips']) ? "127.0.0.1 (loopback)" : "loopback");
1127
				array_push($ips, array('ip' => 'lo0', 'description' => $iface_description));
1128
			}
1129

    
1130
			#show interfaces array on gui
1131
			$size = ($pkga['size'] ? "size=\"{$pkga['size']}\"" : '');
1132
			$multiple = '';
1133
			$fieldname = $pkga['fieldname'];
1134
			if (isset($pkga['multiple'])) {
1135
				$fieldname .= '[]';
1136
				$multiple = 'multiple="multiple"';
1137
			}
1138

    
1139
			$selectedlist = array();
1140
			$optionlist = array();
1141

    
1142
			if (is_array($value)) {
1143
				$values = $value;
1144
			} else {
1145
				$values = explode(',', $value);
1146
			}
1147

    
1148
			foreach ($ips as $iface) {
1149
				if (in_array($iface['ip'], $values)) {
1150
					array_push($selectedlist, $iface['ip']);
1151
				}
1152

    
1153
				$optionlist[$iface['ip']] = $iface['description'];
1154
			}
1155

    
1156
			if($grouping) {
1157
				$group->add(new Form_Select(
1158
					$pkga['fieldname'],
1159
					$pkga['fielddescr'],
1160
					isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
1161
					$optionlist,
1162
					isset($pkga['multiple'])
1163
				))->setHelp($pkga['description']);
1164
			} else {
1165
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1166
					$advanced->addInput(new Form_Select(
1167
						$pkga['fieldname'],
1168
						$pkga['fielddescr'],
1169
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
1170
						$optionlist,
1171
						isset($pkga['multiple'])
1172
					))->setHelp($pkga['description']);
1173
				} else {
1174
					$section->addInput(new Form_Select(
1175
						$pkga['fieldname'],
1176
						$pkga['fielddescr'],
1177
						isset($pkga['multiple']) ? $selectedlist:$selectedlist[0],
1178
						$optionlist,
1179
						isset($pkga['multiple'])
1180
					))->setHelp($pkga['description']);
1181
				}
1182
			}
1183

    
1184
			break;
1185

    
1186
		// Create radio button
1187
		case "radio":
1188
			if($grouping) {
1189
				$group->add(new Form_Checkbox(
1190
					$pkga['fieldname'],
1191
					$pkga['fielddescr'],
1192
					'Show log entries in reverse order (newest entries on top)',
1193
					($value == "on"),
1194
					'on'
1195
				))->setHelp(fixup_string($pkga['description']))->displayAsRadio();
1196
			} else {
1197
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1198
					$advanced->addInput(new Form_Checkbox(
1199
						$pkga['fieldname'],
1200
						$pkga['fielddescr'],
1201
						'Show log entries in reverse order (newest entries on top)',
1202
						($value == "on"),
1203
						'on'
1204
					))->setHelp(fixup_string($pkga['description']))->displayAsRadio();
1205
				} else {
1206
					$section->addInput(new Form_Checkbox(
1207
						$pkga['fieldname'],
1208
						$pkga['fielddescr'],
1209
						'Show log entries in reverse order (newest entries on top)',
1210
						($value == "on"),
1211
						'on'
1212
					))->setHelp(fixup_string($pkga['description']))->displayAsRadio();
1213
				}
1214
			}
1215

    
1216
			break;
1217

    
1218
		// Create form button
1219
		case "button":
1220
			$newbtn = new Form_Button(
1221
				$pkga['fieldname'],
1222
				$pkga['fieldname']
1223
			);
1224

    
1225
			if(grouping) {
1226
				$group->add(new Form_StaticText(
1227
					null,
1228
					$newbtn . '<br />' . '<div class="help-block">' . fixup_string($pkga['description']) . '</div>'
1229
				));
1230
			} else {
1231
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1232
				$advanced->addInput(new Form_StaticText(
1233
					null,
1234
					$newbtn . '<br />' . '<div class="help-block">' . fixup_string($pkga['description']) . '</div>'
1235
				));
1236
				} else {
1237
				$section->addInput(new Form_StaticText(
1238
					null,
1239
					$newbtn . '<br />' . '<div class="help-block">' . fixup_string($pkga['description']) . '</div>'
1240
				));
1241
				}
1242
			}
1243

    
1244
			break;
1245

    
1246
		case "schedule_selection":
1247

    
1248
			$input = "<select id='{$pkga['fieldname']}' name='{$pkga['fieldname']}'>\n";
1249
			$schedules = array();
1250
			$schedules[] = "none";
1251
			if (is_array($config['schedules']['schedule'])) {
1252
				foreach ($config['schedules']['schedule'] as $schedule) {
1253
					if ($schedule['name'] != "") {
1254
						$schedules[] = $schedule['name'];
1255
					}
1256
				}
1257
			}
1258

    
1259
			foreach ($schedules as $schedule) {
1260
				if ($schedule == "none") {
1261
					$schedlist[""] = $schedule;
1262
				} else {
1263
					$schedlist[$schedule] = $schedule;
1264
				}
1265
			}
1266

    
1267
			if($grouping) {
1268
				$group->add(new Form_Select(
1269
					$pkga['fieldname'],
1270
					$pkga['fielddescr'],
1271
					$value,
1272
					$schedlist
1273
				))->setHelp(fixup_string($pkga['description']));
1274
			} else {
1275
				if (isset($pkga['advancedfield']) && isset($advfield_count)) {
1276
					$advanced->addInput(new Form_Select(
1277
						$pkga['fieldname'],
1278
						$pkga['fielddescr'],
1279
						$value,
1280
						$schedlist
1281
					))->setHelp(fixup_string($pkga['description']));
1282
				} else {
1283
					$section->addInput(new Form_Select(
1284
						$pkga['fieldname'],
1285
						$pkga['fielddescr'],
1286
						$value,
1287
						$schedlist
1288
					))->setHelp(fixup_string($pkga['description']));
1289
				}
1290
			}
1291

    
1292
			break;
1293

    
1294
		case "rowhelper":
1295

    
1296
			$rowhelpername="row";
1297

    
1298
				$rowcounter = 0;
1299
				$trc = 0;
1300

    
1301
				//Use assigned $a_pkg or create an empty array to enter loop
1302
				if (isset($a_pkg[$id][$rowhelpername])) {
1303
					$saved_rows=$a_pkg[$id][$rowhelpername];
1304
				} else {
1305
					$saved_rows[] = array();
1306
				}
1307

    
1308
				$numrows = count($saved_rows) - 1;
1309

    
1310
				foreach ($saved_rows as $row) {
1311
					$group = new Form_Group(($rowcounter == 0) ? $pkga['fielddescr']:null);
1312
					$group->addClass('repeatable');
1313

    
1314
					foreach ($pkga['rowhelper']['rowhelperfield'] as $rowhelper) {
1315
						unset($value);
1316
						if ($rowhelper['value'] != "") {
1317
							$value = $rowhelper['value'];
1318
						}
1319
						$fieldname = $rowhelper['fieldname'];
1320
						$fielddescr = $rowhelper['fielddescr'];
1321

    
1322
						// if user is editing a record, load in the data.
1323
						if (isset($id) && $a_pkg[$id]) {
1324
							$value = $row[$fieldname];
1325
						}
1326

    
1327
						$type = $rowhelper['type'];
1328
						$fieldname = $rowhelper['fieldname'];
1329

    
1330
						if ($rowhelper['size']) {
1331
							$size = $rowhelper['size'];
1332
						} else if ($pkga['size']) {
1333
							$size = $pkga['size'];
1334
						} else {
1335
							$size = "8";
1336
						}
1337

    
1338
						display_row($rowcounter, $value, $fieldname, $type, $rowhelper, ($numrows == $rowcounter) ? $fielddescr:null);
1339

    
1340
						$text = "";
1341
						$trc++;
1342
					}
1343

    
1344
					// Delete row button
1345
					$group->add(new Form_Button(
1346
						'deleterow' . $rowcounter,
1347
						'Delete'
1348
					))->removeClass('btn-primary')->addClass('btn-warning btn-sm');
1349

    
1350
					$rowcounter++;
1351
					$section->add($group);
1352
				}
1353

    
1354
			// Add row button
1355
			$section->addInput(new Form_Button(
1356
				'addrow',
1357
				'Add'
1358
			))->removeClass('btn-primary')->addClass('btn-success');
1359

    
1360
			break;
1361

    
1362
	}
1363

    
1364
		if ($pkga['combinefields'] == "end") {
1365
			$group->add(new Form_StaticText(
1366
				null,
1367
				null
1368
			));
1369

    
1370
			if($advanced)
1371
				$advanced->add($group);
1372
			else
1373
				$section->add($group);
1374

    
1375
			$grouping = false;
1376
		}
1377

    
1378
	#increment counter
1379
	$i++;
1380
} // e-o-foreach field described in the XML
1381

    
1382
$form->add($section);
1383

    
1384
$form->addGlobal(new Form_Input(
1385
	'id',
1386
	null,
1387
	'hidden',
1388
	$id
1389
));
1390

    
1391
// If we created an advanced section, add it (and a button) to the form here
1392
if(!empty($advanced)) {
1393
	$form->addGlobal(new Form_Button(
1394
		'showadv',
1395
		'Show advanced options'
1396
	))->removeClass('btn-primary')->addClass('btn-default');
1397

    
1398
	$form->add($advanced);
1399
}
1400

    
1401
print($form);
1402

    
1403
if ($pkg['note'] != "") {
1404
	print_info_box($pkg['note']);
1405

    
1406
if ($pkg['custom_php_after_form_command'])
1407
	eval($pkg['custom_php_after_form_command']);
1408
}
1409

    
1410
if ($pkg['fields']['field'] != "") { ?>
1411
<script type="text/javascript">
1412
//<![CDATA[
1413
	events.push(function(){
1414

    
1415
	function setMasks() {
1416
		// Find all ipaddress masks and make dynamic based on address family of input
1417
		$('span.pfIpMask + select').each(function (idx, select){
1418
			var input = $(select).prevAll('input[type=text]');
1419

    
1420
			input.on('change', function(e){
1421
				var isV6 = (input.val().indexOf(':') != -1), min = 0, max = 128;
1422
				if (!isV6)
1423
					max = 32;
1424

    
1425
				if (input.val() == "")
1426
					return;
1427

    
1428
				while (select.options.length > max)
1429
					select.remove(0);
1430

    
1431
				if (select.options.length < max)
1432
				{
1433
					for (var i=select.options.length; i<=max; i++)
1434
						select.options.add(new Option(i, i), 0);
1435
				}
1436
			});
1437

    
1438
			// Fire immediately
1439
			input.change();
1440
		});
1441
	}
1442

    
1443
	// Complicated function to move all help text associated with this input id to the same id
1444
	// on the row above. That way if you delete the last row, you don't lose the help
1445
	function moveHelpText(id) {
1446
		$('#' + id).parent('div').parent('div').find('input').each(function() {	 // For each <span></span>
1447
			var fromId = this.id;
1448
			var toId = decrStringInt(fromId);
1449
			var helpSpan;
1450

    
1451
			if(!$(this).hasClass('pfIpMask') && !$(this).hasClass('btn')) {
1452

    
1453
				helpSpan = $('#' + fromId).parent('div').parent('div').find('span:last').clone();
1454
				if($(helpSpan).hasClass('help-block')) {
1455
					if($('#' + decrStringInt(fromId)).parent('div').hasClass('input-group'))
1456
						$('#' + decrStringInt(fromId)).parent('div').after(helpSpan);
1457
					else
1458
						$('#' + decrStringInt(fromId)).after(helpSpan);
1459
				}
1460
			}
1461
		});
1462
	}
1463

    
1464
	// Increment the number at the end of the string
1465
	function bumpStringInt( str )	{
1466
	  var data = str.match(/(\D*)(\d+)(\D*)/), newStr = "";
1467

    
1468
	  if( data )
1469
		newStr = data[ 1 ] + ( Number( data[ 2 ] ) + 1 ) + data[ 3 ];
1470

    
1471
	  return newStr || str;
1472
	}
1473

    
1474
	// Decrement the number at the end of the string
1475
	function decrStringInt( str )	{
1476
	  var data = str.match(/(\D*)(\d+)(\D*)/), newStr = "";
1477

    
1478
	  if( data )
1479
		newStr = data[ 1 ] + ( Number( data[ 2 ] ) - 1 ) + data[ 3 ];
1480

    
1481
	  return newStr || str;
1482
	}
1483

    
1484
	// Called after a delete so that there are no gaps in the numbering. Most of the time the config system doesn't care about
1485
	// gaps, but I do :)
1486
	function renumber() {
1487
		var idx = 0;
1488

    
1489
		$('.repeatable').each(function() {
1490

    
1491
			$(this).find('input').each(function() {
1492
				$(this).prop("id", this.id.replace(/\d+$/, "") + idx);
1493
				$(this).prop("name", this.name.replace(/\d+$/, "") + idx);
1494
			});
1495

    
1496
			$(this).find('select').each(function() {
1497
				$(this).prop("id", this.id.replace(/\d+$/, "") + idx);
1498
				$(this).prop("name", this.name.replace(/\d+$/, "") + idx);
1499
			});
1500

    
1501
			$(this).find('label').attr('for', $(this).find('label').attr('for').replace(/\d+$/, "") + idx);
1502

    
1503
			idx++;
1504
		});
1505
	}
1506

    
1507
	function delete_row(row) {
1508
		$('#' + row).parent('div').parent('div').remove();
1509
		renumber();
1510
	}
1511

    
1512
	function add_row() {
1513
		// Find the lst repeatable group
1514
		var lastRepeatableGroup = $('.repeatable:last');
1515

    
1516
		// Clone it
1517
		var newGroup = lastRepeatableGroup.clone(true);
1518

    
1519
		// Increment the suffix number for each input elemnt in the new group
1520
		$(newGroup).find('input').each(function() {
1521
			$(this).prop("id", bumpStringInt(this.id));
1522
			$(this).prop("name", bumpStringInt(this.name));
1523
			if(!$(this).is('[id^=delete]'))
1524
				$(this).val('');
1525
		});
1526

    
1527
		// Do the same for selectors
1528
		$(newGroup).find('select').each(function() {
1529
			$(this).prop("id", bumpStringInt(this.id));
1530
			$(this).prop("name", bumpStringInt(this.name));
1531
			// If this selector lists mask bits, we need it to be reset to all 128 options
1532
			// and no items selected, so that automatic v4/v6 selection still works
1533
			if($(this).is('[id^=address_subnet]')) {
1534
				$(this).empty();
1535
				for(idx=128; idx>0; idx--) {
1536
					$(this).append($('<option>', {
1537
						value: idx,
1538
						text: idx
1539
					}));
1540
				}
1541
			}
1542
		});
1543

    
1544
		// And for "for" tags
1545
		$(newGroup).find('label').attr('for', bumpStringInt($(newGroup).find('label').attr('for')));
1546
		$(newGroup).find('label').text(""); // Clear the label. We only want it on the very first row
1547

    
1548
		// Insert the updated/cloned row
1549
		$(lastRepeatableGroup).after(newGroup);
1550

    
1551
		// Delete any help text from the group we have cloned
1552
		$(lastRepeatableGroup).find('.help-block').each(function() {
1553
			$(this).remove();
1554
		});
1555

    
1556
		setMasks();
1557

    
1558
		$('[id^=address]').autocomplete({
1559
			source: addressarray
1560
		});
1561
	}
1562

    
1563
	// These are action buttons, not submit buttons
1564
	$('[id^=addrow]').prop('type','button');
1565
	$('[id^=delete]').prop('type','button');
1566

    
1567
	// on click . .
1568
	$('[id^=addrow]').click(function() {
1569
		add_row();
1570
	});
1571

    
1572
	$('[id^=delete]').click(function(event) {
1573
		if($('.repeatable').length > 1) {
1574
			moveHelpText(event.target.id);
1575
			delete_row(event.target.id);
1576
		}
1577
		else
1578
			alert('<?php echo gettext("You may not delete the last one!")?>');
1579
	});
1580

    
1581
	// Hide the advanced section
1582
	var advanced_visible = false;
1583

    
1584
	// Hide on page load
1585
	$('.advancedoptions').hide();
1586

    
1587
	// But show it if you click the showadv button
1588
	$('#showadv').prop('type', 'button');
1589

    
1590
	$("#showadv").click(function() {
1591
		advanced_visible = !advanced_visible;
1592

    
1593
		if(advanced_visible) {
1594
			$('.advancedoptions').show();
1595
			$("#showadv").prop('value', 'Hide advanced Options');
1596
		}
1597
		else {
1598
			$('.advancedoptions').hide();
1599
			$("#showadv").prop('value', 'Show advanced Options');
1600
		}
1601
	});
1602

    
1603
	// Call enablechange function
1604
	enablechange();
1605
});
1606

    
1607
	function enablechange() {
1608
<?php
1609
	foreach ($pkg['fields']['field'] as $field) {
1610
		if (isset($field['enablefields']) or isset($field['checkenablefields'])) {
1611
			echo "\tif (jQuery('input[name=\"{$field['fieldname']}\"]').prop('checked') == false) {\n";
1612

    
1613
			if (isset($field['enablefields'])) {
1614
				foreach (explode(',', $field['enablefields']) as $enablefield) {
1615
					echo "\t\tif (jQuery('input[name=\"{$enablefield}\"]').length > 0) {\n";
1616
					echo "\t\t\tjQuery('input[name=\"{$enablefield}\"]').prop('disabled',true);\n";
1617
					echo "\t\t}\n";
1618
				}
1619
			}
1620

    
1621
			if (isset($field['checkenablefields'])) {
1622
				foreach (explode(',', $field['checkenablefields']) as $checkenablefield) {
1623
					echo "\t\tif (jQuery('input[name=\"{$checkenablefield}\"]').length > 0) {\n";
1624
					echo "\t\t\tjQuery('input[name=\"{$checkenablefield}\"]').prop('checked',true);\n";
1625
					echo "\t\t}\n";
1626
				}
1627
			}
1628

    
1629
			echo "\t}\n\telse {\n";
1630

    
1631
			if (isset($field['enablefields'])) {
1632
				foreach (explode(',', $field['enablefields']) as $enablefield) {
1633
					echo "\t\tif (jQuery('input[name=\"{$enablefield}\"]').length > 0) {\n";
1634
					echo "\t\t\tjQuery('input[name=\"{$enablefield}\"]').prop('disabled',false);\n";
1635
					echo "\t\t}\n";
1636
				}
1637
			}
1638

    
1639
			if (isset($field['checkenablefields'])) {
1640
				foreach (explode(',', $field['checkenablefields']) as $checkenablefield) {
1641
					echo "\t\tif (jQuery('input[name=\"{$checkenablefield}\"]').length > 0) {\n";
1642
					echo "\t\t\tjQuery('input[name=\"{$checkenablefield}\"]').prop('checked',false);\n";
1643
					echo "\t\t}\n";
1644
				}
1645
			}
1646

    
1647
			echo "\t}\n";
1648
		}
1649
	}
1650
	?>
1651
	}
1652
//]]>
1653
</script>
1654

    
1655
<?php
1656
}
1657

    
1658
include("foot.inc");
(114-114/235)