Project

General

Profile

Download (31.4 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",
133
				"0x02",
134
				"0x04");
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
	'8' => "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("(self)" => "This Firewall", "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[] = sprintf(gettext("The field %s contains invalid characters."), $pn);
258
		}
259
	}
260

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

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

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

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

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

    
289
function print_info_box_np($msg, $name="apply",$value="", $showapply=false) {
290
	global $g;
291

    
292
	if(empty($value)) {
293
		$value = gettext("Apply changes");
294
	}
295

    
296
	if (stristr($msg, gettext("apply")) != false || stristr($msg, gettext("save")) != false || stristr($msg, gettext("create")) != false || $showapply) {
297
		$msg .= '<form method="post"><input type="submit" class="btn btn-default" name="apply" value="'.$value.'" />';
298

    
299
		if ($_POST['if'])
300
			$msg .= "<input type=\"hidden\" name=\"if\" value=\"" . htmlspecialchars($_POST['if']) . "\" />";
301

    
302
		$msg .'</form>';
303
	} else
304
		$msg = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'. $msg;
305

    
306
	echo '<div class="alert alert-warning" role="alert">'.$msg.'</div>';
307
}
308

    
309
function print_info_box_np_undo($msg, $name="apply",$value="Apply changes", $undo) {
310
	global $g;
311

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

    
323
	$themename = $g['theme'];
324

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

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

    
335

    
336
	if(!$savebutton) {
337
		$savebutton = "<td class=\"infoboxsave\"><input value=\"" . gettext("Close") . "\" type=\"button\" onclick=\"jQuery(this).parents('table[id=redboxtable]').hide();\" /></td>";
338
	}
339

    
340
	echo <<<EOFnp
341
	<table class="infobox" id="redboxtable" summary="red box table">
342
		<tr>
343
			<td>
344
				<div class="infoboxnp" id="redbox">
345
					<table class="infoboxnptable2" summary="message">
346
						<tr>
347
							<td class="infoboxnptd">
348
								&nbsp;&nbsp;&nbsp;<img class="infoboxnpimg" src="/themes/{$g['theme']}/images/icons/icon_exclam.gif" alt="exclamation" />
349
							</td>
350
							<td class="infoboxnptd2">
351
								<b>{$msg}</b>
352
							</td>
353
							{$savebutton}
354
							{$undobutton}
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","#FFF","{$nifty_redbox}","smooth");
368
		Rounded("td#blackbox","all","#FFF","{$nifty_blackbox}","smooth");
369
	//]]>
370
	</script>
371
EOFnp;
372

    
373
}
374

    
375
function print_info_box($msg) {
376
	print_info_box_np($msg);
377
}
378

    
379
function get_std_save_message($ok) {
380
	global $d_sysrebootreqd_path;
381
	$filter_related = false;
382
	$filter_pages = array("nat", "filter");
383
	$to_return = gettext("The changes have been applied successfully.");
384
	foreach($filter_pages as $fp)
385
		if(stristr($_SERVER['SCRIPT_FILENAME'], $fp))
386
			$filter_related = true;
387
	if($filter_related)
388
		$to_return .= "<br />" . gettext("You can also <a href=\"status_filter_reload.php\">monitor</a> the filter reload progress.");
389
	return $to_return;
390
}
391

    
392
function pprint_address($adr) {
393
	global $specialnets;
394

    
395
	if (isset($adr['any'])) {
396
		$padr = "*";
397
	} else if ($adr['network']) {
398
		$padr = $specialnets[$adr['network']];
399
	} else {
400
		$padr = $adr['address'];
401
	}
402

    
403
	if (isset($adr['not']))
404
		$padr = "! " . $padr;
405

    
406
	return $padr;
407
}
408

    
409
function pprint_port($port) {
410
	global $wkports;
411

    
412
	$pport = "";
413

    
414
	if (!$port)
415
		return "*";
416
	else {
417
		$srcport = explode("-", $port);
418
		if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) {
419
			$pport = $srcport[0];
420
			if ($wkports[$srcport[0]]) {
421
				$pport .= " (" . $wkports[$srcport[0]] . ")";
422
			}
423
		} else
424
			$pport .= $srcport[0] . " - " . $srcport[1];
425
	}
426

    
427
	return $pport;
428
}
429

    
430
function firewall_check_for_advanced_options(&$item) {
431
	$item_set = "";
432
	if($item['os'])
433
		$item_set .= "os {$item['os']} ";
434
	if($item['dscp'])
435
		$item_set .= "dscp {$item['dscp']} ";
436
	if($item['max'])
437
		$item_set .= "max {$item['max']} ";
438
	if($item['max-src-nodes'])
439
		$item_set .= "max-src-nodes {$item['max-src-nodes']} ";
440
	if($item['max-src-conn'])
441
		$item_set .= "max-src-conn {$item['max-src-conn']} ";
442
	if($item['max-src-states'])
443
		$item_set .= "max-src-states {$item['max-src-states']} ";
444
	if(isset($item['nopfsync']))
445
		$item_set .= "nopfsync ";
446
	if($item['statetype'] != "keep state" && $item['statetype'] != "")
447
		$item_set .= "statetype {$item['statetype']} ";
448
	if($item['statetimeout'])
449
		$item_set .= "statetimeout {$item['statetimeout']} ";
450
	if(isset($item['nosync']))
451
		$item_set .= "no XMLRPC Sync ";
452
	if($item['max-src-conn-rate'])
453
		$item_set .= "max-src-conn-rate {$item['max-src-conn-rate']} ";
454
	if($item['max-src-conn-rates'])
455
		$item_set .= "max-src-conn-rates {$item['max-src-conn-rates']} ";
456
	if($item['vlanprio'])
457
		$item_set .= "vlanprio {$item['vlanprio']} ";
458
	if($item['vlanprioset'])
459
		$item_set .= "vlanprioset {$item['vlanprioset']} ";
460
	if($item['gateway'])
461
		$item_set .= "gateway {$item['gateway']} ";
462
	if($item['dnpipe'])
463
		$item_set .= "limiter {$item['dnpipe']} ";
464
	if($item['pdnpipe'])
465
		$item_set .= "limiter {$item['pdnpipe']} ";
466
	if($item['ackqueue'])
467
		$item_set .= "ackqueue {$item['ackqueue']} ";
468
	if($item['defaultqueue'])
469
		$item_set .= "defaultqueue {$item['defaultqueue']} ";
470
	if($item['l7container'])
471
		$item_set .= "layer7 {$item['l7container']} ";
472
	if($item['tag'])
473
		$item_set .= "tag {$item['tag']} ";
474
	if($item['tagged'])
475
		$item_set .= "tagged {$item['tagged']} ";
476
	if(isset($item['allowopts']))
477
		$item_set .= "allowopts ";
478
	if(isset($item['disablereplyto']))
479
		$item_set .= "disable reply-to ";
480
	if($item['tcpflags_any'] || $item['tcpflags1'] || $item['tcpflags2'])
481
		$item_set .= "tcpflags set";
482

    
483
	return $item_set;
484
}
485

    
486
function gentitle($title) {
487
	if(!is_array($title))
488
		return $title;
489
	else
490
		return join($navlevelsep, $title);
491
}
492

    
493
function genhtmltitle($title) {
494
	if(!is_array($title))
495
		return '<h1 class="page-header">' . $title . '</h1>';
496

    
497
	$heading = '<h1 class="page-header">' . end($title) . '</h1>';
498

    
499
	$bc = '<ol class="breadcrumb">';
500

    
501
	foreach ($title as $el)
502
		$bc .= '<li>'.$el.'</li>';
503

    
504
	$bc .= '</ol>';
505

    
506
	return $heading . $bc;
507
}
508

    
509
/* update the changedesc and changecount(er) variables */
510
function update_changedesc($update) {
511
	global $changedesc;
512
	global $changecount;
513

    
514
	$changedesc .= " {$update}";
515
	$changecount++;
516
}
517

    
518
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
519
	global $config, $g;
520
	if ($restart_syslogd)
521
		exec("/usr/bin/killall syslogd");
522
	if(isset($config['system']['disablesyslogclog'])) {
523
		unlink($logfile);
524
		touch($logfile);
525
	} else {
526
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
527
		if(isset($config['system']['usefifolog']))
528
			exec("/usr/sbin/fifolog_create -s {$log_size} " . escapeshellarg($logfile));
529
		else
530
			exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
531
	}
532
	if ($restart_syslogd)
533
		system_syslogd_start();
534
}
535

    
536
function clear_all_log_files() {
537
	global $g;
538
	exec("/usr/bin/killall syslogd");
539

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

    
545
	system_syslogd_start();
546
	killbyname("dhcpd");
547
	services_dhcpd_configure();
548
	return;
549
}
550

    
551
// This version of dump_clog() does not output <td></td> or any other table elements. It can be renamed
552
// and the dump_clog() removed once all of the diag_log*.php files have been converted to Bootstrap
553
function dump_clog_no_table($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
554
	global $g, $config;
555
	$sor = isset($config['syslog']['reverse']) ? "-r" : "";
556
	$logarr = "";
557
	$grepline = "  ";
558
	if(is_array($grepfor))
559
		$grepline .= " | /usr/bin/egrep " . escapeshellarg(implode("|", $grepfor));
560
	if(is_array($grepinvert))
561
		$grepline .= " | /usr/bin/egrep -v " . escapeshellarg(implode("|", $grepinvert));
562
	if (is_dir($logfile)) {
563
		$logarr = array("File $logfile is a directory.");
564
	} elseif (file_exists($logfile) && filesize($logfile) == 0) {
565
		$logarr = array("Log file started.");
566
	} else {
567
		if($config['system']['disablesyslogclog']) {
568
			exec("cat " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
569
		} else {
570
			if(isset($config['system']['usefifolog']))
571
				exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
572
			else
573
				exec("/usr/local/sbin/clog " . escapeshellarg($logfile) . "{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
574
		}
575
	}
576
	echo "\n";
577

    
578
	foreach ($logarr as $logent) {
579
			$logent = preg_split("/\s+/", $logent, 6);
580

    
581
			if ($withorig) {
582
					if(isset($config['system']['usefifolog'])) {
583
						$entry_date_time = htmlspecialchars(date("F j, Y, g:i a","" . $logent[1] . ""));
584
						$entry_text = htmlspecialchars($logent[5]);
585
					} else {
586
						$entry_date_time = htmlspecialchars(join(" ", array_slice($logent, 0, 3)));
587
						$entry_text = ($logent[3] ==  $config['system']['hostname']) ? "" : $logent[3] . " ";
588
						$entry_text .= htmlspecialchars($logent[4] . " " . $logent[5]);
589
					}
590
					echo "{$entry_date_time}";
591
					echo " " . "{$entry_text}"  . "\n";
592
			} else {
593
					echo htmlspecialchars($logent[5]) . "\n";
594
			}
595

    
596
	}
597
}
598

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

    
637
			} else {
638
					echo "<td class=\"listlr\" colspan=\"2\">" . htmlspecialchars($logent[5]) . "</td>\n";
639
			}
640
			echo "</tr>\n";
641
	}
642
}
643

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

    
665
/* Check if variable has changed, update and log if it has
666
 * returns true if var changed
667
 * varname = variable name in plain text
668
 * orig = original value
669
 * new = new value
670
 */
671
function update_if_changed($varname, & $orig, $new) {
672
	if (is_array($orig) && is_array($new)) {
673
		$a_diff = array_diff($orig, $new);
674
		foreach ($a_diff as $diff) {
675
			update_changedesc("removed {$varname}: \"{$diff}\"");
676
		}
677
		$a_diff = array_diff($new, $orig);
678
		foreach ($a_diff as $diff) {
679
			update_changedesc("added {$varname}: \"{$diff}\"");
680
		}
681
		$orig = $new;
682
		return true;
683

    
684
	} else {
685
		if ($orig != $new) {
686
			update_changedesc("{$varname}: \"{$orig}\" -> \"{$new}\"");
687
			$orig = $new;
688
			return true;
689
		}
690
	}
691
	return false;
692
}
693

    
694
function address_to_pconfig($adr, &$padr, &$pmask, &$pnot, &$pbeginport, &$pendport) {
695
	if (isset($adr['any']))
696
		$padr = "any";
697
	else if ($adr['network'])
698
		$padr = $adr['network'];
699
	else if ($adr['address']) {
700
		list($padr, $pmask) = explode("/", $adr['address']);
701
		if (!$pmask) {
702
			if (is_ipaddrv6($padr))
703
				$pmask = 128;
704
			else
705
				$pmask = 32;
706
		}
707
	}
708

    
709
	if (isset($adr['not']))
710
		$pnot = 1;
711
	else
712
		$pnot = 0;
713

    
714
	if ($adr['port']) {
715
		list($pbeginport, $pendport) = explode("-", $adr['port']);
716
		if (!$pendport)
717
			$pendport = $pbeginport;
718
	} else if (!is_alias($pbeginport) && !is_alias($pendport)) {
719
		$pbeginport = "any";
720
		$pendport = "any";
721
	}
722
}
723

    
724
function pconfig_to_address(&$adr, $padr, $pmask, $pnot=false, $pbeginport=0, $pendport=0) {
725
	$adr = array();
726

    
727
	if ($padr == "any")
728
		$adr['any'] = true;
729
	else if (is_specialnet($padr))
730
		$adr['network'] = $padr;
731
	else {
732
		$adr['address'] = $padr;
733
		if (is_ipaddrv6($padr)) {
734
			if ($pmask != 128)
735
				$adr['address'] .= "/" . $pmask;
736
		} else {
737
			if ($pmask != 32)
738
				$adr['address'] .= "/" . $pmask;
739
		}
740
	}
741

    
742
	if ($pnot)
743
		$adr['not'] = true;
744
	else
745
		unset($adr['not']);
746

    
747
	if (($pbeginport != 0) && ($pbeginport != "any")) {
748
		if ($pbeginport != $pendport)
749
			$adr['port'] = $pbeginport . "-" . $pendport;
750
		else
751
			$adr['port'] = $pbeginport;
752
	}
753

    
754
	if(is_alias($pbeginport)) {
755
		$adr['port'] = $pbeginport;
756
	}
757
}
758

    
759
function is_specialnet($net) {
760
	global $specialsrcdst;
761

    
762
	if(!$net)
763
		return false;
764
	if (in_array($net, $specialsrcdst))
765
		return true;
766
	else
767
		return false;
768
}
769

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

    
792
		echo "<div id=\"{$ta[2]}-deactive\" class=\"{$tabclass}-tabdeactive\" style=\"display:{$tabNonActive}; background-color:#777777; color:white; cursor: pointer;\" onclick=\"return changeTabDIV('{$ta[2]}')\">";
793
		echo "<b>&nbsp;&nbsp;&nbsp;{$ta[0]}";
794
		echo "&nbsp;&nbsp;&nbsp;</b>";
795
		echo "</div>";
796
	}
797

    
798
	echo "<script type=\"text/javascript\">";
799
	echo "\n//<![CDATA[\n";
800
	echo "NiftyCheck();\n";
801
	echo "Rounded(\"div.{$tabclass}-tabactive\",\"top\",\"#CCCCCC\",\"#EEEEEE\",\"smooth\");\n";
802
	echo "Rounded(\"div.{$tabclass}-tabdeactive\",\"top\",\"#CCCCCC\",\"#777777\",\"smooth\");\n";
803
	echo "//]]>\n";
804
	echo "</script>";
805
	echo "</div>";
806
}
807

    
808

    
809
// Return inline javascript file or CSS to minimizie
810
// request count going back to server.
811
function outputJavaScriptFileInline($javascript) {
812
	if(file_exists($javascript)) {
813
		echo "\n<script type=\"text/javascript\">\n";
814
		include($javascript);
815
		echo "\n</script>\n";
816
	} else {
817
		echo "\n\n<!-- Could not location file:  {$javascript} -->\n\n";
818
	}
819
}
820

    
821

    
822

    
823
function outputCSSPrintFileInline($css) {
824
	if(file_exists($css)) {
825
		echo "\n<style media=\"print\" type=\"text/css\">\n";
826
		include($css);
827
		echo "\n</style>\n";
828
	} else {
829
		echo "\n\n<!-- Could not location file:  {$css} -->\n\n";
830
	}
831
}
832

    
833

    
834
function outputCSSFileInline($css) {
835
	if(file_exists($css)) {
836
		echo "\n<style type=\"text/css\">\n";
837
		include($css);
838
		echo "\n</style>\n";
839
	} else {
840
		echo "\n\n<!-- Could not location file:  {$css} -->\n\n";
841
	}
842
}
843

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

    
888
function is_rfc2616_code($code) {
889
	global $rfc2616;
890
	if (isset($rfc2616[$code]))
891
		return true;
892
	else
893
		return false;
894
}
895

    
896
function print_rfc2616_select($tag, $current){
897
	global $rfc2616;
898

    
899
	/* Default to 200 OK if not set */
900
	if ($current == "")
901
		$current = 200;
902

    
903
	echo "<select id=\"{$tag}\" name=\"{$tag}\">\n";
904
	foreach($rfc2616 as $code => $message) {
905
		if ($code == $current) {
906
			$sel = " selected=\"selected\"";
907
		} else {
908
			$sel = "";
909
		}
910
		echo "<option value=\"{$code}\"{$sel}>{$message}</option>\n";
911
	}
912
	echo "</select>\n";
913
}
914

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

    
942
/****f* pfsense-utils/display_top_tabs
943
 * NAME
944
 *   display_top_tabs - display tabs with rounded edges
945
 * INPUTS
946
 *   $text	  - array of tabs
947
 * RESULT
948
 *   null
949
 ******/
950
function display_top_tabs(& $tab_array, $no_drop_down = false, $type = 'pills') {
951
	global $config;
952
	global $g;
953
	global $tab_array_indent;
954
	global $tab_array_space;
955
	global $tab_array_char_limit;
956

    
957
	/*  does the user have access to this tab?
958
	 *  master user has access to everything.
959
	 *  if the user does not have access, simply
960
	 *  unset the tab item.
961
	 */
962

    
963
	/* empty string code */
964
	if ($tab_array_indent == '') {
965
		$tab_array_indent = 0;
966
	}
967

    
968
	if ($tab_array_space == '') {
969
		$tab_array_space = 1;
970
	}
971

    
972
	if ($tab_array_char_limit == '') {
973
		$tab_array_char_limit = 92;
974
	}
975

    
976
	foreach ($tab_array as $tab_id => $ta){
977
		if(!isAllowedPage($ta[2]))
978
			unset ($tab_array[$tab_id]);
979
	}
980

    
981
	$tab_active_bg   = "#EEEEEE";
982
	$tab_inactive_bg = "#777777";
983
	$nifty_tabs_corners = "#FFF";
984
	$font_color = "white";
985

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

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

    
995
	// If the character count of the tab names is > 670
996
	// then show a select item dropdown menubox.
997
	if($tabcharcount > $tab_array_char_limit): ?>
998
		echo gettext("Currently viewing: ");
999
		echo "<select name=\"TabSelect\" onchange=\"tabs_will_go(this)\">\n";
1000
		foreach ($tab_array as $ta) {
1001
			if($ta[1]=="true")
1002
				$selected = " selected=\"selected\"";
1003
			else
1004
				$selected = "";
1005
			// Onclick in option will not work in some browser
1006
			// echo "<option onclick=\"document.location='{$ta[2]}';\"{$selected}>{$ta['0']}</option>\n";
1007
			echo "<option value=\"{$ta[2]}\"{$selected}>{$ta['0']}</option>\n";
1008
		}
1009
		echo "</select>\n<p>&nbsp;</p>";
1010
		echo "<script type=\"text/javascript\">";
1011
		echo "\n//<![CDATA[\n";
1012
		echo " function tabs_will_go(obj){ document.location = obj.value; }\n";
1013
		echo "//]]>\n";
1014
		echo "</script>";
1015
<? else: ?>
1016
	<ul class="nav nav-<?= $type ?>">
1017
		<?php foreach ($tab_array as $ta): ?>
1018
			<li role="presentation"<?=($ta[1] ? ' class="active"' : '')?>><a href="<?=$ta[2]?>"><?=$ta[0]?></a></li>
1019
		<?php endforeach; ?>
1020
	</ul>
1021
<?php endif;
1022
}
1023

    
1024
function add_package_tabs($tabgroup, & $tab_array) {
1025
	global $config, $g;
1026

    
1027
	if(!is_array($config['installedpackages']))
1028
		return;
1029
	if(!is_array($config['installedpackages']['tab']))
1030
		return;
1031

    
1032
	foreach($config['installedpackages']['tab'] as $tab) {
1033
		if ($tab['group'] !== $group)
1034
			continue;
1035
		$tab_entry = array();
1036
		if($tab['name']) {
1037
			$tab_entry[] = $tab['name'];
1038
			$tab_entry[] = false;
1039
			$tab_entry[] = $tab['url'];
1040
			$tab_array[] = $tab_entry;
1041
		}
1042
	}
1043
}
1044

    
1045
function alias_info_popup($alias_id){
1046
	global $config;
1047

    
1048
	if (!is_array($config['aliases']['alias'][$alias_id]))
1049
		return;
1050

    
1051
	$maxlength = 60;
1052
	$alias = $config['aliases']['alias'][$alias_id];
1053
	$content = "";
1054

    
1055
	if ($alias['url'])
1056
	{
1057
		// TODO: Change it when pf supports tables with ports
1058
		if ($alias['type'] == "urltable") {
1059
			exec("/sbin/pfctl -t {$alias['name']} -T show | wc -l", $total_entries);
1060
			$counter=preg_replace("/\D/","",$total_entries[0]);
1061
			exec("/sbin/pfctl -t {$alias['name']} -T show | head -10002", $alias_addresses);
1062
		} else {
1063
			$urlfn = alias_expand_urltable($alias['name']);
1064
			$alias_addresses = explode("\n", file_get_contents($urlfn));
1065
			$counter = count($alias_addresses);
1066
		}
1067

    
1068
		$content .= '<h5>'. $alias['url'] .'</h5><ul><li>'. implode('</li><li>', $alias_ports_address) .'</li></ul>';
1069

    
1070
		if ($counter > 10002)
1071
			$content .= '<i>'. gettext("listing only first 10k items") .'</i>';
1072
	}
1073
	else
1074
	{
1075
		$alias_addresses = explode (" ", $alias['address']);
1076
		$alias_details = explode ("||", $alias['detail']);
1077

    
1078
		$content .= '<ul><li>'. implode('</li><li>', $alias_addresses) .'</li></ul>';
1079
	}
1080

    
1081
	if (strlen($alias['descr']) >= $maxlength)
1082
		$alias['descr'] = substr($alias['descr'], 0, $maxlength) . '&hellip;';
1083

    
1084
	return $content;
1085
}
1086

    
1087
function rule_columns_with_alias($src, $srcport, $dst, $dstport){
1088
	global $config;
1089

    
1090
	if ($config['aliases']['alias'] == "" || !is_array($config['aliases']['alias']))
1091
		return;
1092

    
1093
	$columns = array();
1094
	foreach ($config['aliases']['alias'] as $alias_id => $alias_name){
1095
		if ($alias_name['name'] == $src)
1096
			$columns['src'] = $alias_id;
1097
		elseif ($alias_name['name'] == $srcport)
1098
			$columns['srcport'] = $alias_id;
1099
		elseif ($alias_name['name'] == $dst )
1100
			$columns['dst'] = $alias_id;
1101
		elseif ($alias_name['name'] == $dstport)
1102
			$columns['dstport'] = $alias_id;
1103

    
1104
		return $columns;
1105
	}
1106
}
1107

    
1108
function form_output_row($name, $label, $content){
1109
var_dump($content);die;
1110
?>
1111
<div class="form-group">
1112
	<label for="<?=$name?>" class="col-sm-2 control-label"><?=gettext($label); ?></label>
1113
	<div class="col-sm-10">
1114
		<?=$content?>
1115
	</div>
1116
</div>
1117
<?php
1118
}
1119

    
1120
$timezone = $config['system']['timezone'];
1121
if (!$timezone)
1122
	$timezone = "Etc/UTC";
1123

    
1124
date_default_timezone_set($timezone);
1125

    
1126
?>
(87-87/252)