Project

General

Profile

Download (33.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * guiconfig.inc
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-2024 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally based on m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

    
28
/* Include authentication routines */
29
/* THIS MUST BE ABOVE ALL OTHER CODE */
30
header("X-Frame-Options: SAMEORIGIN");
31
include_once('phpsessionmanager.inc');
32
include_once("util.inc");
33

    
34
function pfSense_csrf_callback() {
35
	include "csrf_error.php";
36
}
37

    
38
if (!$nocsrf) {
39
	function csrf_startup() {
40
		csrf_conf('rewrite-js', '/csrf/csrf-magic.js');
41
		/* Loading the configuration to get this value breaks other
42
		 * functions. See https://redmine.pfsense.org/issues/13757 */
43
		// $timeout_minutes = config_get_path('system/webgui/session_timeout', 240);
44
		$timeout_minutes = 240;
45
		csrf_conf('expires', $timeout_minutes * 60);
46
		csrf_conf('callback', 'pfSense_csrf_callback');
47
	}
48
	require_once("csrf/csrf-magic.php");
49
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {
50
		phpsession_end(true);
51
	}
52
}
53

    
54
/* make sure nothing is cached */
55
if (!$omit_nocacheheaders) {
56
	header("Expires: 0");
57
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
58
	header("Cache-Control: no-cache, no-store, must-revalidate");
59
	header("Pragma: no-cache");
60
}
61

    
62
require_once("authgui.inc");
63
/* Load config.inc after authgui.inc
64
 * See https://redmine.pfsense.org/issues/13757 */
65
include_once('config.inc');
66
include_once('config.lib.inc');
67

    
68
/* parse the configuration and include all configuration functions */
69
require_once("functions.inc");
70

    
71
/* Include the autoloader for all the GUI display classes */
72
require_once("classes/autoload.inc.php");
73

    
74
/* used by progress bar */
75
$lastseen = "-1";
76

    
77
$navlevelsep = ": ";	/* navigation level separator string */
78
$mandfldhtml = "";		/* display this before mandatory input fields */
79
$mandfldhtmlspc = "";	/* same as above, but with spacing */
80

    
81
if (!function_exists('set_language')) {
82
	require_once("pfsense-utils.inc");
83
}
84

    
85
set_language();
86

    
87
/* Some ajax scripts still need access to GUI */
88
if (!$ignorefirmwarelock) {
89
	if (is_subsystem_dirty('firmwarelock')) {
90
		if (!$d_isfwfile) {
91
			header("Location: system_update.php");
92
			exit;
93
		} else {
94
			return;
95
		}
96
	}
97
}
98

    
99
$firewall_rules_dscp_types = array(
100
	"af11",
101
	"af12",
102
	"af13",
103
	"af21",
104
	"af22",
105
	"af23",
106
	"af31",
107
	"af32",
108
	"af33",
109
	"af41",
110
	"af42",
111
	"af43",
112
	"VA",
113
	"EF",
114
	"cs1",
115
	"cs2",
116
	"cs3",
117
	"cs4",
118
	"cs5",
119
	"cs6",
120
	"cs7",
121
	"0x01",
122
	"0x02",
123
	"0x04");
124

    
125
$auth_server_types = array(
126
	'ldap' => "LDAP",
127
	'radius' => "RADIUS");
128

    
129
$ldap_urltypes = array(
130
	'Standard TCP' => 389,
131
	'STARTTLS Encrypted' => 389,
132
	'SSL/TLS Encrypted' => 636);
133

    
134
$ldap_scopes = array(
135
	'one' => gettext("One Level"),
136
	'subtree' => gettext("Entire Subtree"));
137

    
138
$ldap_protvers = array(
139
	2,
140
	3);
141

    
142
$ldap_templates = array(
143

    
144
	'open' => array(
145
		'desc' => "OpenLDAP",
146
		'attr_user' => "cn",
147
		'attr_group' => "cn",
148
		'attr_member' => "member",
149
		'allow_unauthenticated' => "true"),
150

    
151
	'msad' => array(
152
		'desc' => "Microsoft AD",
153
		'attr_user' => "samAccountName",
154
		'attr_group' => "cn",
155
		'attr_member' => "memberOf",
156
		'allow_unauthenticated' => "false"),
157

    
158
	'edir' => array(
159
		'desc' => "Novell eDirectory",
160
		'attr_user' => "cn",
161
		'attr_group' => "cn",
162
		'attr_member' => "uniqueMember",
163
		'allow_unauthenticated' => "false"));
164

    
165
$radius_srvcs = array(
166
	'both' => gettext("Authentication and Accounting"),
167
	'auth' => gettext("Authentication"),
168
	'acct' => gettext("Accounting"));
169

    
170
$radius_protocol = array(
171
	'PAP' => "PAP",
172
	'CHAP_MD5' => "MD5-CHAP",
173
	'MSCHAPv1' => "MS-CHAPv1",
174
	'MSCHAPv2' => "MS-CHAPv2");
175

    
176
$netbios_nodetypes = array(
177
	'0' => "none",
178
	'1' => "b-node",
179
	'2' => "p-node",
180
	'4' => "m-node",
181
	'8' => "h-node");
182

    
183
/* some well known ports */
184
$wkports = array(
185
	179 => "BGP",
186
	5999 => "CVSup",
187
	53 => "DNS",
188
	853 => "DNS over TLS",
189
	21 => "FTP",
190
	3000 => "HBCI",
191
	80 => "HTTP",
192
	443 => "HTTPS",
193
	5190 => "ICQ",
194
	113 => "IDENT/AUTH",
195
	143 => "IMAP",
196
	993 => "IMAP/S",
197
	4500 => "IPsec NAT-T",
198
	500 => "ISAKMP",
199
	1701 => "L2TP",
200
	389 => "LDAP",
201
	636 => "LDAP/S",
202
	1755 => "MMS/TCP",
203
	7000 => "MMS/UDP",
204
	445 => "MS DS",
205
	3389 => "MS RDP",
206
	1512 => "MS WINS",
207
	1863 => "MSN",
208
	119 => "NNTP",
209
	123 => "NTP",
210
	138 => "NetBIOS-DGM",
211
	137 => "NetBIOS-NS",
212
	139 => "NetBIOS-SSN",
213
	1194 => "OpenVPN",
214
	110 => "POP3",
215
	995 => "POP3/S",
216
	1723 => "PPTP",
217
	1812 => "RADIUS",
218
	1813 => "RADIUS accounting",
219
	5004 => "RTP",
220
	5060 => "SIP",
221
	25 => "SMTP",
222
	465 => "SMTP/S",
223
	161 => "SNMP",
224
	162 => "SNMP-Trap",
225
	22 => "SSH",
226
	3478 => "STUN",
227
	587 => "SUBMISSION",
228
	514 => "Syslog",
229
	3544 => "Teredo",
230
	23 => "Telnet",
231
	69 => "TFTP",
232
	5900 => "VNC");
233

    
234
/* TCP flags */
235
$tcpflags = array("fin", "syn", "rst", "psh", "ack", "urg", "ece", "cwr");
236

    
237
$medias = array(
238
	"auto" => gettext("autoselect"),
239
	"100full" => gettext("100BASE-TX full-duplex"),
240
	"100half" => gettext("100BASE-TX half-duplex"),
241
	"10full" => gettext("10BASE-T full-duplex"),
242
	"10half" => gettext("10BASE-T half-duplex"));
243

    
244
$wlan_modes = array(
245
	"bss" => gettext("Infrastructure (BSS)"),
246
	"adhoc" => gettext("Ad-hoc (IBSS)"),
247
	"hostap" => gettext("Access Point"));
248

    
249
function do_input_validation($postdata, $reqdfields, $reqdfieldsn, &$input_errors) {
250

    
251
	/* check for bad control characters */
252
	foreach ($postdata as $pn => $pd) {
253
		if (is_string($pd) && preg_match("/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]/", $pd)) {
254
			$input_errors[] = sprintf(gettext("The field %s contains invalid characters."), $pn);
255
		}
256
	}
257

    
258
	if (is_array($reqdfields)) {
259
		for ($i = 0; $i < count($reqdfields); $i++) {
260
			if ($postdata[$reqdfields[$i]] == "") {
261
				$input_errors[] = sprintf(gettext("The field %s is required."), $reqdfieldsn[$i]);
262
			}
263
		}
264
	}
265
}
266

    
267
function print_input_errors($input_errors) {
268
	echo '<div class="alert alert-danger input-errors">';
269
	echo '<p>' . gettext('The following input errors were detected:') . '</p>';
270
	echo '<ul>';
271

    
272
	foreach ($input_errors as $ierr) {
273
		echo '<li>' . htmlspecialchars($ierr) . '</li>';
274
	}
275

    
276
	echo '</ul>';
277
	echo '</div>';
278
}
279

    
280
function verify_gzip_file($fname) {
281
	$returnvar = mwexec("/usr/bin/gzip -t " . escapeshellarg($fname));
282
	if ($returnvar != 0) {
283
		return 0;
284
	} else {
285
		return 1;
286
	}
287
}
288

    
289
// sprint_info_box() returns a string with a formatted informational box, it does not print the box.
290
// To format and print in one step, call print_info_box() as usual.
291
// Any required button is explicitly created, rather than relying on the detection of certain
292
// strings in the message (such as "apply"). print_info_box_np() has been exterminated.
293
// $class = the bootstrap style class (default, info, warning, success, danger)
294
// $btnname and btntext describe the optional button and its display text, the default is an 'x' Close button.
295
// Note that there is also a shortcut function print_apply_box here that creates a standard "apply" box for you.
296
// In many cases just substitute that for print_info_box_np() to easily get a warning style "Apply changes" box.
297
function sprint_info_box($msg, $class="alert-warning", $btnname = "close", $btntext = "", $btnicon = "", $btnclass = "default") {
298

    
299
	if (strpos($class, "alert-") !== 0) {
300
		$class = 'alert-' . $class;
301
	}
302

    
303
	$msg = '<div class="pull-left">' . $msg . '</div>';
304

    
305
	if ($btnname === "close") {
306
		$msg = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $msg;
307
	} else if ($btnname != "") {
308
		if (empty($btntext)) {
309
			$btntext = $btnname;
310
		}
311
		if (!empty($btnicon)) {
312
			$btnicon = '<i class="' . $btnicon . ' icon-embed-btn"></i>';
313
		}
314

    
315
		$msg .= '<form method="post" class="pull-right"><button type="submit" class="btn btn-' . $btnclass . '" name="'. $btnname . '" value="' . $btntext . '">' . $btnicon . $btntext . '</button>';
316

    
317
		if ( isset($_POST['if']) && !empty($_POST['if'])) {
318
			$msg .= "<input type=\"hidden\" name=\"if\" value=\"" . htmlspecialchars($_POST['if']) . "\" />";
319
		}
320

    
321
		$msg .= '</form>';
322
	}
323

    
324
	return '<div class="alert ' . $class . ' clearfix" role="alert">' . $msg . '</div>';
325
}
326

    
327
// Format and print an info box. See sprint_info_box() for details.
328
function print_info_box($msg, $class="alert-warning", $btnname = "close", $btntext = "", $btnicon = "", $btnclass = "default") {
329
	echo sprint_info_box($msg, $class, $btnname, $btntext, $btnicon, $btnclass);
330
}
331

    
332
function print_apply_box($msg) {
333
	print_info_box($msg, "warning", "apply", gettext("Apply Changes"), 'fa-solid fa-check', 'success');
334
}
335

    
336
// Format and print a box reporting that changes have been applied
337
// $retval = status value from the functions called to apply the changes
338
// 0 is good
339
// non-zero is a problem
340
// $extra_text = optional extra text to display after the standard message
341
function print_apply_result_box($retval, $extra_text="") {
342
	$result_msg = get_std_save_message($retval);
343
	if ($retval === 0) {
344
		// 0 is success
345
		$severity = "success";
346
	} else {
347
		// non-zero means there was some problem
348
		$severity = "warning";
349
	}
350

    
351
	if (strlen($extra_text) > 0) {
352
		$result_msg .= " " . $extra_text;
353
	}
354
	print_info_box($result_msg, $severity);
355
}
356

    
357
/*
358
 * Print Bootstrap callout
359
 *
360
 * @param string $msg     message to display
361
 * @param string $class   contextual class, defaults to info (default | danger | warning | info)
362
 * @param string $heading optional callout heading
363
 */
364
function print_callout($msg, $class = 'info', $heading = '') {
365

    
366
	if ('' == $msg) {
367
		return;
368
	}
369
	$class = strtolower($class);
370
	$callout = '';
371

    
372
	if ($class != 'default' && $class != 'danger' && $class != 'warning' && $class != 'info') {
373
		$class = 'info';
374
	}
375
	$callout .= '<div class="bs-callout bs-callout-' . $class . '">';
376

    
377
	if ('' != $heading) {
378
		$callout .= '<h4>' . $heading . '</h4>';
379
	}
380
	$callout .= $msg . '</div>';
381
	echo $callout;
382
}
383

    
384
function get_std_save_message($retval) {
385
	$filter_related = false;
386
	$filter_pages = array("firewall_aliases", "firewall_nat", "firewall_rules", "status_logs_filter");
387
	if ($retval === 0) {
388
		// 0 is success
389
		$to_return = gettext("The changes have been applied successfully.");
390
	} else {
391
		// non-zero means there was some problem
392
		$to_return = sprintf(gettext('There was a problem applying the changes. See the %1$sSystem Logs%2$s.'), '<a href="/status_logs.php">', '</a>');
393
	}
394
	foreach ($filter_pages as $fp) {
395
		if (stristr($_SERVER['SCRIPT_FILENAME'], $fp)) {
396
			$filter_related = true;
397
		}
398
	}
399
	if ($filter_related) {
400
		$to_return .= " " . gettext("The firewall rules are now reloading in the background.") . "<br />" .
401
		    sprintf(gettext('%1$sMonitor%2$s the filter reload progress.'), "<a href='/status_filter_reload.php'>", "</a>");
402
	}
403
	return $to_return;
404
}
405

    
406
function pprint_address($adr, $specialnet_flags = []) {
407
	// outbound NAT rules use a value of 'any' rather than a key
408
	if (isset($adr['any']) || $adr['network'] == 'any') {
409
		$padr = "*";
410
	} else if ($adr['network']) {
411
		$specialnets = get_specialnet('', $specialnet_flags);
412
		if (array_key_exists($adr['network'], $specialnets)) {
413
			$padr = $specialnets[$adr['network']];
414
		} else {
415
			$padr = $adr['network'];
416
		}
417
	} else {
418
		$padr = $adr['address'];
419
	}
420

    
421
	if (isset($adr['not'])) {
422
		$padr = "! " . $padr;
423
	}
424

    
425
	return $padr;
426
}
427

    
428
function pprint_port($port) {
429
	global $wkports;
430

    
431
	$pport = "";
432

    
433
	if (!$port) {
434
		return "*";
435
	} else {
436
		$srcport = explode("-", $port);
437
		if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) {
438
			$pport = $srcport[0];
439
			if ($wkports[$srcport[0]]) {
440
				$pport .= " (" . $wkports[$srcport[0]] . ")";
441
			}
442
		} else {
443
			$pport .= $srcport[0] . " - " . $srcport[1];
444
		}
445
	}
446

    
447
	return $pport;
448
}
449

    
450
function insert_word_breaks_in_domain_name($domain_name) {
451
	return str_replace('.', '<wbr>.', $domain_name);
452
}
453

    
454
function firewall_check_for_advanced_options(&$item) {
455
	$item_set = "";
456
	if ($item['os']) {
457
			$item_set .= "os " . htmlspecialchars($item['os']) . " ";
458
	}
459
	if ($item['dscp']) {
460
		$item_set .= "dscp " . htmlspecialchars($item['dscp']) . " ";
461
	}
462
	if ($item['max']) {
463
		$item_set .= "max " . htmlspecialchars($item['max']) . " ";
464
	}
465
	if ($item['max-src-nodes']) {
466
		$item_set .= "max-src-nodes " . htmlspecialchars($item['max-src-nodes']) . " ";
467
	}
468
	if ($item['max-src-conn']) {
469
		$item_set .= "max-src-conn " . htmlspecialchars($item['max-src-conn']) . " ";
470
	}
471
	if ($item['max-src-states']) {
472
		$item_set .= "max-src-states " . htmlspecialchars($item['max-src-states']) . " ";
473
	}
474
	if (isset($item['nopfsync'])) {
475
		$item_set .= "nopfsync ";
476
	}
477
	if ($item['statetype'] != "keep state" && $item['statetype'] != "") {
478
		$item_set .= "statetype " . htmlspecialchars($item['statetype']) . " ";
479
	}
480
	if ($item['statetimeout']) {
481
		$item_set .= "statetimeout " . htmlspecialchars($item['statetimeout']) . " ";
482
	}
483
	if (isset($item['nosync'])) {
484
		$item_set .= "no XMLRPC Sync ";
485
	}
486
	if ($item['max-src-conn-rate']) {
487
		$item_set .= "max-src-conn-rate " . htmlspecialchars($item['max-src-conn-rate']) . " ";
488
	}
489
	if ($item['max-src-conn-rates']) {
490
		$item_set .= "max-src-conn-rates " . htmlspecialchars($item['max-src-conn-rates']) . " ";
491
	}
492
	if ($item['vlanprio']) {
493
		$item_set .= "vlanprio " . htmlspecialchars($item['vlanprio']) . " ";
494
	}
495
	if ($item['vlanprioset']) {
496
		$item_set .= "vlanprioset " . htmlspecialchars($item['vlanprioset']) . " ";
497
	}
498
	if ($item['gateway']) {
499
		$item_set .= "gateway " . htmlspecialchars($item['gateway']) . " ";
500
	}
501
	if ($item['dnpipe']) {
502
		$item_set .= "limiter " . htmlspecialchars($item['dnpipe']) . " ";
503
	}
504
	if ($item['pdnpipe']) {
505
		$item_set .= "limiter " . htmlspecialchars($item['pdnpipe']) . " ";
506
	}
507
	if ($item['ackqueue']) {
508
		$item_set .= "ackqueue " . htmlspecialchars($item['ackqueue']) . " ";
509
	}
510
	if ($item['defaultqueue']) {
511
		$item_set .= "defaultqueue " . htmlspecialchars($item['defaultqueue']) . " ";
512
	}
513
	if ($item['tagged']) {
514
		if (array_key_exists('nottagged', $item)) {
515
			$item_set .= '!';
516
		}
517
		$item_set .= "tagged " . htmlspecialchars($item['tagged']) . " ";
518
	}
519
	if ($item['tag']) {
520
		$item_set .= "tag " . htmlspecialchars($item['tag']) . " ";
521
	}
522
	if (isset($item['allowopts'])) {
523
		$item_set .= "allowopts ";
524
	}
525
	if (isset($item['disablereplyto'])) {
526
		$item_set .= "disable reply-to ";
527
	}
528
	if ($item['tcpflags_any'] || $item['tcpflags1'] || $item['tcpflags2']) {
529
		$item_set .= "tcpflags set";
530
	}
531
	return $item_set;
532
}
533

    
534
function gentitle($title) {
535
	global $navlevelsep;
536
	if (!is_array($title)) {
537
		return $title;
538
	} else {
539
		return join($navlevelsep, $title);
540
	}
541
}
542

    
543
function genhtmltitle($title, $links=true) {
544
	if (is_array($title)) {
545
		$num_crumbs = count($title);
546
	} else if ($title != NULL) {
547
		$num_crumbs = 1;
548
	} else {
549
		$num_crumbs = 0;
550
	}
551

    
552
	// If the array contains only one element, there are no breadcrumbs, so don't
553
	// add anything else
554
	if ($num_crumbs > 1) {
555
		$bc = '<ol class="breadcrumb">';
556

    
557
		if (!is_array($links)) {
558
			$gen_default = ($links === true);
559
			$links = array_fill(0, $num_crumbs, '');
560
			// If no links passed, then default to a link to self on the last entry.
561
			if ($gen_default) {
562
				$links[$num_crumbs-1] = '@self';
563
			}
564
		}
565

    
566
		foreach ($title as $idx => $el) {
567
			$href = $links[$idx];
568
			if (strlen($href) > 0) {
569
				// For convenience, if the caller specifies '@self' then make a link
570
				// to the current page, including any query string.
571
				if ($href == '@self') {
572
					$href = $_SERVER['REQUEST_URI'];
573
				}
574
				if (substr($href, 0, 1) != '/') {
575
					$href = '/' . $href;
576
				}
577
				$bc .= '<li><a href="' . htmlentities($href) . '">' . $el . '</a></li>';
578
			} else {
579
				$bc .= '<li>' . $el . '</li>';
580
			}
581
		}
582

    
583
		$bc .= '</ol>';
584
	} else {
585
		$bc = "";
586
	}
587

    
588
	return $bc;
589
}
590

    
591
function gen_customwidgettitle_div($widgettitle) {
592
	$divstr = '<div class="form-group">';
593
	$divstr .= '  <label for="descr" class="col-sm-4 control-label">' . gettext('Widget title'). '</label>';
594
	$divstr .= '  <div class="col-sm-4">';
595
	$divstr .= '    <input type="text" name="descr" id="descr" value="'. $widgettitle . '" class="form-control" />';
596
	$divstr .= '  </div>';
597
	$divstr .= '</div>';
598

    
599
	return $divstr;
600
}
601

    
602
function set_customwidgettitle(& $user_settings) {
603
	if ($_POST['descr']) {
604
		$user_settings['widgets'][$_POST['widgetkey']]['descr'] = trim($_POST['descr']);
605
	} else {
606
		unset($user_settings['widgets'][$_POST['widgetkey']]['descr']);
607
	}
608
}
609

    
610
/* update the changedesc and changecount(er) variables */
611
function update_changedesc($update) {
612
	global $changedesc;
613
	global $changecount;
614

    
615
	$changedesc .= " {$update}";
616
	$changecount++;
617
}
618

    
619
/* Check if variable has changed, update and log if it has
620
 * returns true if var changed
621
 * varname = variable name in plain text
622
 * orig = original value
623
 * new = new value
624
 */
625
function update_if_changed($varname, & $orig, $new) {
626
	if (is_array($orig) && is_array($new)) {
627
		$a_diff = array_diff($orig, $new);
628
		foreach ($a_diff as $diff) {
629
			update_changedesc("removed {$varname}: \"{$diff}\"");
630
		}
631
		$a_diff = array_diff($new, $orig);
632
		foreach ($a_diff as $diff) {
633
			update_changedesc("added {$varname}: \"{$diff}\"");
634
		}
635
		$orig = $new;
636
		return true;
637

    
638
	} else {
639
		if ($orig != $new) {
640
			update_changedesc("{$varname}: \"{$orig}\" -> \"{$new}\"");
641
			$orig = $new;
642
			return true;
643
		}
644
	}
645
	return false;
646
}
647

    
648
//function to create widget tabs when called
649
function display_widget_tabs(& $tab_array) {
650
	echo "<div id=\"tabs\">";
651
	foreach ($tab_array as $ta) {
652
		$dashpos = strpos($ta[2], '-');
653
		$tabclass = substr($ta[2], 0, $dashpos);
654
		$tabclass = $tabclass . "-class";
655
		if ($ta[1] == true) {
656
			$tabActive = "table-cell";
657
			$tabNonActive = "none";
658
		} else {
659
			$tabActive = "none";
660
			$tabNonActive = "table-cell";
661
		}
662
		echo "<div id=\"{$ta[2]}-active\" class=\"{$tabclass}-tabactive\" style=\"display:{$tabActive}; background-color:#EEEEEE; color:black;\">";
663
		echo "<b>&nbsp;&nbsp;&nbsp;{$ta[0]}";
664
		echo "&nbsp;&nbsp;&nbsp;</b>";
665
		echo "</div>";
666

    
667
		echo "<div id=\"{$ta[2]}-deactive\" class=\"{$tabclass}-tabdeactive\" style=\"display:{$tabNonActive}; background-color:#777777; color:white; cursor: pointer;\" onclick=\"return changeTabDIV('{$ta[2]}')\">";
668
		echo "<b>&nbsp;&nbsp;&nbsp;{$ta[0]}";
669
		echo "&nbsp;&nbsp;&nbsp;</b>";
670
		echo "</div>";
671
	}
672
	echo "</div>";
673
}
674

    
675
// Return inline javascript file or CSS to minimize
676
// request count going back to server.
677
function outputJavaScriptFileInline($javascript) {
678
	if (file_exists($javascript)) {
679
		echo "\n<script type=\"text/javascript\">\n";
680
		include_once($javascript);
681
		echo "\n</script>\n";
682
	} else {
683
		echo "\n\n<!-- Could not locate file:  {$javascript} -->\n\n";
684
	}
685
}
686

    
687
function outputCSSPrintFileInline($css) {
688
	if (file_exists($css)) {
689
		echo "\n<style media=\"print\" type=\"text/css\">\n";
690
		include_once($css);
691
		echo "\n</style>\n";
692
	} else {
693
		echo "\n\n<!-- Could not locate file:  {$css} -->\n\n";
694
	}
695
}
696

    
697
function outputCSSFileInline($css) {
698
	if (file_exists($css)) {
699
		echo "\n<style type=\"text/css\">\n";
700
		include_once($css);
701
		echo "\n</style>\n";
702
	} else {
703
		echo "\n\n<!-- Could not locate file:  {$css} -->\n\n";
704
	}
705
}
706

    
707
$rfc2616 = array(
708
	100 => "100 Continue",
709
	101 => "101 Switching Protocols",
710
	200 => "200 OK",
711
	201 => "201 Created",
712
	202 => "202 Accepted",
713
	203 => "203 Non-Authoritative Information",
714
	204 => "204 No Content",
715
	205 => "205 Reset Content",
716
	206 => "206 Partial Content",
717
	300 => "300 Multiple Choices",
718
	301 => "301 Moved Permanently",
719
	302 => "302 Found",
720
	303 => "303 See Other",
721
	304 => "304 Not Modified",
722
	305 => "305 Use Proxy",
723
	306 => "306 (Unused)",
724
	307 => "307 Temporary Redirect",
725
	400 => "400 Bad Request",
726
	401 => "401 Unauthorized",
727
	402 => "402 Payment Required",
728
	403 => "403 Forbidden",
729
	404 => "404 Not Found",
730
	405 => "405 Method Not Allowed",
731
	406 => "406 Not Acceptable",
732
	407 => "407 Proxy Authentication Required",
733
	408 => "408 Request Timeout",
734
	409 => "409 Conflict",
735
	410 => "410 Gone",
736
	411 => "411 Length Required",
737
	412 => "412 Precondition Failed",
738
	413 => "413 Request Entity Too Large",
739
	414 => "414 Request-URI Too Long",
740
	415 => "415 Unsupported Media Type",
741
	416 => "416 Requested Range Not Satisfiable",
742
	417 => "417 Expectation Failed",
743
	500 => "500 Internal Server Error",
744
	501 => "501 Not Implemented",
745
	502 => "502 Bad Gateway",
746
	503 => "503 Service Unavailable",
747
	504 => "504 Gateway Timeout",
748
	505 => "505 HTTP Version Not Supported"
749
);
750

    
751
function is_rfc2616_code($code) {
752
	global $rfc2616;
753
	if (isset($rfc2616[$code])) {
754
		return true;
755
	} else {
756
		return false;
757
	}
758
}
759

    
760
function print_rfc2616_select($tag, $current) {
761
	global $rfc2616;
762

    
763
	/* Default to 200 OK if not set */
764
	if ($current == "") {
765
		$current = 200;
766
	}
767

    
768
	echo "<select id=\"{$tag}\" name=\"{$tag}\">\n";
769
	foreach ($rfc2616 as $code => $message) {
770
		if ($code == $current) {
771
			$sel = " selected";
772
		} else {
773
			$sel = "";
774
		}
775
		echo "<option value=\"{$code}\"{$sel}>{$message}</option>\n";
776
	}
777
	echo "</select>\n";
778
}
779

    
780
// Useful debugging function, much cleaner than print_r
781
function echo_array($array, $return_me = false) {
782
	$return = "";
783
	if (is_array($array) == false) {
784
		$return = "The provided variable is not an array.";
785
	} else {
786
		foreach ($array as $name=>$value) {
787
			if (is_array($value)) {
788
				$return .= "";
789
				$return .= "['<b>$name</b>'] {<div style=\"margin-left:10px;\">\n";
790
				$return .= echo_array($value, true);
791
				$return .= "</div>}";
792
				$return .= "\n\n";
793
			} else {
794
				if (is_string($value)) {
795
					$value = "\"$value\"";
796
				}
797
				$return .= "['<b>$name</b>'] = $value\n\n";
798
			}
799
		}
800
	}
801
	if ($return_me == true) {
802
		return $return;
803
	} else {
804
		echo "<pre>".$return."</pre>";
805
	}
806
}
807

    
808
/****f* pfsense-utils/display_top_tabs
809
 * NAME
810
 *	 display_top_tabs - display tabs with rounded edges
811
 * INPUTS
812
 *	 $text	  - array of tabs
813
 * RESULT
814
 *	 null
815
 ******/
816
function display_top_tabs(& $tab_array, $no_drop_down = false, $type = 'pills', $usepost = "") {
817
	global $tab_array_indent;
818
	global $tab_array_space;
819
	global $tab_array_char_limit;
820

    
821
	/*	does the user have access to this tab?
822
	 *	master user has access to everything.
823
	 *	if the user does not have access, simply
824
	 *	unset the tab item.
825
	 */
826

    
827
	/* empty string code */
828
	if ($tab_array_indent == '') {
829
		$tab_array_indent = 0;
830
	}
831

    
832
	if ($tab_array_space == '') {
833
		$tab_array_space = 1;
834
	}
835

    
836
	if ($tab_array_char_limit == '') {
837
		$tab_array_char_limit = 256;
838
	}
839

    
840
	foreach ($tab_array as $tab_id => $ta) {
841
		if (!isAllowedPage($ta[2])) {
842
			unset ($tab_array[$tab_id]);
843
		}
844
	}
845

    
846
	$tabcharcount = 0;
847
	foreach ($tab_array as $ta) {
848
		$tabcharcount = $tabcharcount + strlen($ta[0]);
849
	}
850

    
851
	if ($no_drop_down == true) {
852
		$tabcharcount = 0;
853
		unset($tab_array_char_limit);
854
	}
855

    
856
	// If the character count of the tab names is > 670
857
	// then show a select item dropdown menubox.
858
	if ($tabcharcount > $tab_array_char_limit) {
859
		echo gettext("Currently viewing: ");
860
		echo "<select name=\"TabSelect\" onchange=\"tabs_will_go(this)\">\n";
861

    
862
		foreach ($tab_array as $ta) {
863
			if ($ta[1] == "true") {
864
				$selected = " selected";
865
			} else {
866
				$selected = "";
867
			}
868
			// Onclick in option will not work in some browser
869
			// echo "<option onclick=\"document.location='{$ta[2]}';\"{$selected}>{$ta['0']}</option>\n";
870
			echo "<option value=\"{$ta[2]}\"{$selected}>{$ta['0']}</option>\n";
871
		}
872

    
873
		echo "</select>\n<p>&nbsp;</p>";
874
		echo "<script type=\"text/javascript\">";
875
		echo "\n//<![CDATA[\n";
876
		if ($usepost == 'usepost') {
877
			echo " function tabs_will_go(obj){ var target = obj.value.split(\"?\"); postSubmit(get2post(target[1]),target[0]); }\n";
878
		} else {
879
			echo " function tabs_will_go(obj){ document.location = obj.value; }\n";
880
		}
881
		echo "//]]>\n";
882
		echo "</script>";
883
	} else {
884
		echo '<ul class="nav nav-' . $type . '">';
885

    
886
		foreach ($tab_array as $ta) {
887
			echo '<li role="presentation"';
888
			if ($ta[1]) {
889
				echo ' class="active"';
890
			}
891

    
892
			echo '><a href="' . $ta[2] . '" ' . $usepost . '>' . $ta[0] . '</a></li>';
893
		}
894

    
895
		echo '</ul>';
896
	}
897
}
898

    
899
function add_package_tabs($tabgroup, &$tab_array) {
900
	foreach (config_get_path('installedpackages/package', []) as $pkg) {
901
		if (!is_array($pkg['tabs']['tab'])) {
902
			continue;
903
		}
904

    
905
		foreach ($pkg['tabs']['tab'] as $tab) {
906
			if ($tab['tabgroup'] != $tabgroup) {
907
				continue;
908
			}
909
			$tab_entry = array();
910
			if ($tab['name']) {
911
				$tab_entry[] = $tab['name'];
912
				$tab_entry[] = false;
913
				$tab_entry[] = $tab['url'];
914
				$tab_array[] = $tab_entry;
915
			}
916
		}
917
	}
918
}
919

    
920
function system_alias_info_popup($friendly_interface) {
921
	if (empty($friendly_interface)) {
922
		return '';
923
	}
924

    
925
	$content = [];
926
	$alias = escapeshellarg(strtoupper($friendly_interface) . '__NETWORK');
927
	exec("/sbin/pfctl -t {$alias} -T show 2>/dev/null", $content);
928

    
929
	$alias_items = [];
930
	foreach ($content as $address) {
931
		$alias_items[] = trim($address);
932
	}
933

    
934
	$content = "<h5>{$alias}</h5>";
935
	if (empty($alias_items)) {
936
		return $content;
937
	}
938

    
939
	$content .= '<ul><li>' . implode('</li><li>', $alias_items) . '</li></ul>';
940
	return $content;
941
}
942

    
943
function alias_info_popup($alias_id) {
944
	global $user_settings;
945

    
946
	$alias = config_get_path("aliases/alias/{$alias_id}");
947
	if (!is_array($alias)) {
948
		return;
949
	}
950

    
951
	$maxlength = 60;
952
	$content = "";
953

    
954
	if ($user_settings['webgui']['disablealiaspopupdetail']) {
955
		if (strlen($alias['descr']) >= $maxlength) {
956
			$alias['descr'] = substr($alias['descr'], 0, $maxlength) . '&hellip;';
957
		}
958

    
959
		$content .= $alias['descr'];
960
	} else if ($alias['url']) {
961
		// TODO: Change it when pf supports tables with ports
962
		if ($alias['type'] == "urltable") {
963
			exec("/sbin/pfctl -t {$alias['name']} -T show | wc -l", $total_entries);
964
			$counter=preg_replace("/\D/", "", $total_entries[0]);
965
			exec("/sbin/pfctl -t {$alias['name']} -T show | head -10002", $alias_addresses);
966
		} else {
967
			$urlfn = alias_expand_urltable($alias['name']);
968
			$alias_addresses = empty($urlfn) ? [] : explode("\n", file_get_contents($urlfn));
969
			$counter = count($alias_addresses);
970
		}
971

    
972
		$content .= '<h5>'. htmlspecialchars($alias['url']) .'</h5><ul><li>'. implode('</li><li>', $alias_addresses) .'</li></ul>';
973
		if ($counter > 10002) {
974
			$content .= '<i>'. gettext("listing only first 10k items") .'</i>';
975
		}
976
	} else {
977
		$alias_addresses = explode (" ", $alias['address']);
978
		$alias_details = explode ("||", $alias['detail']);
979
		$idx = 0;
980

    
981
		$content .= "<table>\n";
982
		$content .= "<thead>\n";
983
		$content .= "<tr>\n";
984
		$content .= "<th>" . gettext("Value") . "</th><th  style='padding-left: 10px;'>" . gettext("Description") . "</th></tr>\n";
985
		$content .= "</thead>\n";
986
		$content .= "<tbody>\n";
987

    
988
		foreach ($alias_addresses as $ap) {
989
			$content .= "	<tr>\n";
990
			$content .= "		<td>\n";
991
			$content .= 			alias_idn_to_utf8($ap);
992
			$content .=	"		</td>\n";
993
			$content .= "		<td style='padding-left: 10px;'>\n";
994
			$content .= 			htmlspecialchars($alias_details[$idx]);
995
			$content .=	"		</td>\n";
996
			$content .= "	</tr>\n";
997
			$idx++;
998
		}
999

    
1000
		$content .= "</tbody>\n";
1001
		$content .= "</table>\n";
1002
	}
1003

    
1004
	return $content;
1005
}
1006

    
1007
function gateway_info_popup($showgw, $gateways_status = false) {
1008
	config_init_path('gateways/gateway_group');
1009
	/* Get groups indexed by name so we can avoid re-scanning the array
1010
	 * multiple times later unnecessarily. */
1011
	$a_gateways = get_gateways(GW_CACHE_DISABLED | GW_CACHE_INACTIVE);
1012

    
1013
	/* Use cached gateway status if available.
1014
	 * See https://redmine.pfsense.org/issues/12174 */
1015
	if (!is_array($gateways_status)) {
1016
		$gateways_status = return_gateways_status(true);
1017
	}
1018

    
1019
	$content = "";
1020
	$gws = array();
1021
	$bgdanger = array('force_down', 'down', 'highloss', 'highdelay');
1022
	$bgwarning = array('loss', 'delay');
1023
	$bgsuccess = array('online', 'none');
1024
	$bgcolor = "bg-info";
1025
	$link = "";
1026

    
1027
	if (is_array($a_gateways)) {
1028
		/* Since gw array is hashed by name, we need to count the
1029
		 * index number manually for links since those are by position.
1030
		 */
1031
		$i = 0;
1032
		foreach ($a_gateways as $gateway) {
1033
			if ($gateway['name'] == $showgw) {
1034
				$gws[] = $gateway['name'];
1035
				$link = "/system_gateways_edit.php?id={$i}";
1036
				break;
1037
			}
1038
			$i++;
1039
		}
1040
	}
1041
	$grouptiermap = [];
1042
	foreach(config_get_path('gateways/gateway_group', []) as $i => $gwgroup) {
1043
		if ($gwgroup['name'] == $showgw) {
1044
			$groupinfo = [];
1045
			foreach ($gwgroup['item'] as $member) {
1046
				$membersplit = explode("|", $member);
1047
				$groupinfo[] = [
1048
					'gw' => $membersplit[0],
1049
					'tier' => $membersplit[1],
1050
					'type' => $membersplit[2]
1051
				];
1052
				/* Store tier separately */
1053
				$grouptiermap[$membersplit[0]] = $membersplit[1];
1054
			}
1055
			/* Sort group info array by tier (number) and then by
1056
			 * name (natural) */
1057
			$gws = array_column($groupinfo, 'gw');
1058
			$tiers = array_column($groupinfo, 'tier');
1059
			array_multisort($tiers, SORT_NUMERIC,
1060
					$gws, SORT_NATURAL,
1061
					$groupinfo);
1062
			/* Re-slice member gateways which are now sorted */
1063
			$gws = array_column($groupinfo, 'gw');
1064
			$link = "/system_gateway_groups_edit.php?id={$i}";
1065
			break;
1066
		}
1067
	}
1068

    
1069
	if (!empty($gws)) {
1070
		$content .= "<table>\n";
1071
		$content .= "<thead>\n";
1072
		$content .= "<tr>\n";
1073
		/* Only add Tier column if this is a group */
1074
		if (!empty($grouptiermap)) {
1075
			$content .= "<th>" . gettext("Tier") . "</th>";
1076
			$content .= "<th style='padding-left: 10px;'>";
1077
		} else {
1078
			$content .= "<th>";
1079
		}
1080
		$content .= gettext("Name") . "</th>";
1081
		$content .= "<th style='padding-left: 10px;'>" . gettext("Interface") . "</th>";
1082
		$content .= "<th style='padding-left: 10px;'>" . gettext("Gateway") . "</th></tr>\n";
1083
		$content .= "</thead>\n";
1084
		$content .= "<tbody>\n";
1085
		foreach ($gws as $gw) {
1086
			foreach ($gateways_status as $gwstatus) {
1087
				if ($gwstatus['name'] != $gw) {
1088
					continue;
1089
				}
1090
				/* Distinguish between online/offline in general */
1091
				if (stristr($gwstatus['status'], "online")) {
1092
					/* Use substatus to indicate warnings as needed */
1093
					if (in_array($gwstatus['substatus'], $bgdanger)) {
1094
						$bgcolor = "bg-danger";
1095
					} elseif (in_array($gwstatus['substatus'], $bgwarning)) {
1096
						$bgcolor = "bg-warning";
1097
					} elseif (in_array($gwstatus['substatus'], $bgsuccess)) {
1098
						$bgcolor = "bg-success";
1099
					}
1100
				} elseif (stristr($gwstatus['status'], "down")) {
1101
					/* Anything down is danger, no need to check substatus. */
1102
					$bgcolor = "bg-danger";
1103
				} else {
1104
					/* Unknown status */
1105
					$bgcolor = "bg-info";
1106
				}
1107
			}
1108
			$content .= "	<tr class='{$bgcolor}'>\n";
1109
			/* Only print Tier if this is a group */
1110
			if (!empty($grouptiermap)) {
1111
				$content .= "		<td>\n";
1112
				$content .= 			$grouptiermap[$gw];
1113
				$content .= "		</td>\n";
1114
			}
1115
			$content .= "		<td>\n";
1116
			$content .= 			$gw;
1117
			$content .= "		</td>\n";
1118
			$content .= "		<td style='padding-left: 10px;'>\n";
1119
			$content .= 			$a_gateways[$gw]['friendlyifdescr'];
1120
			$content .= "		</td>\n";
1121
			$content .= "		<td style='padding-left: 10px;'>\n";
1122
			$content .= 			$a_gateways[$gw]['gateway'];
1123
			$content .= "		</td>\n";
1124
			$content .= "	</tr>\n";
1125
		}
1126
		$content .= "</tbody>\n";
1127
		$content .= "</table>\n";
1128
	} else {
1129
		return;
1130
	}
1131

    
1132
	return "<a href=\"{$link}\" data-toggle=\"popover\" data-trigger=\"hover focus\" title=\"" . gettext('Gateway details') . "\" data-content=\"{$content}\" data-html=\"true\">";
1133
}
1134

    
1135
function rule_columns_with_alias($src, $srcport, $dst, $dstport, $target="", $targetport="") {
1136
	$columns = array();
1137
	foreach (config_get_path('aliases/alias', []) as $alias_id => $alias_name) {
1138
		if ($alias_name['name'] == $src) {
1139
			$columns['src'] = $alias_id;
1140
		}
1141
		if ($alias_name['name'] == $srcport) {
1142
			$columns['srcport'] = $alias_id;
1143
		}
1144
		if ($alias_name['name'] == $dst) {
1145
			$columns['dst'] = $alias_id;
1146
		}
1147
		if ($alias_name['name'] == $dstport) {
1148
			$columns['dstport'] = $alias_id;
1149
		}
1150
		if ($alias_name['name'] == $target) {
1151
			$columns['target'] = $alias_id;
1152
		}
1153
		if ($alias_name['name'] == $targetport) {
1154
			$columns['targetport'] = $alias_id;
1155
		}
1156
	}
1157

    
1158
	return $columns;
1159
}
1160

    
1161
function form_output_row($name, $label, $content) {
1162
var_dump($content);die;
1163
?>
1164
<div class="form-group">
1165
	<label for="<?=$name?>" class="col-sm-2 control-label"><?=gettext($label); ?></label>
1166
	<div class="col-sm-10">
1167
		<?=$content?>
1168
	</div>
1169
</div>
1170
<?php
1171
}
1172

    
1173
function set_flash_message($class, $msg) {
1174
	@phpsession_begin();
1175
	$_SESSION['flash_messages'][$class][] = $msg;
1176
	@phpsession_end(true);
1177
}
1178

    
1179
function get_flash_message() {
1180
	@phpsession_begin();
1181
	if (isset($_SESSION['flash_messages']) && !empty($_SESSION['flash_messages'])) {
1182
		foreach ($_SESSION['flash_messages'] as $class => $flash_message) {
1183
			print_info_box(implode("<br />", $flash_message), $class);
1184
		}
1185
		unset($_SESSION['flash_messages']);
1186
	}
1187
	@phpsession_end(true);
1188
}
1189

    
1190
/* Retrieve GET or POST Value/State
1191
 * Example Usage:
1192
 * $value = getGETPOSTsettingvalue('get/post parameter name', "");
1193
 * $value = getGETPOSTsettingvalue('get/post parameter name', null);
1194
 * $state = getGETPOSTsettingvalue('get/post parameter name', null);
1195
 * $state = getGETPOSTsettingvalue('get/post parameter name', false);
1196
 */
1197
function getGETPOSTsettingvalue($settingname, $default) {
1198
	$settingvalue = $default;
1199
	if ($_GET[$settingname]) {
1200
		$settingvalue = $_GET[$settingname];
1201
	}
1202
	if ($_POST[$settingname]) {
1203
		$settingvalue = $_POST[$settingname];
1204
	}
1205
	return $settingvalue;
1206
}
1207

    
1208
/* set timezone */
1209
$cfgtz = config_get_path('system/timezone');
1210
if ($cfgtz) {
1211
	$timezone = $cfgtz;
1212
} elseif (isset($g['default_timezone']) && !empty(g_get('default_timezone'))) {
1213
	$timezone = g_get('default_timezone');
1214
} else {
1215
	$timezone = "Etc/UTC";
1216
}
1217

    
1218
/* Remove files we do not want to see in a crash report */
1219
function cleanup_crash_file_list() {
1220
	$files = glob("/var/crash/*");
1221
	if (!is_array($files) || empty($files)) {
1222
		return array();
1223
	}
1224

    
1225
	$exclude_patterns = array(
1226
		'.*.last',
1227
		'bounds',
1228
		'minfree'
1229
	);
1230

    
1231
	foreach ($files as $idx => $fb) {
1232
		if (preg_match('/' . implode('|', $exclude_patterns) . '/', basename($fb)) == 1) {
1233
			unset($files[$idx]);
1234
		}
1235
	}
1236

    
1237
	return $files;
1238
}
1239

    
1240
function system_has_crash_data() {
1241
	/* Test if there are any crash data files present */
1242
	return count(cleanup_crash_file_list()) > 0;
1243
}
1244

    
1245
function system_has_php_errors() {
1246
	/* Check if the PHP error log is empty. Cast to int in case the file
1247
	 * does not exist and filesize() returns false. */
1248
	return (int) @filesize("/tmp/PHP_errors.log") > 0;
1249
}
1250

    
1251
date_default_timezone_set($timezone);
1252

    
1253
?>
(68-68/232)