Project

General

Profile

Download (25.9 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
	var body = $(el).parents('.panel').children('.panel-body')
488
	var isOpen = body.hasClass('in');
489

    
490
	$(el).children('i').toggleClass('fa-plus-circle', !isOpen);
491
	$(el).children('i').toggleClass('fa-minus-circle', isOpen);
492

    
493
	body.on('shown.bs.collapse', function(){
494
		$(el).children('i').toggleClass('fa-minus-circle', true);
495
		$(el).children('i').toggleClass('fa-plus-circle', false);
496
	});
497

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

    
504
// Separator bar stuff ------------------------------------------------------------------------
505

    
506
// Globals
507
gColor = 'bg-info';
508
newSeparator = false;
509
saving = false;
510
dirty = false;
511

    
512
$("#addsep").prop('type' ,'button');
513

    
514
$("#addsep").click(function() {
515
	if (newSeparator) {
516
		return(false);
517
	}
518

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

    
523
	$('#ruletable > tbody:last').append('<tr>' +
524
		'<td class="' + gColor + '" colspan="' + sepcols + '"><input id="newsep" placeholder="' + svbtnplaceholder + '" class="col-md-12" type="text" /></td>' +
525
		'<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>' +
526
		'<button class="btn btn-info btn-sm" id="btncncsep"><i class="fa-solid fa-undo icon-embed-btn"></i>' + cncltxt + '</button>' +
527
		'&nbsp;&nbsp;&nbsp;&nbsp;' +
528
		'&nbsp;&nbsp;<a id="sepclrblue" value="bg-info"><i class="fa-solid fa-circle text-info icon-pointer"></i></a>' +
529
		'&nbsp;&nbsp;<a id="sepclrred" value="bg-danger"><i class="fa-solid fa-circle text-danger icon-pointer"></i></a>' +
530
		'&nbsp;&nbsp;<a id="sepclrgreen" value="bg-success"><i class="fa-solid fa-circle text-success icon-pointer"></i></a>' +
531
		'&nbsp;&nbsp;<a id="sepclrorange" value="bg-warning"><i class="fa-solid fa-circle text-warning icon-pointer"></i></button>' +
532
		'</td></tr>');
533

    
534
	$('#newsep').focus();
535
	newSeparator = true;
536

    
537
	$("#btnnewsep").prop('type' ,'button');
538

    
539
	// Watch escape and enter keys
540
	$('#newsep').keyup(function(e) {
541
		if (e.which == 27) {
542
			$('#btncncsep').trigger('click');
543
		}
544
	});
545

    
546
	$('#newsep').keypress(function(e) {
547
		if (e.which == 13) {
548
			$('#btnnewsep').trigger('click');
549
		}
550
	});
551

    
552
	handle_colors();
553

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

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

    
565
		$('#order-store').removeAttr('disabled');
566
		newSeparator = false;
567
		dirty = true;
568
	});
569

    
570
	// Cancel button
571
	$('#btncncsep').click(function(e) {
572
		e.preventDefault();
573
		$(this).parents('tr').remove();
574
		newSeparator = false;
575
	});
576
});
577

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

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

    
642
// Compose an input array containing the row #, color and text for each separator
643
function save_separators() {
644
	var row = 0;
645
	var sepinput;
646
	var sepnum = 0;
647

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

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

    
672
function reindex_rules(section) {
673
	var row = 0;
674

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

    
684
			row++;
685
		}
686
	});
687
}
688

    
689
function handle_colors() {
690
	$('[id^=sepclr]').prop("type", "button");
691

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

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

    
715
	return text.replace(/[&<>"']/g, function(m) { return map[m]; });
716
}
717
// --------------------------------------------------------------------------------------------
718

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

    
726
// Move all selected options from one multiselect to another
727
function moveOptions(From, To)	{
728
	var len = From.length;
729
	var option;
730

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

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

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

    
765
	$(this).children('i').removeClass().addClass('fa-solid fa-cog fa-spin text-success');
766
	this.blur();
767

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

    
783
	// Once the AJAX call has returned, refresh the page to show the new service
784
	ajaxRequest.done(function (response, textStatus, jqXHR) {
785
		location.reload(true);
786
	});
787
});
788

    
789
// The scripts that follow are an EXPERIMENT in using jQuery/JavaScript to automatically convert
790
// GET calls to POST calls
791
// Any anchor with the attribute "usepost" usses these functions.
792

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

    
796
interceptGET();
797

    
798
function interceptGET() {
799
	$('a').click(function(e) {
800
		// Does the clicked anchor have the "usepost" attribute?
801
		var attr = $(this).attr('usepost');
802

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

    
809
				if (!msg)
810
					var msg = $.trim(this.value).toLowerCase();
811

    
812
				var q = 'Are you sure you wish to '+ msg +'?';
813

    
814
				if ($(this).attr('title') != undefined)
815
					q = 'Are you sure you wish to '+ $(this).attr('title').toLowerCase() + '?';
816

    
817
				if (!confirm(q)) {
818
					return false;
819
				}
820
			}
821

    
822
			var target = $(this).attr("href").split("?");
823

    
824
			// the usepost attribute value is prepended to the POST action URI
825
			postSubmit(get2post(target[1]),target[0].concat(attr));
826
			return false;
827
		}
828
	});
829
}
830

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

    
837
	argarray.forEach(function(arg) {
838
		arg = arg.split('=');
839
		argdict[arg[0]] = arg[1];
840
	});
841

    
842
	return argdict;
843
}
844

    
845
// Create a form, add, the POST data and submit it
846
function postSubmit(data, target) {
847
	var $form = $('<form>');
848

    
849
	for (var name in data) {
850
		$form.append(
851
			$("<input>")
852
				.attr("type", "hidden")
853
				.attr("name", name)
854
				.val(data[name])
855
		);
856
    }
857

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

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

    
887
$('input.autotrim').on('change', function () {
888
	$(this).val($(this).val().replace(/\s/g, ''));
889
});
(2-2/4)