Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

    
90
// 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
91
function hideIpAddress(id, hide) {
92
	if (hide)
93
		$('#' + id).parent().parent().parent('div').addClass('hidden');
94
	else
95
		$('#' + id).parent().parent().parent('div').removeClass('hidden');
96
}
97

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

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

    
109
	var element = $('label:contains(' + text + ')');
110

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

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

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

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

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

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

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

    
158
	var row = $('#' + prefix + id);
159

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

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

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

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

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

    
184
			if (input.val() == "")
185
				return;
186

    
187
			while (select.options.length > max)
188
				select.remove(0);
189

    
190
			if (select.options.length < max) {
191
				for (var i=select.options.length; i<=max; i++)
192
					select.options.add(new Option(i, i), 0);
193
			}
194
		});
195

    
196
		// Fire immediately
197
		input.change();
198
	});
199
}
200

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

    
205
	$('#' + id).parent('div').parent('div').find('input, select, checkbox, button').each(function() {	 // For each <span></span>
206
		var fromId = this.id;
207
		var toId = decrStringInt(fromId);
208
		var helpSpan;
209

    
210

    
211
		if (!$(this).hasClass('pfIpMask') && !$(this).hasClass('btn')) {
212
			if ($('#' + decrStringInt(fromId)).parent('div').hasClass('input-group')) {
213
				helpSpan = $('#' + fromId).parent('div').parent('div').find('span:last').clone();
214
			} else {
215
				helpSpan = $('#' + fromId).parent('div').find('span:last').clone();
216
			}
217

    
218
			if ($(helpSpan).hasClass('help-block')) {
219
				if ($('#' + decrStringInt(fromId)).parent('div').hasClass('input-group')) {
220
					$('#' + decrStringInt(fromId)).parent('div').after(helpSpan);
221
				} else {
222
					$('#' + decrStringInt(fromId)).after(helpSpan);
223
				}
224
			}
225
		}
226
	});
227
}
228

    
229
// Increment the number at the end of the string
230
function getStringInt( str )	{
231
  var data = str.match(/(\D*)(\d+)(\D*)/), newStr = "";
232
  return Number( data[ 2 ] );
233
}
234

    
235
// Increment the number at the end of the string
236
function bumpStringInt( str )	{
237
  var data = str.match(/(\D*)(\d+)(\D*)/), newStr = "";
238

    
239
  if (data)
240
	newStr = data[ 1 ] + ( Number( data[ 2 ] ) + 1 ) + data[ 3 ];
241

    
242
  return newStr || str;
243
}
244

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

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

    
252
  return newStr || str;
253
}
254

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

    
260
	$('.repeatable').each(function() {
261

    
262
		$(this).find('input').each(function() {
263
			$(this).prop("id", this.id.replace(/\d+$/, "") + idx);
264
			$(this).prop("name", this.name.replace(/\d+$/, "") + idx);
265
		});
266

    
267
		$(this).find('select').each(function() {
268
			$(this).prop("id", this.id.replace(/\d+$/, "") + idx);
269
			$(this).prop("name", this.name.replace(/\d+$/, "") + idx);
270
		});
271

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

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

    
279
		idx++;
280
	});
281
}
282

    
283
function delete_row(rowDelBtn) {
284
	var rowLabel;
285

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

    
291
	$('#' + rowDelBtn).parent('div').parent('div').remove();
292

    
293
	renumber();
294
	checkLastRow();
295

    
296
	if (rowDelBtn == "deleterow0") {
297
		$('#' + rowDelBtn).parent('div').parent('div').find('label:first').text(rowLabel);
298
	}
299
}
300

    
301
function checkLastRow() {
302
	if (($('.repeatable').length <= 1) && (! $('#deleterow0').hasClass("nowarn"))) {
303
		$('#deleterow0').hide();
304
	} else {
305
		$('[id^=deleterow]').show();
306
	}
307
}
308

    
309
function bump_input_id(newGroup) {
310
	$(newGroup).find('input').each(function() {
311
		$(this).prop("id", bumpStringInt(this.id));
312
		$(this).prop("name", bumpStringInt(this.name));
313
		if (!$(this).is('[id^=delete]'))
314
			$(this).val('');
315
	});
316

    
317
	// Increment the suffix number for the deleterow button element in the new group
318
	$(newGroup).find('[id^=deleterow]').each(function() {
319
		$(this).prop("id", bumpStringInt(this.id));
320
		$(this).prop("name", bumpStringInt(this.name));
321
	});
322

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

    
344
	// If the number of repeats exceeds the maximum, do not add another clone
345
	if ($('.repeatable').length >= lastRepeatableGroup.attr('max_repeats')) {
346
		// Alert user if alert message is specified
347
		if (typeof lastRepeatableGroup.attr('max_repeats_alert') !== 'undefined') {
348
			alert(lastRepeatableGroup.attr('max_repeats_alert'));
349
		}
350
		return;
351
	}
352

    
353
	// Clone it
354
	var newGroup = lastRepeatableGroup.clone();
355

    
356
	// Increment the suffix number for each input element in the new group
357
	bump_input_id(newGroup);
358

    
359
	// And for "for" tags
360
//	$(newGroup).find('label').attr('for', bumpStringInt($(newGroup).find('label').attr('for')));
361

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

    
364
	// Insert the updated/cloned row
365
	$(lastRepeatableGroup).after(newGroup);
366

    
367
	// Delete any help text from the group we have cloned
368
	$(lastRepeatableGroup).find('.help-block').each(function() {
369
		if ((typeof retainhelp) == "undefined")
370
			$(this).remove();
371
	});
372

    
373
	setMasks();
374

    
375
	checkLastRow();
376

    
377
	// Autocomplete
378
	if ( typeof addressarray !== 'undefined') {
379
		$('[id^=address]').each(function() {
380
			if (this.id.substring(0, 8) != "address_") {
381
				$(this).autocomplete({
382
					source: addressarray
383
				});
384
			}
385
		});
386
	}
387

    
388
	// Now that we are no longer cloning the event handlers, we need to remove and re-add after a new row
389
	// has been added to the table
390
	$('[id^=delete]').unbind();
391
	$('[id^=delete]').click(function(event) {
392
		if ($('.repeatable').length > 1) {
393
			if ((typeof retainhelp) == "undefined")
394
				moveHelpText($(this).attr("id"));
395

    
396
			delete_row($(this).attr("id"));
397
		} else if ($(this).hasClass("nowarn")) {
398
			clearRow0();
399
		} else {
400
			alert('The last row may not be deleted.');
401
		}
402
	});
403
}
404

    
405
// These are action buttons, not submit buttons
406
$('[id^=addrow]').prop('type','button');
407
$('[id^=delete]').prop('type','button');
408

    
409
// on click . .
410
$('[id^=addrow]').click(function() {
411
	add_row();
412
});
413

    
414
$('[id^=delete]').click(function(event) {
415
	if ($('.repeatable').length > 1) {
416
		if ((typeof retainhelp) == "undefined")
417
			moveHelpText($(this).attr("id"));
418

    
419
		delete_row($(this).attr("id"));
420
		} else if ($(this).hasClass("nowarn")) {
421
			clearRow0();
422
		} else {
423
			alert('The last row may not be deleted.');
424
		}
425
});
426

    
427
function clearRow0() {
428
	$('#deleterow0').parent('div').parent().find('input[type=text]').val('');
429
	$('#deleterow0').parent('div').parent().find('input[type=checkbox]:checked').removeAttr('checked');
430
}
431

    
432
// "More information" handlers --------------------------------------------------------------------
433

    
434
// If there is an infoblock, automatically add an info icon that toggles its display
435

    
436
var sfx = 0;
437

    
438
$('.infoblock').each(function() {
439
	// If the block has the class "blockopen" it is initially open
440
	if (! $(this).hasClass("blockopen")) {
441
		$(this).hide();
442
	} else {
443
		$(this).removeClass("blockopen");
444
	}
445

    
446
	// Add the "i" icon before the infoblock, incrementing the icon id for each block (in case there are multiple infoblocks on a page)
447
	$(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>');
448
	$(this).removeClass("infoblock");
449
	$(this).addClass("infoblock" + sfx.toString());
450
	sfx++;
451
});
452

    
453
// Show the help on clicking the info icon
454
$('[id^="showinfo"]').click(function() {
455
	var id = $(this).attr("id");
456
	$('.' + "infoblock" + id.substr(8)).toggle();
457
	document.getSelection().removeAllRanges();		// Ensure the text is un-selected (Chrome browser quirk)
458
});
459
// ------------------------------------------------------------------------------------------------
460

    
461
// Put a dummy row into any empty table to keep IE happy
462
// Commented out due to https://redmine.pfsense.org/issues/7504
463
//$('tbody').each(function(){
464
//	$(this).html($.trim($(this).html()))
465
//});
466

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

    
469
// Hide configuration button for panels without configuration
470
$('.container .panel-heading a.config').each(function (idx, el){
471
	var config = $(el).parents('.panel').children('.panel-footer');
472
	if (config.length == 1)
473
		$(el).removeClass('hidden');
474
});
475

    
476
// Initial state & toggle icons of collapsed panel
477
$('.container .panel-heading a[data-toggle="collapse"]').each(function (idx, el){
478
	var body = $(el).parents('.panel').children('.panel-body')
479
	var isOpen = body.hasClass('in');
480

    
481
	$(el).children('i').toggleClass('fa-plus-circle', !isOpen);
482
	$(el).children('i').toggleClass('fa-minus-circle', isOpen);
483

    
484
	body.on('shown.bs.collapse', function(){
485
		$(el).children('i').toggleClass('fa-minus-circle', true);
486
		$(el).children('i').toggleClass('fa-plus-circle', false);
487
	});
488

    
489
	body.on('hidden.bs.collapse', function(){
490
		$(el).children('i').toggleClass('fa-minus-circle', false);
491
		$(el).children('i').toggleClass('fa-plus-circle', true);
492
	});
493
});
494

    
495
// Separator bar stuff ------------------------------------------------------------------------
496

    
497
// Globals
498
gColor = 'bg-info';
499
newSeparator = false;
500
saving = false;
501
dirty = false;
502

    
503
$("#addsep").prop('type' ,'button');
504

    
505
$("#addsep").click(function() {
506
	if (newSeparator) {
507
		return(false);
508
	}
509

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

    
514
	$('#ruletable > tbody:last').append('<tr>' +
515
		'<td class="' + gColor + '" colspan="' + sepcols + '"><input id="newsep" placeholder="' + svbtnplaceholder + '" class="col-md-12" type="text" /></td>' +
516
		'<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>' +
517
		'<button class="btn btn-info btn-sm" id="btncncsep"><i class="fa fa-undo icon-embed-btn"></i>' + cncltxt + '</button>' +
518
		'&nbsp;&nbsp;&nbsp;&nbsp;' +
519
		'&nbsp;&nbsp;<a id="sepclrblue" value="bg-info"><i class="fa fa-circle text-info icon-pointer"></i></a>' +
520
		'&nbsp;&nbsp;<a id="sepclrred" value="bg-danger"><i class="fa fa-circle text-danger icon-pointer"></i></a>' +
521
		'&nbsp;&nbsp;<a id="sepclrgreen" value="bg-success"><i class="fa fa-circle text-success icon-pointer"></i></a>' +
522
		'&nbsp;&nbsp;<a id="sepclrorange" value="bg-warning"><i class="fa fa-circle text-warning icon-pointer"></i></button>' +
523
		'</td></tr>');
524

    
525
	$('#newsep').focus();
526
	newSeparator = true;
527

    
528
	$("#btnnewsep").prop('type' ,'button');
529

    
530
	// Watch escape and enter keys
531
	$('#newsep').keyup(function(e) {
532
		if (e.which == 27) {
533
			$('#btncncsep').trigger('click');
534
		}
535
	});
536

    
537
	$('#newsep').keypress(function(e) {
538
		if (e.which == 13) {
539
			$('#btnnewsep').trigger('click');
540
		}
541
	});
542

    
543
	handle_colors();
544

    
545
	// Replace the temporary separator bar with the final version containing the
546
	// user's text and a delete icon
547
	$("#btnnewsep").click(function() {
548
		var septext = escapeHtml($('#newsep').val());
549
		sepcols = $( "#ruletable tr th" ).length - 1;
550

    
551
		$(this).parents('tr').replaceWith('<tr class="ui-sortable-handle separator">' +
552
			'<td class="' + gColor + '" colspan="' + sepcols + '">' + '<span class="' + gColor + '">' + septext + '</span></td>' +
553
			'<td class="' + gColor + '"><a href="#"><i class="fa fa-trash sepdel"></i></a>' +
554
			'</td></tr>');
555

    
556
		$('#order-store').removeAttr('disabled');
557
		newSeparator = false;
558
		dirty = true;
559
	});
560

    
561
	// Cancel button
562
	$('#btncncsep').click(function(e) {
563
		e.preventDefault();
564
		$(this).parents('tr').remove();
565
		newSeparator = false;
566
	});
567
});
568

    
569
// Delete a separator row
570
$(function(){
571
	$('table').on('click','tr a .sepdel',function(e){
572
		e.preventDefault();
573
		$(this).parents('tr').remove();
574
		$('#order-store').removeAttr('disabled');
575
		dirty = true;
576
	});
577
});
578

    
579
// Compose an input array containing the row #, color and text for each separator
580
function save_separators() {
581
	var row = 0;
582
	var sepinput;
583
	var sepnum = 0;
584

    
585
	$('#ruletable > tbody > tr').each(function() {
586
		if ($(this).hasClass('separator')) {
587
			seprow = $(this).next('tr').attr("id");
588
			if (seprow == undefined) {
589
				seprow = "fr" + row;
590
			}
591

    
592
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][row]" value="' + seprow + '"></input>';
593
			$('form').append(sepinput);
594
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][text]" value="' + escapeHtml($(this).find('td').text()) + '"></input>';
595
			$('form').append(sepinput);
596
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][color]" value="' + $(this).find('td').prop('class') + '"></input>';
597
			$('form').append(sepinput);
598
			sepinput = '<input type="hidden" name="separator[' + sepnum + '][if]" value="' + iface + '"></input>';
599
			$('form').append(sepinput);
600
			sepnum++;
601
		} else {
602
			if ($(this).parent('tbody').hasClass('user-entries')) {
603
				row++;
604
			}
605
		}
606
	});
607
}
608

    
609
function reindex_rules(section) {
610
	var row = 0;
611

    
612
	section.find('tr').each(function() {
613
		if (this.id) {
614
			$(this).attr("id", "fr" + row);
615
			$(this).attr("onclick", "fr_toggle(" + row + ")")
616
			$(this).find('input:checkbox:first').each(function() {
617
				$(this).attr("id", "frc" + row);
618
				$(this).attr("onclick", "fr_toggle(" + row + ")");
619
			});
620

    
621
			row++;
622
		}
623
	});
624
}
625

    
626
function handle_colors() {
627
	$('[id^=sepclr]').prop("type", "button");
628

    
629
	$('[id^=sepclr]').click(function () {
630
		var color =	 $(this).attr('value');
631
		// Clear all the color classes
632
		$(this).parent('td').prop('class', '');
633
		$(this).parent('td').prev('td').prop('class', '');
634
		// Install our new color class
635
		$(this).parent('td').addClass(color);
636
		$(this).parent('td').prev('td').addClass(color);
637
		// Set the global color
638
		gColor = color;
639
	});
640
}
641

    
642
//JS equivalent to PHP htmlspecialchars()
643
function escapeHtml(text) {
644
	var map = {
645
		'&': '&amp;',
646
		'<': '&lt;',
647
		'>': '&gt;',
648
		'"': '&quot;',
649
		"'": '&#039;'
650
	};
651

    
652
	return text.replace(/[&<>"']/g, function(m) { return map[m]; });
653
}
654
// --------------------------------------------------------------------------------------------
655

    
656
// Select every option in the specified multiselect
657
function AllServers(id, selectAll) {
658
   for (i = 0; i < id.length; i++)	   {
659
	   id.eq(i).prop('selected', selectAll);
660
   }
661
}
662

    
663
// Move all selected options from one multiselect to another
664
function moveOptions(From, To)	{
665
	var len = From.length;
666
	var option;
667

    
668
	if (len > 0) {
669
		for (i=0; i<len; i++) {
670
			if (From.eq(i).is(':selected')) {
671
				option = From.eq(i).val();
672
				value  = From.eq(i).text();
673
				To.append(new Option(value, option));
674
				From.eq(i).remove();
675
			}
676
		}
677
	}
678
}
679

    
680
// ------------- Service start/stop/restart functions.
681
// If a start/stop/restart button is clicked, parse the button name and make a POST via AJAX
682
$('[id*=restartservice-], [id*=stopservice-], [id*=startservice-]').click(function(event) {
683
	var args = this.id.split('-');
684
	var action, name, mode_zone, id;
685

    
686
	if (args[0] == "openvpn") {
687
		action = args[1];
688
		name = args[0];
689
		mode_zone = args[2];
690
		id = args[3];
691
	} else if (args[0] == "captiveportal") {
692
		action = args[1];
693
		name = args[0];
694
		mode_zone = args[2];
695
		id = args[3];
696
	} else {
697
		action = args[0];
698
		args.shift();
699
		name = args.join('-');
700
	}
701

    
702
	$(this).children('i').removeClass().addClass('fa fa-cog fa-spin text-success');
703
	this.blur();
704

    
705
	ajaxRequest = $.ajax(
706
		{
707
			url: "/status_services.php",
708
			type: "post",
709
			data: {
710
				ajax: 		"ajax",
711
				mode: 		action,
712
				service: 	name,
713
				vpnmode: 	mode_zone,
714
				zone: 		mode_zone,
715
				id: 		id
716
			}
717
		}
718
	);
719

    
720
	// Once the AJAX call has returned, refresh the page to show the new service
721
	ajaxRequest.done(function (response, textStatus, jqXHR) {
722
		location.reload(true);
723
	});
724
});
725

    
726
// The scripts that follow are an EXPERIMENT in using jQuery/Javascript to automatically convert
727
// GET calls to POST calls
728
// Any anchor with the attribute "usepost" usses these functions.
729

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

    
733
interceptGET();
734

    
735
function interceptGET() {
736
	$('a').click(function(e) {
737
		// Does the clicked anchor have the "usepost" attribute?
738
		var attr = $(this).attr('usepost');
739

    
740
		if (typeof attr !== typeof undefined && attr !== false) {
741
			// Automatically apply a confirmation dialog to "Delete" icons
742
			if (!($(this).hasClass('no-confirm')) && !($(this).hasClass('icon-embed-btn')) &&
743
			   ($(this).hasClass('fa-trash'))) {
744
				var msg = $.trim(this.textContent).toLowerCase();
745

    
746
				if (!msg)
747
					var msg = $.trim(this.value).toLowerCase();
748

    
749
				var q = 'Are you sure you wish to '+ msg +'?';
750

    
751
				if ($(this).attr('title') != undefined)
752
					q = 'Are you sure you wish to '+ $(this).attr('title').toLowerCase() + '?';
753

    
754
				if (!confirm(q)) {
755
					return false;
756
				}
757
			}
758

    
759
			var target = $(this).attr("href").split("?");
760

    
761
			postSubmit(get2post(target[1]),target[0]);
762
			return false;
763
		}
764
	});
765
}
766

    
767
// Convert a GET argument list such as ?name=fred&action=delete into an object of POST
768
// parameters such as {name : fred, action : delete}
769
function get2post(getargs) {
770
	var argdict = {};
771
	var argarray = getargs.split('&');
772

    
773
	argarray.forEach(function(arg) {
774
		arg = arg.split('=');
775
		argdict[arg[0]] = arg[1];
776
	});
777

    
778
	return argdict;
779
}
780

    
781
// Create a form, add, the POST data and submit it
782
function postSubmit(data, target) {
783
	var $form = $('<form>');
784

    
785
	for (var name in data) {
786
		$form.append(
787
			$("<input>")
788
				.attr("type", "hidden")
789
				.attr("name", name)
790
				.val(data[name])
791
		);
792
    }
793

    
794
	$form
795
		.attr("method", "POST")
796
		.attr("action", target)
797
		// The CSRF magic is required because we will be viewing the results of the POST
798
		.append(
799
			$("<input>")
800
				.attr("type", "hidden")
801
				.attr("name", "__csrf_magic")
802
				.val(csrfMagicToken)
803
		)
804
		.appendTo('body')
805
		.submit();
806
}
(2-2/4)