Project

General

Profile

Download (33.7 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
	guiconfig.inc
4
	by Scott Ullrich, Copyright 2004, All rights reserved.
5
	originally based on of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31
/*
32
	pfSense_MODULE:	base
33
*/
34

    
35
/* Include authentication routines */
36
/* THIS MUST BE ABOVE ALL OTHER CODE */
37
if(!$nocsrf) {
38
	function csrf_startup() {
39
		csrf_conf('rewrite-js', '/csrf/csrf-magic.js');
40
		$timeout_minutes = isset($config['system']['webgui']['session_timeout']) ?  $config['system']['webgui']['session_timeout'] : 240;
41
		csrf_conf('expires', $timeout_minutes * 60);
42
	}
43
	require_once("csrf/csrf-magic.php");
44
}
45

    
46
/* make sure nothing is cached */
47
if (!$omit_nocacheheaders) {
48
	header("Expires: 0");
49
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
50
	header("Cache-Control: no-store, no-cache, must-revalidate");
51
	header("Cache-Control: post-check=0, pre-check=0", false);
52
	header("Pragma: no-cache");
53
}
54

    
55
Header("X-Frame-Options: SAMEORIGIN");
56
require_once("authgui.inc");
57

    
58
/* parse the configuration and include all configuration functions */
59
require_once("functions.inc");
60

    
61
/* Pull in all the gui related display classes) */
62
foreach (scandir("/usr/local/www/classes/") as $file) {
63
	if (substr($file, -4) == ".inc") {
64
		require_once("classes/{$file}");
65
	}
66
}
67

    
68
$g['theme'] = get_current_theme();
69

    
70
/* Set the default interface language */
71
if($config['system']['language'] <> "") {
72
	$g['language'] = $config['system']['language'];
73
} elseif ($g['language'] == "") {
74
	$g['language'] = 'en_US';
75
}
76

    
77
set_language($g['language']);
78

    
79
/* used by progress bar */
80
$lastseen = "-1";
81

    
82
$navlevelsep = ": ";	/* navigation level separator string */
83
$mandfldhtml = "";		/* display this before mandatory input fields */
84
$mandfldhtmlspc = "";	/* same as above, but with spacing */
85

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

    
98
/* Reserved table names to avoid colision */
99
$reserved_table_names = array(
100
        "bogons",
101
        "bogonsv6",
102
        "negate_networks",
103
        "snort2c",
104
        "sshlockout",
105
        "tonatsubnets",
106
        "virusprot",
107
        "vpn_networks",
108
        "webConfiguratorlockout"
109
);
110

    
111
$firewall_rules_dscp_types = array("af11",
112
				"af12",
113
				"af13",
114
				"af21",
115
				"af22",
116
				"af23",
117
				"af31",
118
				"af32",
119
				"af33",
120
				"af41",
121
				"af42",
122
				"af43",
123
				"VA",
124
				"EF",
125
				"cs1",
126
				"cs2",
127
				"cs3",
128
				"cs4",
129
				"cs5",
130
				"cs6",
131
				"cs7",
132
				"0x01 (reliability, ToS 0x04)",
133
				"0x02 (throughput, ToS 0x08)",
134
				"0x04 (lowdelay, ToS 0x10)");
135

    
136
$auth_server_types = array(
137
	'ldap' => "LDAP",
138
	'radius' => "Radius");
139

    
140
$ldap_urltypes = array(
141
	'TCP - Standard' => 389,
142
	'SSL - Encrypted' => 636);
143

    
144
$ldap_scopes = array(
145
	'one' => "One Level",
146
	'subtree' => "Entire Subtree");
147

    
148
$ldap_protvers = array(
149
	2,
150
	3);
151

    
152
$ldap_templates = array(
153

    
154
	'open' => array(
155
				'desc' => "OpenLDAP",
156
				'attr_user' => "cn",
157
				'attr_group' => "cn",
158
				'attr_member' => "member"),
159

    
160
	'msad' => array(
161
				'desc' => "Microsoft AD",
162
				'attr_user' => "samAccountName",
163
				'attr_group' => "cn",
164
				'attr_member' => "memberOf"),
165

    
166
	'edir' => array(
167
				'desc' => "Novell eDirectory",
168
				'attr_user' => "cn",
169
				'attr_group' => "cn",
170
				'attr_member' => "uniqueMember"));
171

    
172
$radius_srvcs = array(
173
	'both' => "Authentication and Accounting",
174
	'auth' => "Authentication",
175
	'acct' => "Accounting");
176

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

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

    
231
/* TCP flags */
232
$tcpflags = array("fin", "syn", "rst", "psh", "ack", "urg", "ece", "cwr");
233

    
234
$specialnets = array("pptp" => "PPTP clients", "pppoe" => "PPPoE clients", "l2tp" => "L2TP clients");
235

    
236
$spiflist = get_configured_interface_with_descr(false, true);
237
foreach ($spiflist as $ifgui => $ifdesc) {
238
	$specialnets[$ifgui] = $ifdesc . " net";
239
	$specialnets[$ifgui . 'ip'] = $ifdesc . " address";
240
}
241

    
242
$medias = array("auto" => "autoselect", "100full" => "100BASE-TX full-duplex",
243
	"100half" => "100BASE-TX half-duplex", "10full" => "10BASE-T full-duplex",
244
	"10half" => "10BASE-T half-duplex");
245

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

    
249
/* platforms that support firmware updating */
250
$fwupplatforms = array('pfSense', 'net45xx', 'net48xx', 'generic-pc', 'embedded', 'wrap', 'nanobsd');
251

    
252
function do_input_validation($postdata, $reqdfields, $reqdfieldsn, &$input_errors) {
253

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

    
261
	for ($i = 0; $i < count($reqdfields); $i++) {
262
		if ($_POST[$reqdfields[$i]] == "" && $_REQUEST[$reqdfields[$i]] == "") {
263
			$input_errors[] = "The field '" . $reqdfieldsn[$i] . "' is required.";
264
		}
265
	}
266
}
267

    
268
function print_input_errors($input_errors) {
269
	global $g;
270

    
271
	print <<<EOF
272
	<div id="inputerrorsdiv">
273
	<table border="0" cellspacing="0" cellpadding="4" width="100%" summary="input errors">
274
	<tr>
275
		<td class="inputerrorsleft">
276
			<img src="/themes/{$g['theme']}/images/icons/icon_error.gif" alt="errors" />
277
		</td>
278
		<td class="inputerrorsright errmsg">
279
			<p>The following input errors were detected:</p>
280
				<ul>
281
EOF;
282
		foreach ($input_errors as $ierr) {
283
			echo "<li>" . htmlspecialchars($ierr) . "</li>";
284
		}
285

    
286
	print <<<EOF2
287
				</ul>
288
		</td></tr>
289
	</table>
290
	</div>
291
	&nbsp;<br />
292
EOF2;
293

    
294
}
295

    
296
function verify_gzip_file($fname) {
297
	$returnvar = mwexec("/usr/bin/gzip -t " . escapeshellarg($fname));
298
	if ($returnvar != 0)
299
		return 0;
300
	else
301
		return 1;
302
}
303

    
304
function print_info_box_np($msg, $name="apply",$value="", $showapply=false) {
305
	global $g, $nifty_redbox, $nifty_blackbox, $nifty_background;
306

    
307
	if(empty($value)) {
308
		$value = gettext("Apply changes");
309
	}
310

    
311
	// Set the Nifty background color if one is not set already (defaults to white)
312
	if($nifty_background == "")
313
		$nifty_background = "#FFF";
314

    
315
	if(stristr($msg, gettext("apply")) != false || stristr($msg, gettext("save")) != false || stristr($msg, gettext("create")) != false || $showapply) {
316
		$savebutton = "<td class=\"infoboxsave\">";
317
		$savebutton .= "<input name=\"{$name}\" type=\"submit\" class=\"formbtn\" id=\"${name}\" value=\"{$value}\" />";
318
		if($_POST['if'])
319
			$savebutton .= "<input type=\"hidden\" name=\"if\" value=\"" . htmlspecialchars($_POST['if']) . "\" />";
320
		$savebutton.="</td>";
321
	}
322
	$nifty_redbox = "#990000";
323
	$nifty_blackbox = "#000000";
324

    
325
	$themename = $g['theme'];
326

    
327
	if(file_exists("/usr/local/www/themes/{$themename}/tabcontrols.php")) {
328
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/tabcontrols.php");
329
		eval($toeval);
330
	}
331

    
332
	if(file_exists("/usr/local/www/themes/{$themename}/infobox.php")) {
333
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/infobox.php");
334
		eval($toeval);
335
	}
336

    
337
	if(!$savebutton) {
338
		$savebutton = "<td class=\"infoboxsave\"><input value=\"Close\" type=\"button\" onclick=\"jQuery('#redboxtable').hide();\" /></td>";
339
	}
340

    
341
	echo <<<EOFnp
342
	<table class="infobox" id="redboxtable" summary="red box table">
343
		<tr>
344
			<td>
345
				<div class="infoboxnp" id="redbox">
346
					<table class="infoboxnptable2" summary="message">
347
						<tr>
348
							<td class="infoboxnptd">
349
								&nbsp;&nbsp;&nbsp;<img class="infoboxnpimg" src="/themes/{$g['theme']}/images/icons/icon_exclam.gif" alt="exclamation" />
350
							</td>
351
							<td class="infoboxnptd2">
352
								<b>{$msg}</b>
353
							</td>
354
							{$savebutton}
355
						</tr>
356
					</table>
357
				</div>
358
				<div>
359
					<p>&nbsp;</p>
360
				</div>
361
			</td>
362
		</tr>
363
	</table>
364
	<script type="text/javascript">
365
	//<![CDATA[
366
		NiftyCheck();
367
		Rounded("div#redbox","all","{$nifty_background}","{$nifty_redbox}","smooth");
368
		Rounded("td#blackbox","all","{$nifty_background}","{$nifty_blackbox}","smooth");
369
	//]]>
370
	</script>
371
EOFnp;
372

    
373
}
374

    
375
function print_info_box_np_undo($msg, $name="apply",$value="Apply changes", $undo) {
376
	global $g;
377

    
378
	if(stristr($msg, "apply") != false || stristr($msg, "save") != false || stristr($msg, "create") != false) {
379
		$savebutton = "<td class=\"infoboxsave nowrap\">";
380
		$savebutton .= "<input type=\"button\" value=\"Undo\" onclick=\"document.location='{$undo}'\" />";
381
		$savebutton .= "<input name=\"{$name}\" type=\"submit\" class=\"formbtn\" id=\"${name}\" value=\"{$value}\" />";
382
		$savebutton .= "</td>";
383
		if($_POST['if'])
384
			$savebutton .= "<input type=\"hidden\" name=\"if\" value=\"" . htmlspecialchars($_POST['if']) . "\" />";
385
	}
386
	$nifty_redbox = "#990000";
387
	$nifty_blackbox = "#000000";
388

    
389
	$themename = $g['theme'];
390

    
391
	if(file_exists("/usr/local/www/themes/{$themename}/tabcontrols.php")) {
392
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/tabcontrols.php");
393
		eval($toeval);
394
	}
395

    
396
	if(file_exists("/usr/local/www/themes/{$themename}/infobox.php")) {
397
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/infobox.php");
398
		eval($toeval);
399
	}
400

    
401

    
402
	if(!$savebutton) {
403
		$savebutton = "<td class=\"infoboxsave\"><input value=\"Close\" type=\"button\" onclick=\"jQuery('#redboxtable').hide();\" /></td>";
404
	}
405

    
406
	echo <<<EOFnp
407
	<table class="infobox" id="redboxtable" summary="red box table">
408
		<tr>
409
			<td>
410
				<div class="infoboxnp" id="redbox">
411
					<table class="infoboxnptable2" summary="message">
412
						<tr>
413
							<td class="infoboxnptd">
414
								&nbsp;&nbsp;&nbsp;<img class="infoboxnpimg" src="/themes/{$g['theme']}/images/icons/icon_exclam.gif" alt="exclamation" />
415
							</td>
416
							<td class="infoboxnptd2">
417
								<b>{$msg}</b>
418
							</td>
419
							{$savebutton}
420
							{$undobutton}
421
						</tr>
422
					</table>
423
				</div>
424
				<div>
425
					<p>&nbsp;</p>
426
				</div>
427
			</td>
428
		</tr>
429
	</table>
430
	<script type="text/javascript">
431
	//<![CDATA[
432
		NiftyCheck();
433
		Rounded("div#redbox","all","#FFF","{$nifty_redbox}","smooth");
434
		Rounded("td#blackbox","all","#FFF","{$nifty_blackbox}","smooth");
435
	//]]>
436
	</script>
437
EOFnp;
438

    
439
}
440

    
441
function print_info_box($msg) {
442
	print_info_box_np($msg);
443
}
444

    
445
function get_std_save_message($ok) {
446
	global $d_sysrebootreqd_path;
447
	$filter_related = false;
448
	$filter_pages = array("nat", "filter");
449
	$to_return = "The changes have been applied successfully.";
450
	foreach($filter_pages as $fp)
451
		if(stristr($_SERVER['SCRIPT_FILENAME'], $fp))
452
			$filter_related = true;
453
	if($filter_related)
454
		$to_return .= "<br/>You can also <a href=\"status_filter_reload.php\">monitor</a> the filter reload progress.";
455
	return $to_return;
456
}
457

    
458
function pprint_address($adr) {
459
	global $specialnets;
460

    
461
	if (isset($adr['any'])) {
462
		$padr = "*";
463
	} else if ($adr['network']) {
464
		$padr = $specialnets[$adr['network']];
465
	} else {
466
		$padr = $adr['address'];
467
	}
468

    
469
	if (isset($adr['not']))
470
		$padr = "! " . $padr;
471

    
472
	return $padr;
473
}
474

    
475
function pprint_port($port) {
476
	global $wkports;
477

    
478
	$pport = "";
479

    
480
	if (!$port)
481
		return "*";
482
	else {
483
		$srcport = explode("-", $port);
484
		if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) {
485
			$pport = $srcport[0];
486
			if ($wkports[$srcport[0]]) {
487
				$pport .= " (" . $wkports[$srcport[0]] . ")";
488
			}
489
		} else
490
			$pport .= $srcport[0] . " - " . $srcport[1];
491
	}
492

    
493
	return $pport;
494
}
495

    
496
function firewall_check_for_advanced_options(&$item) {
497
	$item_set = "";
498
	if($item['max'])
499
		$item_set .= "max {$item['max']} ";
500
	if($item['max-src-nodes'])
501
		$item_set .= "max-src-nodes {$item['max-src-nodes']} ";
502
	if($item['max-src-conn'])
503
		$item_set .= "max-src-conn {$item['max-src-conn']} ";
504
	if($item['max-src-states'])
505
		$item_set .= "max-src-states {$item['max-src-states']} ";
506
	if($item['statetype'] != "keep state" && $item['statetype'] != "")
507
		$item_set .= "statetype {$item['statetype']} ";
508
	if($item['statetimeout'])
509
		$item_set .= "statetimeout {$item['statetimeout']} ";
510
	if($item['nosync'])
511
		$item_set .= "nosync ";
512
	if($item['max-src-conn-rate'])
513
		$item_set .= "max-src-conn-rate {$item['max-src-conn-rate']} ";
514
	if($item['max-src-conn-rates'])
515
		$item_set .= "max-src-conn-rates {$item['max-src-conn-rates']} ";
516
	if($item['gateway'])
517
		$item_set .= "gateway {$item['gateway']} ";
518
	if($item['dnpipe'])
519
		$item_set .= "limiter {$item['dnpipe']} ";
520
	if($item['pdnpipe'])
521
		$item_set .= "limiter {$item['pdnpipe']} ";
522
	if($item['l7container'])
523
		$item_set .= "layer7 {$item['l7container']} ";
524
	if($item['tag'])
525
		$item_set .= "tag {$item['tag']} ";
526
	if($item['tagged'])
527
		$item_set .= "tagged {$item['tagged']} ";
528
	if(isset($item['allowopts']))
529
		$item_set .= "allowopts ";
530
	if(isset($item['disablereplyto']))
531
		$item_set .= "disable reply-to ";
532
	if($item['tcpflags_any'] || $item['tcpflags1'] || $item['tcpflags2'])
533
		$item_set .= "tcpflags set";
534

    
535
	return $item_set;
536
}
537

    
538
function gentitle($title) {
539
	global $navlevelsep;
540
	if(!is_array($title))
541
		return $title;
542
	else
543
		return join($navlevelsep, $title);
544
}
545

    
546
function genhtmltitle($title) {
547
	global $config;
548
	return gentitle($title);
549
}
550

    
551
/* update the changedesc and changecount(er) variables */
552
function update_changedesc($update) {
553
	global $changedesc;
554
	global $changecount;
555

    
556
	$changedesc .= " {$update}";
557
	$changecount++;
558
}
559

    
560
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
561
	global $config, $g;
562
	if ($restart_syslogd)
563
		exec("/usr/bin/killall syslogd");
564
	if(isset($config['system']['disablesyslogclog'])) {
565
		unlink($logfile);
566
		touch($logfile);
567
	} else {
568
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
569
		if(isset($config['system']['usefifolog']))
570
			exec("/usr/sbin/fifolog_create -s {$log_size} " . escapeshellarg($logfile));
571
		else
572
			exec("/usr/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
573
	}
574
	if ($restart_syslogd)
575
		system_syslogd_start();
576
}
577

    
578
function clear_all_log_files() {
579
	global $g;
580
	exec("/usr/bin/killall syslogd");
581

    
582
	$log_files = array("system", "filter", "dhcpd", "vpn", "pptps", "poes", "l2tps", "openvpn", "portalauth", "ipsec", "ppp", "relayd", "wireless", "lighttpd", "ntpd", "gateways", "resolver", "routing");
583
	foreach ($log_files as $lfile) {
584
		clear_log_file("{$g['varlog_path']}/{$lfile}.log", false);
585
	}
586

    
587
	system_syslogd_start();
588
	killbyname("dhcpd");
589
	services_dhcpd_configure();
590
	return;
591
}
592

    
593
function dump_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
594
	global $g, $config;
595
	$sor = isset($config['syslog']['reverse']) ? "-r" : "";
596
	$logarr = "";
597
	$grepline = "  ";
598
	if(is_array($grepfor))
599
		$grepline .= " | /usr/bin/egrep " . escapeshellarg(implode("|", $grepfor));
600
	if(is_array($grepinvert))
601
		$grepline .= " | /usr/bin/egrep -v " . escapeshellarg(implode("|", $grepinvert));
602
	if(file_exists($logfile) && filesize($logfile) == 0) {
603
		$logarr = array("Log file started.");
604
	} else {
605
		if($config['system']['disablesyslogclog']) {
606
			exec("cat " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
607
		} else {
608
			if(isset($config['system']['usefifolog']))
609
				exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
610
			else
611
				exec("/usr/sbin/clog " . escapeshellarg($logfile) . "{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
612
		}
613
	}
614
	foreach ($logarr as $logent) {
615
			$logent = preg_split("/\s+/", $logent, 6);
616
			echo "<tr valign=\"top\">\n";
617
			if ($withorig) {
618
					if(isset($config['system']['usefifolog'])) {
619
						$entry_date_time = htmlspecialchars(date("F j, Y, g:i a","" . $logent[1] . ""));
620
						$entry_text = htmlspecialchars($logent[5]);
621
					} else {
622
						$entry_date_time = htmlspecialchars(join(" ", array_slice($logent, 0, 3)));
623
						$entry_text = ($logent[3] ==  $config['system']['hostname']) ? "" : $logent[3] . " ";
624
						$entry_text .= htmlspecialchars($logent[4] . " " . $logent[5]);
625
					}
626
					echo "<td class=\"listlr nowrap\">{$entry_date_time}</td>\n";
627
					echo "<td class=\"listr\">{$entry_text}</td>\n";
628

    
629
			} else {
630
					echo "<td class=\"listlr\" colspan=\"2\">" . htmlspecialchars($logent[5]) . "</td>\n";
631
			}
632
			echo "</tr>\n";
633
	}
634
}
635

    
636
function return_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
637
	global $g, $config;
638
	$sor = (isset($config['syslog']['reverse']) || $grepreverse) ? "-r" : "";
639
	$logarr = "";
640
	$grepline = "  ";
641
	if(is_array($grepfor))
642
		$grepline .= " | /usr/bin/egrep " . escapeshellarg(implode("|", $grepfor));
643
	if(is_array($grepinvert))
644
		$grepline .= " | /usr/bin/egrep -v " . escapeshellarg(implode("|", $grepinvert));
645
	if($config['system']['disablesyslogclog']) {
646
		exec("cat " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
647
	} else {
648
		if(isset($config['system']['usefifolog'])) {
649
			exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
650
		} else {
651
			exec("/usr/sbin/clog " . escapeshellarg($logfile) . "{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
652
		}
653
	}
654
	return($logarr);
655
}
656

    
657
/* Check if variable has changed, update and log if it has
658
 * returns true if var changed
659
 * varname = variable name in plain text
660
 * orig = original value
661
 * new = new value
662
 */
663
function update_if_changed($varname, & $orig, $new) {
664
	if (is_array($orig) && is_array($new)) {
665
		$a_diff = array_diff($orig, $new);
666
		foreach ($a_diff as $diff) {
667
			update_changedesc("removed {$varname}: \"{$diff}\"");
668
		}
669
		$a_diff = array_diff($new, $orig);
670
		foreach ($a_diff as $diff) {
671
			update_changedesc("added {$varname}: \"{$diff}\"");
672
		}
673
		$orig = $new;
674
		return true;
675

    
676
	} else {
677
		if ($orig != $new) {
678
			update_changedesc("{$varname}: \"{$orig}\" -> \"{$new}\"");
679
			$orig = $new;
680
			return true;
681
		}
682
	}
683
	return false;
684
}
685

    
686
function address_to_pconfig($adr, &$padr, &$pmask, &$pnot, &$pbeginport, &$pendport) {
687
	if (isset($adr['any']))
688
		$padr = "any";
689
	else if ($adr['network'])
690
		$padr = $adr['network'];
691
	else if ($adr['address']) {
692
		list($padr, $pmask) = explode("/", $adr['address']);
693
		if (!$pmask) {
694
			if (is_ipaddrv6($padr))
695
				$pmask = 128;
696
			else
697
				$pmask = 32;
698
		}
699
	}
700

    
701
	if (isset($adr['not']))
702
		$pnot = 1;
703
	else
704
		$pnot = 0;
705

    
706
	if ($adr['port']) {
707
		list($pbeginport, $pendport) = explode("-", $adr['port']);
708
		if (!$pendport)
709
			$pendport = $pbeginport;
710
	} else if (!is_alias($pbeginport) && !is_alias($pendport)) {
711
		$pbeginport = "any";
712
		$pendport = "any";
713
	}
714
}
715

    
716
function pconfig_to_address(&$adr, $padr, $pmask, $pnot=false, $pbeginport=0, $pendport=0) {
717
	$adr = array();
718

    
719
	if ($padr == "any")
720
		$adr['any'] = true;
721
	else if (is_specialnet($padr))
722
		$adr['network'] = $padr;
723
	else {
724
		$adr['address'] = $padr;
725
		if (is_ipaddrv6($padr)) {
726
			if ($pmask != 128)
727
				$adr['address'] .= "/" . $pmask;
728
		} else {
729
			if ($pmask != 32)
730
				$adr['address'] .= "/" . $pmask;
731
		}
732
	}
733

    
734
	if ($pnot)
735
		$adr['not'] = true;
736
	else
737
		unset($adr['not']);
738

    
739
	if (($pbeginport != 0) && ($pbeginport != "any")) {
740
		if ($pbeginport != $pendport)
741
			$adr['port'] = $pbeginport . "-" . $pendport;
742
		else
743
			$adr['port'] = $pbeginport;
744
	}
745

    
746
	if(is_alias($pbeginport)) {
747
		$adr['port'] = $pbeginport;
748
	}
749
}
750

    
751
function is_specialnet($net) {
752
	global $specialsrcdst;
753

    
754
	if(!$net)
755
		return false;
756
	if (in_array($net, $specialsrcdst))
757
		return true;
758
	else
759
		return false;
760
}
761

    
762
//function to create widget tabs when called
763
function display_widget_tabs(& $tab_array) {
764
	echo "<div id=\"tabs\">";
765
	$tabscounter = 0;
766
	foreach ($tab_array as $ta) {
767
	$dashpos = strpos($ta[2],'-');
768
	$tabname = $ta[2] . "-tab";
769
	$tabclass = substr($ta[2],0,$dashpos);
770
	$tabclass = $tabclass . "-class";
771
		if ($ta[1] == true) {
772
			$tabActive = "table-cell";
773
			$tabNonActive = "none";
774
		}
775
		else {
776
			$tabActive = "none";
777
			$tabNonActive = "table-cell";
778
		}
779
		echo "<div id=\"{$ta[2]}-active\" class=\"{$tabclass}-tabactive\" style=\"display:{$tabActive}; background-color:#EEEEEE; color:black;\">";
780
		echo "<b>&nbsp;&nbsp;&nbsp;{$ta[0]}";
781
		echo "&nbsp;&nbsp;&nbsp;</b>";
782
		echo "</div>";
783

    
784
		echo "<div id=\"{$ta[2]}-deactive\" class=\"{$tabclass}-tabdeactive\" style=\"display:{$tabNonActive}; background-color:#777777; color:white; cursor: pointer;\" onclick=\"return changeTabDIV('{$ta[2]}')\">";
785
		echo "<b>&nbsp;&nbsp;&nbsp;{$ta[0]}";
786
		echo "&nbsp;&nbsp;&nbsp;</b>";
787
		echo "</div>";
788
	}
789

    
790
	echo "<script type=\"text/javascript\">";
791
	echo "\n//<![CDATA[\n";
792
	echo "NiftyCheck();\n";
793
	echo "Rounded(\"div.{$tabclass}-tabactive\",\"top\",\"#CCCCCC\",\"#EEEEEE\",\"smooth\");\n";
794
	echo "Rounded(\"div.{$tabclass}-tabdeactive\",\"top\",\"#CCCCCC\",\"#777777\",\"smooth\");\n";
795
	echo "//]]>\n";
796
	echo "</script>";
797
	echo "</div>";
798
}
799

    
800

    
801
// Return inline javascript file or CSS to minimizie
802
// request count going back to server.
803
function outputJavaScriptFileInline($javascript) {
804
	if(file_exists($javascript)) {
805
		echo "\n<script type=\"text/javascript\">\n";
806
		include($javascript);
807
		echo "\n</script>\n";
808
	} else {
809
		echo "\n\n<!-- Could not location file:  {$javascript} -->\n\n";
810
	}
811
}
812

    
813

    
814

    
815
function outputCSSPrintFileInline($css) {
816
	if(file_exists($css)) {
817
		echo "\n<style media=\"print\" type=\"text/css\">\n";
818
		include($css);
819
		echo "\n</style>\n";
820
	} else {
821
		echo "\n\n<!-- Could not location file:  {$css} -->\n\n";
822
	}
823
}
824

    
825

    
826
function outputCSSFileInline($css) {
827
	if(file_exists($css)) {
828
		echo "\n<style type=\"text/css\">\n";
829
		include($css);
830
		echo "\n</style>\n";
831
	} else {
832
		echo "\n\n<!-- Could not location file:  {$css} -->\n\n";
833
	}
834
}
835

    
836
$rfc2616 = array(
837
	100 => "100 Continue",
838
	101 => "101 Switching Protocols",
839
	200 => "200 OK",
840
	201 => "201 Created",
841
	202 => "202 Accepted",
842
	203 => "203 Non-Authoritative Information",
843
	204 => "204 No Content",
844
	205 => "205 Reset Content",
845
	206 => "206 Partial Content",
846
	300 => "300 Multiple Choices",
847
	301 => "301 Moved Permanently",
848
	302 => "302 Found",
849
	303 => "303 See Other",
850
	304 => "304 Not Modified",
851
	305 => "305 Use Proxy",
852
	306 => "306 (Unused)",
853
	307 => "307 Temporary Redirect",
854
	400 => "400 Bad Request",
855
	401 => "401 Unauthorized",
856
	402 => "402 Payment Required",
857
	403 => "403 Forbidden",
858
	404 => "404 Not Found",
859
	405 => "405 Method Not Allowed",
860
	406 => "406 Not Acceptable",
861
	407 => "407 Proxy Authentication Required",
862
	408 => "408 Request Timeout",
863
	409 => "409 Conflict",
864
	410 => "410 Gone",
865
	411 => "411 Length Required",
866
	412 => "412 Precondition Failed",
867
	413 => "413 Request Entity Too Large",
868
	414 => "414 Request-URI Too Long",
869
	415 => "415 Unsupported Media Type",
870
	416 => "416 Requested Range Not Satisfiable",
871
	417 => "417 Expectation Failed",
872
	500 => "500 Internal Server Error",
873
	501 => "501 Not Implemented",
874
	502 => "502 Bad Gateway",
875
	503 => "503 Service Unavailable",
876
	504 => "504 Gateway Timeout",
877
	505 => "505 HTTP Version Not Supported"
878
);
879

    
880
function is_rfc2616_code($code) {
881
	global $rfc2616;
882
	if (isset($rfc2616[$code]))
883
		return true;
884
	else
885
		return false;
886
}
887

    
888
function print_rfc2616_select($tag, $current){
889
	global $rfc2616;
890

    
891
	/* Default to 200 OK if not set */
892
	if ($current == "")
893
		$current = 200;
894

    
895
	echo "<select id=\"{$tag}\" name=\"{$tag}\">\n";
896
	foreach($rfc2616 as $code => $message) {
897
		if ($code == $current) {
898
			$sel = " selected=\"selected\"";
899
		} else {
900
			$sel = "";
901
		}
902
		echo "<option value=\"{$code}\"{$sel}>{$message}</option>\n";
903
	}
904
}
905

    
906
// Useful debugging function, much cleaner than print_r
907
function echo_array($array,$return_me=false){
908
	if(is_array($array) == false){
909
		$return = "The provided variable is not an array.";
910
	}else{
911
		foreach($array as $name=>$value){
912
			if(is_array($value)){
913
				$return .= "";
914
				$return .= "['<b>$name</b>'] {<div style=\"margin-left:10px;\">\n";
915
				$return .= echo_array($value,true);
916
				$return .= "</div>}";
917
				$return .= "\n\n";
918
			}else{
919
				if(is_string($value)){
920
					$value = "\"$value\"";
921
				}
922
				$return .= "['<b>$name</b>'] = $value\n\n";
923
			}
924
		}
925
	}
926
	if($return_me == true){
927
		return $return;
928
	}else{
929
		echo "<pre>".$return."</pre>";
930
	}
931
}
932

    
933
/****f* pfsense-utils/display_top_tabs
934
 * NAME
935
 *   display_top_tabs - display tabs with rounded edges
936
 * INPUTS
937
 *   $text      - array of tabs
938
 * RESULT
939
 *   null
940
 ******/
941
function display_top_tabs(& $tab_array, $no_drop_down = false) {
942
	global $config;
943
	global $g;
944
	global $tab_array_indent;
945
	global $tab_array_space;
946
	global $tab_array_char_limit;
947

    
948
	/*  does the user have access to this tab?
949
	 *  master user has access to everything.
950
	 *  if the user does not have access, simply
951
	 *  unset the tab item.
952
	 */
953

    
954
	/* empty string code */
955
	if ($tab_array_indent == '') {
956
		$tab_array_indent = 0;
957
	}
958

    
959
	if ($tab_array_space == '') {
960
		$tab_array_space = 1;
961
	}
962

    
963
	if ($tab_array_char_limit == '') {
964
		$tab_array_char_limit = 92;
965
	}
966

    
967
	foreach ($tab_array as $tab_id => $ta){
968
		if(!isAllowedPage($ta[2]))
969
			unset ($tab_array[$tab_id]);
970
	}
971

    
972
	$tab_active_bg   = "#EEEEEE";
973
	$tab_inactive_bg = "#777777";
974
	$nifty_tabs_corners = "#FFF";
975
	$font_color = "white";
976

    
977
	/* if tabcontrols.php exist for a theme, allow it to be overriden */
978
	$themename = $config['theme'];
979
	$filename = "/usr/local/www/themes/{$themename}/tabcontrols.php";
980
	if(file_exists($filename)) {
981
		$eval_code = file_get_contents($filename);
982
		eval($eval_code);
983
	}
984

    
985
	$tabcharcount = 0;
986
	foreach ($tab_array as $ta)
987
		$tabcharcount = $tabcharcount + strlen($ta[0]);
988

    
989
	if($no_drop_down == true) {
990
		$tabcharcount = 0;
991
		unset($tab_array_char_limit);
992
	}
993

    
994
	// If the character count of the tab names is > 670
995
	// then show a select item dropdown menubox.
996
	if($tabcharcount > $tab_array_char_limit) {
997
		echo "Currently viewing: ";
998
		echo "<select name=\"TabSelect\" onchange=\"tabs_will_go(this)\">\n";
999
		foreach ($tab_array as $ta) {
1000
			if($ta[1]=="true")
1001
				$selected = " selected=\"selected\"";
1002
			else
1003
				$selected = "";
1004
			// Onclick in option will not work in some browser
1005
			// echo "<option onclick=\"document.location='{$ta[2]}';\"{$selected}>{$ta['0']}</option>\n";
1006
			echo "<option value=\"{$ta[2]}\"{$selected}>{$ta['0']}</option>\n";
1007
		}
1008
		echo "</select>\n<p>&nbsp;</p>";
1009
		echo "<script type=\"text/javascript\">";
1010
		echo "\n//<![CDATA[\n";
1011
		echo " function tabs_will_go(obj){ document.location = obj.value; }\n";
1012
		echo "//]]>\n";
1013
		echo "</script>";
1014
	}  else {
1015
		echo "<div class=\"newtabmenu\" style=\"margin:{$tab_array_space}px {$tab_array_indent}px; width:775px;\">\n";
1016
		echo "<!-- Tabbed bar code-->\n";
1017
		echo "<ul class=\"newtabmenu\">\n";
1018
		$tabscounter = 0;
1019
		foreach ($tab_array as $ta) {
1020
			if ($ta[1] == true) {
1021
				echo "  <li class=\"newtabmenu_active\"><a href=\"{$ta[2]}\"><span>{$ta[0]}</span></a></li>\n";
1022
			} else {
1023
				echo "  <li><a href=\"{$ta[2]}\"><span>{$ta[0]}</span></a></li>\n";
1024
			}
1025
			$tabscounter++;
1026
		}
1027
		echo "</ul>\n</div>\n";
1028
	}
1029
}
1030

    
1031
function add_package_tabs($tabgroup, & $tab_array) {
1032
	global $config, $g;
1033

    
1034
	if(!is_array($config['installedpackages']))
1035
		return;
1036
	if(!is_array($config['installedpackages']['tab']))
1037
		return;
1038

    
1039
	foreach($config['installedpackages']['tab'] as $tab) {
1040
		if ($tab['group'] !== $group)
1041
			continue;
1042
		$tab_entry = array();
1043
		if($tab['name']) {
1044
			$tab_entry[] = $tab['name'];
1045
			$tab_entry[] = false;
1046
			$tab_entry[] = $tab['url'];
1047
			$tab_array[] = $tab_entry;
1048
		}
1049
	}
1050
}
1051

    
1052
function alias_info_popup($alias_id){
1053
	global $config;
1054
	$maxlength = 60;
1055
	$close_title="title='".gettext('move mouse out this alias to hide')."'";
1056
	if (is_array($config['aliases']['alias'][$alias_id])){
1057
		$alias_name=$config['aliases']['alias'][$alias_id];
1058
		$alias_objects_with_details = "<table width=\"100%\" border=\"0\" cellpadding=\"2\" cellspacing=\"0\" summary=\"alias info popup\">";
1059
		if ($alias_name['url']) {
1060
			// TODO: Change it when pf supports tables with ports
1061
			if ($alias_name['type'] == "urltable") {
1062
				exec("/sbin/pfctl -t {$alias_name['name']} -T show | wc -l", $total_entries);
1063
				$counter=preg_replace("/\D/","",$total_entries[0]);
1064
				exec("/sbin/pfctl -t {$alias_name['name']} -T show | head -10002", $alias_addresses);
1065
			} else {
1066
				$urlfn = alias_expand_urltable($alias_name['name']);
1067
				$alias_addresses = explode("\n", file_get_contents($urlfn));
1068
				$counter = count($alias_addresses);
1069
			}
1070
			$alias_objects_with_details .= "<tr><td colspan=\"3\" $close_title class=\"vncell\">{$alias_name['url']}</td></tr>";
1071
			$x=0;
1072
			foreach ($alias_addresses as $alias_ports_address ) {
1073
				switch ($x) {
1074
				case 0:
1075
					$x++;
1076
					$alias_objects_with_details .= "<tr><td $close_title class=\"vncell\" width=\"33%\" style=\"background: #FFFFFF;color: #000000;\">{$alias_ports_address}</td>";
1077
					break;
1078
				case 1:
1079
					$x++;
1080
					$alias_objects_with_details .= "<td $close_title class=\"vncell\" width=\"33%\" style=\"background: #FFFFFF;color: #000000;\">{$alias_ports_address}</td>";
1081
					break;
1082
				default:
1083
					$x=0;
1084
					$alias_objects_with_details .= "<td  $close_title class=\"vncell\" width=\"33%\" style=\"background: #FFFFFF;color: #000000;\">{$alias_ports_address}</td><tr>";
1085
					break;
1086
				}
1087
			}
1088
			for ($y = $x; $y <= $x; $y++) {
1089
				$alias_objects_with_details .= "<td $close_title class=\"vncell\" width=\"33%\">&nbsp;</td>";
1090
			}
1091
			if ($x > 0) {
1092
				$alias_objects_with_details .= "</tr>";
1093
			}
1094
			if ($counter > 10002) {
1095
				$alias_objects_with_details .= "<tr><td colspan=\"3\"> listing only first 10k items</td><tr>";
1096
			}
1097
		}
1098
		else{
1099
			$alias_addresses = explode (" ", $alias_name['address']);
1100
			$alias_details = explode ("||", $alias_name['detail']);
1101
			$counter = 0;
1102
			foreach ($alias_addresses as $alias_ports_address) {
1103
				$alias_objects_with_details .= "<tr><td $close_title width=\"5%\" class=\"vncell\" style=\"background: #FFFFFF;color: #000000;\">{$alias_addresses[$counter]}</td>";
1104
				$alias_detail_default = strpos ($alias_details[$counter],"Entry added");
1105
				if ($alias_details[$counter] != "" && $alias_detail_default === False)
1106
					$alias_objects_with_details .="<td $close_title width=\"95%\" class=\"vncell\" style=\"background: #FFFFFF;color: #000000;\">{$alias_details[$counter]}</td>";
1107
				else
1108
					$alias_objects_with_details .="<td $close_title width=\"95%\" class=\"vncell\" style=\"background: #FFFFFF;color: #000000;\">&nbsp;</td>";
1109
				$alias_objects_with_details .= "</tr>";
1110
				$counter++;
1111
			}
1112
		}
1113
		$alias_objects_with_details .= "</table>";
1114
	}
1115
	$alias_descr_substr = $alias_name['descr'];
1116
	if ($strlength >= $maxlength)
1117
		$alias_descr_substr = substr($alias_descr_substr, 0, $maxlength) . "...";
1118
	$item_text = ($counter > 1 ? "items" : "item");
1119
	$alias_caption = "{$alias_descr_substr} - {$counter} {$item_text}<a href=\"/firewall_aliases_edit.php?id={$alias_id}\" title=\"".gettext('edit this alias')."\">&nbsp;&nbsp;edit </a>";
1120
	$strlength = strlen ($alias_caption);
1121
	print "<h1>{$alias_caption}</h1>" . $alias_objects_with_details;
1122
}
1123

    
1124
function rule_popup($src,$srcport,$dst,$dstport){
1125
	global $config,$g;
1126
	$aliases_array = array();
1127
	if ($config['aliases']['alias'] <> "" and is_array($config['aliases']['alias'])) {
1128
		$descriptions = array ();
1129
		foreach ($config['aliases']['alias'] as $alias_id=>$alias_name){
1130
			$loading_image="<a><img src=\'/themes/{$g['theme']}/images/misc/loader.gif\' alt=\'loader\' /> " .gettext("loading...")."</a>";
1131
			switch ($alias_name['type']){
1132
			case "port":
1133
				$width="250";
1134
				break;
1135
			case "urltable":
1136
				$width="500";
1137
				break;
1138
			default:
1139
				$width="350";
1140
				break;
1141
			}
1142
			$span_begin = "<span style=\"cursor: help;\" onmouseover=\"var response_html=domTT_activate(this, event, 'id','ttalias_{$alias_id}','content','{$loading_image}', 'trail', true, 'delay', 300, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle','type','velcro','width',{$width});alias_popup('{$alias_id}','{$g['theme']}','".gettext('loading...')."');\" onmouseout=\"this.style.color = ''; domTT_mouseout(this, event);\"><u>";
1143
			$span_end = "</u></span>";
1144
			if ($alias_name['name'] == $src) {
1145
				$descriptions['src'] = $span_begin;
1146
				$descriptions['src_end'] = $span_end;
1147
			}
1148
			if ($alias_name['name'] == $srcport) {
1149
				$descriptions['srcport'] = $span_begin;
1150
				$descriptions['srcport_end'] = $span_end;
1151
			}
1152
			if ($alias_name['name'] == $dst ) {
1153
				$descriptions['dst'] = $span_begin;
1154
				$descriptions['dst_end'] = $span_end;
1155
			}
1156
			if ($alias_name['name'] == $dstport) {
1157
				$descriptions['dstport'] = $span_begin;
1158
				$descriptions['dstport_end'] = $span_end;
1159
			}
1160
		}
1161
		return $descriptions;
1162
	}
1163
}
1164

    
1165
$timezone = $config['system']['timezone'];
1166
if (!$timezone)
1167
	$timezone = "Etc/UTC";
1168

    
1169
date_default_timezone_set($timezone);
1170

    
1171
?>
(86-86/249)