Project

General

Profile

Download (23.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-2021 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 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 fa-save icon-embed-btn"></i>' + svtxt + '</button>' +
526
		'<button class="btn btn-info btn-sm" id="btncncsep"><i class="fa 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 fa-circle text-info icon-pointer"></i></a>' +
529
		'&nbsp;&nbsp;<a id="sepclrred" value="bg-danger"><i class="fa fa-circle text-danger icon-pointer"></i></a>' +
530
		'&nbsp;&nbsp;<a id="sepclrgreen" value="bg-success"><i class="fa fa-circle text-success icon-pointer"></i></a>' +
531
		'&nbsp;&nbsp;<a id="sepclrorange" value="bg-warning"><i class="fa 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 fa-trash 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

    
588
// Compose an input array containing the row #, color and text for each separator
589
function save_separators() {
590
	var row = 0;
591
	var sepinput;
592
	var sepnum = 0;
593

    
594
	$('#ruletable > tbody > tr').each(function() {
595
		if ($(this).hasClass('separator')) {
596
			seprow = $(this).next('tr').attr("id");
597
			if (seprow == undefined) {
598
				seprow = "fr" + row;
599
			}
600

    
601
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][row]" value="' + seprow + '"></input>';
602
			$('form').append(sepinput);
603
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][text]" value="' + escapeHtml($(this).find('td').text()) + '"></input>';
604
			$('form').append(sepinput);
605
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][color]" value="' + $(this).find('td').prop('class') + '"></input>';
606
			$('form').append(sepinput);
607
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][if]" value="' + iface + '"></input>';
608
			$('form').append(sepinput);
609
			sepnum++;
610
		} else {
611
			if ($(this).parent('tbody').hasClass('user-entries')) {
612
				row++;
613
			}
614
		}
615
	});
616
}
617

    
618
function reindex_rules(section) {
619
	var row = 0;
620

    
621
	section.find('tr').each(function() {
622
		if (this.id) {
623
			$(this).attr("id", "fr" + row);
624
			$(this).attr("onclick", "fr_toggle(" + row + ")")
625
			$(this).find('input:checkbox:first').each(function() {
626
				$(this).attr("id", "frc" + row);
627
				$(this).attr("onclick", "fr_toggle(" + row + ")");
628
			});
629

    
630
			row++;
631
		}
632
	});
633
}
634

    
635
function handle_colors() {
636
	$('[id^=sepclr]').prop("type", "button");
637

    
638
	$('[id^=sepclr]').click(function () {
639
		var color =	 $(this).attr('value');
640
		// Clear all the color classes
641
		$(this).parent('td').prop('class', '');
642
		$(this).parent('td').prev('td').prop('class', '');
643
		// Install our new color class
644
		$(this).parent('td').addClass(color);
645
		$(this).parent('td').prev('td').addClass(color);
646
		// Set the global color
647
		gColor = color;
648
	});
649
}
650

    
651
//JS equivalent to PHP htmlspecialchars()
652
function escapeHtml(text) {
653
	var map = {
654
		'&': '&amp;',
655
		'<': '&lt;',
656
		'>': '&gt;',
657
		'"': '&quot;',
658
		"'": '&#039;'
659
	};
660

    
661
	return text.replace(/[&<>"']/g, function(m) { return map[m]; });
662
}
663
// --------------------------------------------------------------------------------------------
664

    
665
// Select every option in the specified multiselect
666
function AllServers(id, selectAll) {
667
   for (i = 0; i < id.length; i++)	   {
668
	   id.eq(i).prop('selected', selectAll);
669
   }
670
}
671

    
672
// Move all selected options from one multiselect to another
673
function moveOptions(From, To)	{
674
	var len = From.length;
675
	var option;
676

    
677
	if (len > 0) {
678
		for (i=0; i<len; i++) {
679
			if (From.eq(i).is(':selected')) {
680
				option = From.eq(i).val();
681
				value  = From.eq(i).text();
682
				To.append(new Option(value, option));
683
				From.eq(i).remove();
684
			}
685
		}
686
	}
687
}
688

    
689
// ------------- Service start/stop/restart functions.
690
// If a start/stop/restart button is clicked, parse the button name and make a POST via AJAX
691
$('[id*=restartservice-], [id*=stopservice-], [id*=startservice-]').click(function(event) {
692
	var args = this.id.split('-');
693
	var action, name, mode_zone, id;
694

    
695
	if (args[0] == "openvpn") {
696
		action = args[1];
697
		name = args[0];
698
		mode_zone = args[2];
699
		id = args[3];
700
	} else if (args[0] == "captiveportal") {
701
		action = args[1];
702
		name = args[0];
703
		mode_zone = args[2];
704
		id = args[3];
705
	} else {
706
		action = args[0];
707
		args.shift();
708
		name = args.join('-');
709
	}
710

    
711
	$(this).children('i').removeClass().addClass('fa fa-cog fa-spin text-success');
712
	this.blur();
713

    
714
	ajaxRequest = $.ajax(
715
		{
716
			url: "/status_services.php",
717
			type: "post",
718
			data: {
719
				ajax: 		"ajax",
720
				mode: 		action,
721
				service: 	name,
722
				vpnmode: 	mode_zone,
723
				zone: 		mode_zone,
724
				id: 		id
725
			}
726
		}
727
	);
728

    
729
	// Once the AJAX call has returned, refresh the page to show the new service
730
	ajaxRequest.done(function (response, textStatus, jqXHR) {
731
		location.reload(true);
732
	});
733
});
734

    
735
// The scripts that follow are an EXPERIMENT in using jQuery/Javascript to automatically convert
736
// GET calls to POST calls
737
// Any anchor with the attribute "usepost" usses these functions.
738

    
739
// Any time an anchor is clicked and the "usepost" attibute is present, convert the href attribute
740
// to POST format, make a POST form and submit it
741

    
742
interceptGET();
743

    
744
function interceptGET() {
745
	$('a').click(function(e) {
746
		// Does the clicked anchor have the "usepost" attribute?
747
		var attr = $(this).attr('usepost');
748

    
749
		if (typeof attr !== typeof undefined && attr !== false) {
750
			// Automatically apply a confirmation dialog to "Delete" icons
751
			if (!($(this).hasClass('no-confirm')) && !($(this).hasClass('icon-embed-btn')) &&
752
			   ($(this).hasClass('fa-trash'))) {
753
				var msg = $.trim(this.textContent).toLowerCase();
754

    
755
				if (!msg)
756
					var msg = $.trim(this.value).toLowerCase();
757

    
758
				var q = 'Are you sure you wish to '+ msg +'?';
759

    
760
				if ($(this).attr('title') != undefined)
761
					q = 'Are you sure you wish to '+ $(this).attr('title').toLowerCase() + '?';
762

    
763
				if (!confirm(q)) {
764
					return false;
765
				}
766
			}
767

    
768
			var target = $(this).attr("href").split("?");
769

    
770
			postSubmit(get2post(target[1]),target[0]);
771
			return false;
772
		}
773
	});
774
}
775

    
776
// Convert a GET argument list such as ?name=fred&action=delete into an object of POST
777
// parameters such as {name : fred, action : delete}
778
function get2post(getargs) {
779
	var argdict = {};
780
	var argarray = getargs.split('&');
781

    
782
	argarray.forEach(function(arg) {
783
		arg = arg.split('=');
784
		argdict[arg[0]] = arg[1];
785
	});
786

    
787
	return argdict;
788
}
789

    
790
// Create a form, add, the POST data and submit it
791
function postSubmit(data, target) {
792
	var $form = $('<form>');
793

    
794
	for (var name in data) {
795
		$form.append(
796
			$("<input>")
797
				.attr("type", "hidden")
798
				.attr("name", name)
799
				.val(data[name])
800
		);
801
    }
802

    
803
	$form
804
		.attr("method", "POST")
805
		.attr("action", target)
806
		// The CSRF magic is required because we will be viewing the results of the POST
807
		.append(
808
			$("<input>")
809
				.attr("type", "hidden")
810
				.attr("name", "__csrf_magic")
811
				.val(csrfMagicToken)
812
		)
813
		.appendTo('body')
814
		.submit();
815
}
(2-2/4)