Project

General

Profile

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

    
23
// These helper functions are used on many/most UI pages to hide/show/disable/enable form elements where required
24

    
25
// Cause the input to be displayed as a required field by adding the element-required class to the label
26
function setRequired(id, req) {
27
	if (req)
28
		$('#' + id).parent().parent('div').find('span:first').addClass('element-required');
29
	else
30
		$('#' + id).parent().parent('div').find('span:first').removeClass('element-required');
31
}
32

    
33
// Hides the <div> in which the specified input element lives so that the input, its label and help text are hidden
34
function hideInput(id, hide) {
35
	if (hide)
36
		$('#' + id).parent().parent('div').addClass('hidden');
37
	else
38
		$('#' + id).parent().parent('div').removeClass('hidden');
39
}
40

    
41
// Hides the <div> in which the specified group input element lives so that the input,
42
// its label and help text are hidden
43
function hideGroupInput(id, hide) {
44
	if (hide)
45
		$('#' + id).parent('div').addClass('hidden');
46
	else
47
		$('#' + id).parent('div').removeClass('hidden');
48
}
49

    
50
function invisibleGroupInput(id, hide) {
51
	if (hide)
52
		$('#' + id).addClass('invisible');
53
	else
54
		$('#' + id).removeClass('invisible');
55
}
56

    
57
// Hides the <div> in which the specified checkbox lives so that the checkbox, its label and help text are hidden
58
function hideCheckbox(id, hide) {
59
	if (hide)
60
		$('#' + id).parent().parent().parent('div').addClass('hidden');
61
	else
62
		$('#' + id).parent().parent().parent('div').removeClass('hidden');
63
}
64

    
65
// Disables the specified input element
66
function disableInput(id, disable) {
67
	$('#' + id).prop("disabled", disable);
68
}
69

    
70
// Hides all elements of the specified class. This will usually be a section
71
function hideClass(s_class, hide) {
72
	if (hide)
73
		$('.' + s_class).hide();
74
	else
75
		$('.' + s_class).show();
76
}
77

    
78
function hideSelect(id, hide) {
79
	if (hide)
80
		$('#' + id).parent('div').parent('div').addClass('hidden');
81
	else
82
		$('#' + id).parent('div').parent('div').removeClass('hidden');
83
}
84

    
85
function hideMultiCheckbox(id, hide) {
86
	if (hide)
87
		$("[name=" + id + "]").parent().addClass('hidden');
88
	else
89
		$("[name=" + id + "]").parent().removeClass('hidden');
90
}
91

    
92
// Hides the <div> in which the specified IP address element lives so that the input, any mask selector, its label and help text are hidden
93
function hideIpAddress(id, hide) {
94
	if (hide)
95
		$('#' + id).parent().parent().parent('div').addClass('hidden');
96
	else
97
		$('#' + id).parent().parent().parent('div').removeClass('hidden');
98
}
99

    
100
// Hides all elements of the specified class belonging to a multiselect.
101
function hideMultiClass(s_class, hide) {
102
	if (hide)
103
		$('.' + s_class).parent().parent().hide();
104
	else
105
		$('.' + s_class).parent().parent().show();
106
}
107

    
108
// Hides div whose label contains the specified text. (Good for StaticText)
109
function hideLabel(text, hide) {
110

    
111
	var element = $('label:contains(' + text + ')');
112

    
113
	if (hide)
114
		element.parent('div').addClass('hidden');
115
	else
116
		element.parent('div').removeClass('hidden');
117
}
118

    
119
// Hides the '/' and the subnet mask of an Ip_Address/subnet_mask group
120
function hideMask(name, hide) {
121
	if (hide) {
122
		$('[id^=' + name + ']').hide();
123
		$('[id^=' + name + ']').prev('span').hide();
124
		$('[id^=' + name + ']').parent('div').removeClass('input-group');
125
	} else {
126
		$('[id^=' + name + ']').show();
127
		$('[id^=' + name + ']').prev('span').show();
128
		$('[id^=' + name + ']').parent('div').addClass('input-group');
129
	}
130
}
131

    
132
// Set the help text for a given input
133
function setHelpText(id, text) {
134
	$('#' + id).parent().parent('div').find('span:nth-child(2)').html(text);
135
}
136

    
137
// Toggle table row checkboxes and background colors on the pages that use sortable tables:
138
//	/usr/local/www/firewall_nat.php
139
//	/usr/local/www/firewall_nat_1to1.php
140
//	/usr/local/www/firewall_nat_out.php
141
//	/usr/local/www/firewall_rules.php
142
//	/usr/local/www/vpn_ipsec.php
143
// Striping of the tables is handled here, NOT with the Bootstrap table-striped class because it would
144
// get confused when rows are sorted or deleted.
145

    
146
function fr_toggle(id, prefix) {
147
	if (!prefix)
148
		prefix = 'fr';
149

    
150
	var checkbox = document.getElementById(prefix + 'c' + id);
151
	checkbox.checked = !checkbox.checked;
152
	fr_bgcolor(id, prefix);
153
}
154

    
155
// Change background color of selected row based on state of checkbox
156
function fr_bgcolor(id, prefix) {
157
	if (!prefix)
158
		prefix = 'fr';
159

    
160
	var row = $('#' + prefix + id);
161

    
162
	if ($('#' + prefix + 'c' + id).prop('checked') ) {
163
		row.addClass('active');
164
	} else {
165
		row.removeClass('active');
166
	}
167
}
168

    
169
// The following functions are used by Form_Groups assigned a class of "repeatable" and provide the ability
170
// to add/delete rows of sequentially numbered elements, their labels and their help text
171
// See firewall_aliases_edit.php for an example
172

    
173
// NOTE: retainhelp is a global var that when defined prevents any help text from being deleted as lines are inserted.
174
// IOW it causes every row to have help text, not just the last row
175

    
176
function setMasks() {
177
	// Find all ipaddress masks and make dynamic based on address family of input
178
	$('span.pfIpMask + select').each(function (idx, select){
179
		var input = $(select).prevAll('input[type=text]');
180

    
181
		input.on('change', function(e){
182
			var isV6 = (input.val().indexOf(':') != -1), min = 0, max = 128;
183
			if (!isV6)
184
				max = 32;
185

    
186
			if (input.val() == "")
187
				return;
188

    
189
			// Sometimes the mask includes '0' (e.g. for VPNs), sometimes it does not
190
			if (select.options[select.options.length - 1].value == 0) {
191
				var mm = max + 1;
192
			} else {
193
				var mm = max;
194
			}
195

    
196
			while (select.options.length > mm)
197
				select.remove(0);
198

    
199
			if (select.options.length < max) {
200
				for (var i=select.options.length; i<=max; i++)
201
					select.options.add(new Option(i, i), 0);
202
			}
203
		});
204

    
205
		// Fire immediately
206
		input.change();
207
	});
208
}
209

    
210
// Complicated function to move all help text associated with this input id to the same id
211
// on the row above. That way if you delete the last row, you don't lose the help
212
function moveHelpText(id) {
213

    
214
	$('#' + id).parent('div').parent('div').find('input, select, checkbox, button').each(function() {	 // For each <span></span>
215
		var fromId = this.id;
216
		var toId = decrStringInt(fromId);
217
		var helpSpan;
218

    
219

    
220
		if (!$(this).hasClass('pfIpMask') && !$(this).hasClass('btn')) {
221
			if ($('#' + decrStringInt(fromId)).parent('div').hasClass('input-group')) {
222
				helpSpan = $('#' + fromId).parent('div').parent('div').find('span:last').clone();
223
			} else {
224
				helpSpan = $('#' + fromId).parent('div').find('span:last').clone();
225
			}
226

    
227
			if ($(helpSpan).hasClass('help-block')) {
228
				if ($('#' + decrStringInt(fromId)).parent('div').hasClass('input-group')) {
229
					$('#' + decrStringInt(fromId)).parent('div').after(helpSpan);
230
				} else {
231
					$('#' + decrStringInt(fromId)).after(helpSpan);
232
				}
233
			}
234
		}
235
	});
236
}
237

    
238
// Increment the number at the end of the string
239
function getStringInt( str )	{
240
  var data = str.match(/(\D*)(\d+)(\D*)/), newStr = "";
241
  return Number( data[ 2 ] );
242
}
243

    
244
// Increment the number at the end of the string
245
function bumpStringInt( str )	{
246
  var data = str.match(/(\D*)(\d+)(\D*)/), newStr = "";
247

    
248
  if (data)
249
	newStr = data[ 1 ] + ( Number( data[ 2 ] ) + 1 ) + data[ 3 ];
250

    
251
  return newStr || str;
252
}
253

    
254
// Decrement the number at the end of the string
255
function decrStringInt( str )	{
256
  var data = str.match(/(\D*)(\d+)(\D*)/), newStr = "";
257

    
258
  if (data)
259
	newStr = data[ 1 ] + ( Number( data[ 2 ] ) - 1 ) + data[ 3 ];
260

    
261
  return newStr || str;
262
}
263

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

    
269
	$('.repeatable').each(function() {
270

    
271
		$(this).find('input').each(function() {
272
			$(this).prop("id", this.id.replace(/\d+$/, "") + idx);
273
			$(this).prop("name", this.name.replace(/\d+$/, "") + idx);
274
		});
275

    
276
		$(this).find('select').each(function() {
277
			$(this).prop("id", this.id.replace(/\d+$/, "") + idx);
278
			$(this).prop("name", this.name.replace(/\d+$/, "") + idx);
279
		});
280

    
281
		$(this).find('button').each(function() {
282
			$(this).prop("id", this.id.replace(/\d+$/, "") + idx);
283
			$(this).prop("name", this.name.replace(/\d+$/, "") + idx);
284
		});
285

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

    
288
		idx++;
289
	});
290
}
291

    
292
function delete_row(rowDelBtn) {
293
	var rowLabel;
294

    
295
	// If we are deleting row zero, we need to save/restore the label
296
	if ( (rowDelBtn == "deleterow0") && ((typeof retainhelp) == "undefined")) {
297
		rowLabel = $('#' + rowDelBtn).parent('div').parent('div').find('label:first').text();
298
	}
299

    
300
	$('#' + rowDelBtn).parent('div').parent('div').remove();
301

    
302
	renumber();
303
	checkLastRow();
304

    
305
	if (rowDelBtn == "deleterow0") {
306
		$('#' + rowDelBtn).parent('div').parent('div').find('label:first').text(rowLabel);
307
	}
308
}
309

    
310
function checkLastRow() {
311
	if (($('.repeatable').length <= 1) && (! $('#deleterow0').hasClass("nowarn"))) {
312
		$('#deleterow0').hide();
313
	} else {
314
		$('[id^=deleterow]').show();
315
	}
316
}
317

    
318
function bump_input_id(newGroup) {
319
	$(newGroup).find('input').each(function() {
320
		$(this).prop("id", bumpStringInt(this.id));
321
		$(this).prop("name", bumpStringInt(this.name));
322
		if (!$(this).is('[id^=delete]'))
323
			$(this).val('');
324
	});
325

    
326
	// Increment the suffix number for the deleterow button element in the new group
327
	$(newGroup).find('[id^=deleterow]').each(function() {
328
		$(this).prop("id", bumpStringInt(this.id));
329
		$(this).prop("name", bumpStringInt(this.name));
330
	});
331

    
332
	// Do the same for selectors
333
	$(newGroup).find('select').each(function() {
334
		$(this).prop("id", bumpStringInt(this.id));
335
		$(this).prop("name", bumpStringInt(this.name));
336
		// If this selector lists mask bits, we need it to be reset to all 128 options
337
		// and no items selected, so that automatic v4/v6 selection still works
338
		if ($(this).is('[id^=address_subnet]')) {
339
			$(this).empty();
340
			for (idx=128; idx>=0; idx--) {
341
				$(this).append($('<option>', {
342
					value: idx,
343
					text: idx
344
				}));
345
			}
346
		}
347
	});
348
}
349
function add_row() {
350
	// Find the last repeatable group
351
	var lastRepeatableGroup = $('.repeatable:last');
352

    
353
	// If the number of repeats exceeds the maximum, do not add another clone
354
	if ($('.repeatable').length >= lastRepeatableGroup.attr('max_repeats')) {
355
		// Alert user if alert message is specified
356
		if (typeof lastRepeatableGroup.attr('max_repeats_alert') !== 'undefined') {
357
			alert(lastRepeatableGroup.attr('max_repeats_alert'));
358
		}
359
		return;
360
	}
361

    
362
	// Clone it
363
	var newGroup = lastRepeatableGroup.clone();
364

    
365
	// Increment the suffix number for each input element in the new group
366
	bump_input_id(newGroup);
367

    
368
	// And for "for" tags
369
//	$(newGroup).find('label').attr('for', bumpStringInt($(newGroup).find('label').attr('for')));
370

    
371
	$(newGroup).find('label:first').text(""); // Clear the label. We only want it on the very first row
372

    
373
	// Insert the updated/cloned row
374
	$(lastRepeatableGroup).after(newGroup);
375

    
376
	// Delete any help text from the group we have cloned
377
	$(lastRepeatableGroup).find('.help-block').each(function() {
378
		if ((typeof retainhelp) == "undefined")
379
			$(this).remove();
380
	});
381

    
382
	setMasks();
383

    
384
	checkLastRow();
385

    
386
	// Autocomplete
387
	if ( typeof addressarray !== 'undefined') {
388
		$('[id^=address]').each(function() {
389
			if (this.id.substring(0, 8) != "address_") {
390
				$(this).autocomplete({
391
					source: addressarray
392
				});
393
			}
394
		});
395
	}
396

    
397
	// Now that we are no longer cloning the event handlers, we need to remove and re-add after a new row
398
	// has been added to the table
399
	$('[id^=delete]').unbind();
400
	$('[id^=delete]').click(function(event) {
401
		if ($('.repeatable').length > 1) {
402
			if ((typeof retainhelp) == "undefined")
403
				moveHelpText($(this).attr("id"));
404

    
405
			delete_row($(this).attr("id"));
406
		} else if ($(this).hasClass("nowarn")) {
407
			clearRow0();
408
		} else {
409
			alert('The last row may not be deleted.');
410
		}
411
	});
412
}
413

    
414
// These are action buttons, not submit buttons
415
$('[id^=addrow]').prop('type','button');
416
$('[id^=delete]').prop('type','button');
417

    
418
// on click . .
419
$('[id^=addrow]').click(function() {
420
	add_row();
421
});
422

    
423
$('[id^=delete]').click(function(event) {
424
	if ($('.repeatable').length > 1) {
425
		if ((typeof retainhelp) == "undefined")
426
			moveHelpText($(this).attr("id"));
427

    
428
		delete_row($(this).attr("id"));
429
		} else if ($(this).hasClass("nowarn")) {
430
			clearRow0();
431
		} else {
432
			alert('The last row may not be deleted.');
433
		}
434
});
435

    
436
function clearRow0() {
437
	$('#deleterow0').parent('div').parent().find('input[type=text]').val('');
438
	$('#deleterow0').parent('div').parent().find('input[type=checkbox]:checked').removeAttr('checked');
439
}
440

    
441
// "More information" handlers --------------------------------------------------------------------
442

    
443
// If there is an infoblock, automatically add an info icon that toggles its display
444

    
445
var sfx = 0;
446

    
447
$('.infoblock').each(function() {
448
	// If the block has the class "blockopen" it is initially open
449
	if (! $(this).hasClass("blockopen")) {
450
		$(this).hide();
451
	} else {
452
		$(this).removeClass("blockopen");
453
	}
454

    
455
	// Add the "i" icon before the infoblock, incrementing the icon id for each block (in case there are multiple infoblocks on a page)
456
	$(this).before('<i class="fa-solid fa-info-circle icon-pointer" style="color: #337AB7; font-size:20px; margin-left: 10px; margin-bottom: 10px;" id="showinfo' + sfx.toString() + '" title="More information"></i>');
457
	$(this).removeClass("infoblock");
458
	$(this).addClass("infoblock" + sfx.toString());
459
	sfx++;
460
});
461

    
462
// Show the help on clicking the info icon
463
$('[id^="showinfo"]').click(function() {
464
	var id = $(this).attr("id");
465
	$('.' + "infoblock" + id.substr(8)).toggle();
466
	document.getSelection().removeAllRanges();		// Ensure the text is un-selected (Chrome browser quirk)
467
});
468
// ------------------------------------------------------------------------------------------------
469

    
470
// Put a dummy row into any empty table to keep IE happy
471
// Commented out due to https://redmine.pfsense.org/issues/7504
472
//$('tbody').each(function(){
473
//	$(this).html($.trim($(this).html()))
474
//});
475

    
476
$('tbody:empty').html("<tr><td></td></tr>");
477

    
478
// Hide configuration button for panels without configuration
479
$('.container .panel-heading a.config').each(function (idx, el){
480
	var config = $(el).parents('.panel').children('.panel-footer');
481
	if (config.length == 1)
482
		$(el).removeClass('hidden');
483
});
484

    
485
// Initial state & toggle icons of collapsed panel
486
$('.container .panel-heading a[data-toggle="collapse"]').each(function (idx, el){
487
	// Avoid modifying configuration button
488
	if ($(el).hasClass('config')) {
489
		return true;
490
	}
491
	var body = $(el).parents('.panel').children('.panel-body')
492
	var isOpen = body.hasClass('in');
493

    
494
	$(el).children('i').toggleClass('fa-plus-circle', !isOpen);
495
	$(el).children('i').toggleClass('fa-minus-circle', isOpen);
496

    
497
	body.on('shown.bs.collapse', function(){
498
		$(el).children('i').toggleClass('fa-minus-circle', true);
499
		$(el).children('i').toggleClass('fa-plus-circle', false);
500
	});
501

    
502
	body.on('hidden.bs.collapse', function(){
503
		$(el).children('i').toggleClass('fa-minus-circle', false);
504
		$(el).children('i').toggleClass('fa-plus-circle', true);
505
	});
506
});
507

    
508
// Separator bar stuff ------------------------------------------------------------------------
509

    
510
// Globals
511
gColor = 'bg-info';
512
newSeparator = false;
513
saving = false;
514
dirty = false;
515

    
516
$("#addsep").prop('type' ,'button');
517

    
518
$("#addsep").click(function() {
519
	if (newSeparator) {
520
		return(false);
521
	}
522

    
523
	gColor = 'bg-info';
524
	// Insert a temporary bar in which the user can enter some optional text
525
	sepcols = $( "#ruletable tr th" ).length - 2;
526

    
527
	$('#ruletable > tbody:last').append('<tr>' +
528
		'<td class="' + gColor + '" colspan="' + sepcols + '"><input id="newsep" placeholder="' + svbtnplaceholder + '" class="col-md-12" type="text" /></td>' +
529
		'<td class="' + gColor + '" colspan="2"><button class="btn btn-primary btn-sm" id="btnnewsep"><i class="fa-solid fa-save icon-embed-btn"></i>' + svtxt + '</button>' +
530
		'<button class="btn btn-info btn-sm" id="btncncsep"><i class="fa-solid fa-undo icon-embed-btn"></i>' + cncltxt + '</button>' +
531
		'&nbsp;&nbsp;&nbsp;&nbsp;' +
532
		'&nbsp;&nbsp;<a id="sepclrblue" value="bg-info"><i class="fa-solid fa-circle text-info icon-pointer"></i></a>' +
533
		'&nbsp;&nbsp;<a id="sepclrred" value="bg-danger"><i class="fa-solid fa-circle text-danger icon-pointer"></i></a>' +
534
		'&nbsp;&nbsp;<a id="sepclrgreen" value="bg-success"><i class="fa-solid fa-circle text-success icon-pointer"></i></a>' +
535
		'&nbsp;&nbsp;<a id="sepclrorange" value="bg-warning"><i class="fa-solid fa-circle text-warning icon-pointer"></i></button>' +
536
		'</td></tr>');
537

    
538
	$('#newsep').focus();
539
	newSeparator = true;
540

    
541
	$("#btnnewsep").prop('type' ,'button');
542

    
543
	// Watch escape and enter keys
544
	$('#newsep').keyup(function(e) {
545
		if (e.which == 27) {
546
			$('#btncncsep').trigger('click');
547
		}
548
	});
549

    
550
	$('#newsep').keypress(function(e) {
551
		if (e.which == 13) {
552
			$('#btnnewsep').trigger('click');
553
		}
554
	});
555

    
556
	handle_colors();
557

    
558
	// Replace the temporary separator bar with the final version containing the
559
	// user's text and a delete icon
560
	$("#btnnewsep").click(function() {
561
		var septext = escapeHtml($('#newsep').val());
562
		sepcols = $( "#ruletable tr th" ).length - 1;
563

    
564
		$(this).parents('tr').replaceWith('<tr class="ui-sortable-handle separator">' +
565
			'<td class="' + gColor + '" colspan="' + sepcols + '">' + '<span class="' + gColor + '">' + septext + '</span></td>' +
566
			'<td class="' + gColor + '"><a href="#"><i class="fa-solid fa-trash-can sepdel"></i></a>' +
567
			'</td></tr>');
568

    
569
		$('#order-store').removeAttr('disabled');
570
		newSeparator = false;
571
		dirty = true;
572
	});
573

    
574
	// Cancel button
575
	$('#btncncsep').click(function(e) {
576
		e.preventDefault();
577
		$(this).parents('tr').remove();
578
		newSeparator = false;
579
	});
580
});
581

    
582
// Delete a separator row
583
$(function(){
584
	$('table').on('click','tr a .sepdel',function(e){
585
		e.preventDefault();
586
		$(this).parents('tr').remove();
587
		$('#order-store').removeAttr('disabled');
588
		dirty = true;
589
	});
590

    
591
	// IPsec status page and widget actions
592
	$(document).on('click', '[id*=ipsecstatus-]', function(event) {
593
		// Parse out arguments from id
594
		var args = this.id.split('-');
595
		var act = args[1];
596
		var ipsectype = args[2];
597
		var conid = args[3];
598
		if (args[4] == 'mobile') {
599
			conid += '-mobile';
600
			args.shift();
601
		}
602
		var uniqueid;
603
		if (args.length > 4) {
604
			uniqueid = args[4];
605
		} else {
606
			uniqueid = '';
607
		}
608
		// Prompt to confirm only on disconnect
609
		if (($(this).hasClass('fa-trash-can')) || ($(this).children('i').hasClass('fa-trash-can'))) {
610
			var msg = $.trim(this.title) + ' ' + $.trim(conid);
611
			if (!msg) {
612
				msg = 'Confirm?';
613
			} else {
614
				msg = msg + '?';
615
			}
616
			if (!confirm(msg)) {
617
				return false;
618
			}
619
		}
620
		// Change to icon to show it is working
621
		$(this).children('i').removeClass().addClass('fa-solid fa-cog fa-spin text-success');
622
		this.blur();
623
		// POST request to handle the (dis)connect request
624
		ajaxRequest = $.ajax(
625
			{
626
				url: "/status_ipsec.php",
627
				type: "post",
628
				data: {
629
					ajax:		"ajax",
630
					act:		act,
631
					type:		ipsectype,
632
					conid:		conid,
633
					uniqueid:	uniqueid
634
				}
635
			}
636
		);
637
		// Once the AJAX call has returned, clear the icon. Will automatically be replaced when widget refreshes.
638
		ajaxRequest.done(function (response, textStatus, jqXHR) {
639
			$(this).children('i').removeClass();
640
		});
641
		// Stop the browser from adding # to the URL after clicking the link
642
		event.preventDefault();
643
	});
644
});
645

    
646
// Compose an input array containing the row #, color and text for each separator
647
function save_separators() {
648
	var row = 0;
649
	var sepinput;
650
	var sepnum = 0;
651

    
652
	$('#ruletable > tbody > tr').each(function() {
653
		if ($(this).hasClass('separator')) {
654
			seprow = $(this).next('tr').attr("id");
655
			if (seprow == undefined) {
656
				seprow = "fr" + row;
657
			}
658

    
659
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][row]" value="' + seprow + '"></input>';
660
			$('form').append(sepinput);
661
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][text]" value="' + escapeHtml($(this).find('td').text()) + '"></input>';
662
			$('form').append(sepinput);
663
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][color]" value="' + $(this).find('td').prop('class') + '"></input>';
664
			$('form').append(sepinput);
665
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][if]" value="' + iface + '"></input>';
666
			$('form').append(sepinput);
667
			sepnum++;
668
		} else {
669
			if ($(this).parent('tbody').hasClass('user-entries')) {
670
				row++;
671
			}
672
		}
673
	});
674
}
675

    
676
function reindex_rules(section) {
677
	var row = 0;
678

    
679
	section.find('tr').each(function() {
680
		if (this.id) {
681
			$(this).attr("id", "fr" + row);
682
			$(this).attr("onclick", "fr_toggle(" + row + ")")
683
			$(this).find('input:checkbox:first').each(function() {
684
				$(this).attr("id", "frc" + row);
685
				$(this).attr("onclick", "fr_toggle(" + row + ")");
686
			});
687

    
688
			row++;
689
		}
690
	});
691
}
692

    
693
function handle_colors() {
694
	$('[id^=sepclr]').prop("type", "button");
695

    
696
	$('[id^=sepclr]').click(function () {
697
		var color =	 $(this).attr('value');
698
		// Clear all the color classes
699
		$(this).parent('td').prop('class', '');
700
		$(this).parent('td').prev('td').prop('class', '');
701
		// Install our new color class
702
		$(this).parent('td').addClass(color);
703
		$(this).parent('td').prev('td').addClass(color);
704
		// Set the global color
705
		gColor = color;
706
	});
707
}
708

    
709
//JS equivalent to PHP htmlspecialchars()
710
function escapeHtml(text) {
711
	var map = {
712
		'&': '&amp;',
713
		'<': '&lt;',
714
		'>': '&gt;',
715
		'"': '&quot;',
716
		"'": '&#039;'
717
	};
718

    
719
	return text.replace(/[&<>"']/g, function(m) { return map[m]; });
720
}
721
// --------------------------------------------------------------------------------------------
722

    
723
// Select every option in the specified multiselect
724
function AllServers(id, selectAll) {
725
   for (i = 0; i < id.length; i++)	   {
726
	   id.eq(i).prop('selected', selectAll);
727
   }
728
}
729

    
730
// Move all selected options from one multiselect to another
731
function moveOptions(From, To)	{
732
	var len = From.length;
733
	var option;
734

    
735
	if (len > 0) {
736
		for (i=0; i<len; i++) {
737
			if (From.eq(i).is(':selected')) {
738
				option = From.eq(i).val();
739
				value  = From.eq(i).text();
740
				To.append(new Option(value, option));
741
				From.eq(i).remove();
742
			}
743
		}
744
	}
745
}
746

    
747
// ------------- Service start/stop/restart functions.
748
// If a start/stop/restart button is clicked, parse the button name and make a POST via AJAX
749
$('[id*=restartservice-], [id*=stopservice-], [id*=startservice-]').click(function(event) {
750
	var args = this.id.split('-');
751
	var action, name, mode_zone, id;
752

    
753
	if (args[0] == "openvpn") {
754
		action = args[1];
755
		name = args[0];
756
		mode_zone = args[2];
757
		id = args[3];
758
	} else if (args[0] == "captiveportal") {
759
		action = args[1];
760
		name = args[0];
761
		mode_zone = args[2];
762
		id = args[3];
763
	} else {
764
		action = args[0];
765
		args.shift();
766
		name = args.join('-');
767
	}
768

    
769
	$(this).children('i').removeClass().addClass('fa-solid fa-cog fa-spin text-success');
770
	this.blur();
771

    
772
	ajaxRequest = $.ajax(
773
		{
774
			url: "/status_services.php",
775
			type: "post",
776
			data: {
777
				ajax: 		"ajax",
778
				mode: 		action,
779
				service: 	name,
780
				vpnmode: 	mode_zone,
781
				zone: 		mode_zone,
782
				id: 		id
783
			}
784
		}
785
	);
786

    
787
	// Once the AJAX call has returned, refresh the page to show the new service
788
	ajaxRequest.done(function (response, textStatus, jqXHR) {
789
		location.reload(true);
790
	});
791
});
792

    
793
// The scripts that follow are an EXPERIMENT in using jQuery/JavaScript to automatically convert
794
// GET calls to POST calls
795
// Any anchor with the attribute "usepost" usses these functions.
796

    
797
// Any time an anchor is clicked and the "usepost" attribute is present, convert the href attribute
798
// to POST format, make a POST form and submit it
799

    
800
interceptGET();
801

    
802
function interceptGET() {
803
	$('a').click(function(e) {
804
		// Does the clicked anchor have the "usepost" attribute?
805
		var attr = $(this).attr('usepost');
806

    
807
		if (typeof attr !== typeof undefined && attr !== false) {
808
			// Automatically apply a confirmation dialog to "Delete" icons
809
			if (!($(this).hasClass('no-confirm')) && !($(this).hasClass('icon-embed-btn')) &&
810
			   (($(this).hasClass('do-confirm')) || ($(this).hasClass('fa-trash-can')))) {
811
				var msg = $.trim(this.textContent).toLowerCase();
812

    
813
				if (!msg)
814
					var msg = $.trim(this.value).toLowerCase();
815

    
816
				var q = 'Are you sure you wish to '+ msg +'?';
817

    
818
				if ($(this).attr('title') != undefined)
819
					q = 'Are you sure you wish to '+ $(this).attr('title').toLowerCase() + '?';
820

    
821
				if (!confirm(q)) {
822
					return false;
823
				}
824
			}
825

    
826
			var target = $(this).attr("href").split("?");
827

    
828
			// the usepost attribute value is prepended to the POST action URI
829
			postSubmit(get2post(target[1]),target[0].concat(attr));
830
			return false;
831
		}
832
	});
833
}
834

    
835
// Convert a GET argument list such as ?name=fred&action=delete into an object of POST
836
// parameters such as {name : fred, action : delete}
837
function get2post(getargs) {
838
	var argdict = {};
839
	var argarray = getargs.split('&');
840

    
841
	argarray.forEach(function(arg) {
842
		arg = arg.split('=');
843
		argdict[arg[0]] = arg[1];
844
	});
845

    
846
	return argdict;
847
}
848

    
849
// Create a form, add, the POST data and submit it
850
function postSubmit(data, target) {
851
	var $form = $('<form>');
852

    
853
	for (var name in data) {
854
		$form.append(
855
			$("<input>")
856
				.attr("type", "hidden")
857
				.attr("name", name)
858
				.val(data[name])
859
		);
860
    }
861

    
862
	$form
863
		.attr("method", "POST")
864
		.attr("action", target)
865
		// The CSRF magic is required because we will be viewing the results of the POST
866
		.append(
867
			$("<input>")
868
				.attr("type", "hidden")
869
				.attr("name", "__csrf_magic")
870
				.val(csrfMagicToken)
871
		)
872
		.appendTo('body')
873
		.submit();
874
}
875

    
876
function buttonsmode(tag, buttons) {
877
	var buttonsdisable = true;
878
	$('[id^=' + tag + ']').each(function () {
879
		if ($(this).prop("checked")) {
880
			buttonsdisable = false;
881
		}
882
	});
883
	for (let button in buttons) {
884
		$('#' + button).prop('disabled', buttonsdisable);
885
	}
886
	buttons.forEach(function(button) {
887
		$('#' + button).prop('disabled', buttonsdisable);
888
	})
889
}
890

    
891
$('input.autotrim').on('change', function () {
892
	$(this).val($(this).val().replace(/\s/g, ''));
893
});
894

    
895
function arraysEqual(arr1, arr2) {
896
	if (arr1.length !== arr2.length) {
897
		return false;
898
	}
899

    
900
	var sortedArr1 = arr1.slice().sort();
901
	var sortedArr2 = arr2.slice().sort();
902

    
903
	for (var i = 0; i < sortedArr1.length; i++) {
904
		if (sortedArr1[i] !== sortedArr2[i]) {
905
			return false;
906
		}
907
	}
908
	return true;
909
}
(2-2/4)