Menu="Disk Share"
Title="NFS Security Settings"
Tag="linux"
Cond="(($var['shareNFSEnabled']!='no') && (isset($name)?array_key_exists($name,$sec_nfs)&&($shares[$name]['hasCfg']??false)!='similar':0))"
---
<?PHP
/* Copyright 2005-2023, Lime Technology
 * Copyright 2012-2023, Bergware International.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */

$width = [123,300];
/* Replace spaces in NFS rule with new lines for multi line textarea. */
$sec_nfs[$name]['hostList']	= str_replace(" ", "\n", $sec_nfs[$name]['hostList']);
?>
:nfs_security_help:

<div markdown="1" class="relative">
<div markdown="1" class="clone-settings shade">
_(Read settings from)_ <i class="fa fa-arrow-left fa-fw"></i>
: <span class="flex flex-row items-center gap-4">
	<select name="readnfs" onchange="toggleButton('readnfs',false)">
		<option disabled selected>_(select)_...</option>
		<?
		if (isset($disks[$name])) {
		  foreach (array_filter($disks,'clone_list') as $list) if ($list['name']!=$name) echo mk_option("", $list['name'], _(my_disk($list['name']),3));
		} else {
		  foreach ($shares as $list) if (strpos($list['name'],"'") === false && $list['name']!=$name) echo mk_option("", $list['name'], compress($list['name']));
		}
		?>
	</select>
	<span class="buttons-spaced">
		<input type="button" id="readnfs" value="_(Read)_" class="clone" onclick="readNFS()" disabled>
	</span>
</span>

_(Write settings to)_ <i class="fa fa-arrow-right fa-fw"></i>
: <span class="flex flex-row items-center gap-4">
	<select id="nfs1" name="writenfs" multiple onchange="toggleButton('writenfs',this.id)">
		<?
		$rows = [];
		if (isset($disks[$name])) {
		  foreach (array_filter($disks,'clone_list') as $list) if ($list['name']!=$name) $rows[] = mk_option("", $list['name'], _(my_disk($list['name']),3));
		} else {
		  foreach ($shares as $list) if (strpos($list['name'],"'") === false && $list['name']!=$name) $rows[] = mk_option("", $list['name'], compress($list['name']));
		}
		if ($rows) echo "<option>("._('All').")</option>";
		foreach ($rows as $row) echo $row;
		?>
	</select>
	<span class="buttons-spaced">
		<input type="button" id="writenfs" value="_(Write)_" class="clone" onclick="writeNFS()" disabled>
	</span>
</span>
</div>

<div markdown="1" class="shade">
<form markdown="1" name="nfs_edit" method="POST" action="/update.htm" target="progressFrame" onchange="toggleButton('writenfs',true);$('#nfs1').dropdownchecklist('disable')">
<input type="hidden" name="shareName" value="<?=htmlspecialchars($name)?>">

_(Share name)_:
: <?=htmlspecialchars($name)?>

_(Export)_:
: <select name="shareExportNFS">
  <?=mk_option($sec_nfs[$name]['export'], "-", _('No'));?>
  <?=mk_option($sec_nfs[$name]['export'], "e", _('Yes'));?>
  </select>

_(Security)_:
: <select name="shareSecurityNFS">
  <?=mk_option($sec_nfs[$name]['security'], "public", _('Public'));?>
  <?=mk_option($sec_nfs[$name]['security'], "secure", _('Secure'));?>
  <?=mk_option($sec_nfs[$name]['security'], "private", _('Private'));?>
  </select>

&nbsp;
: <span class="buttons-spaced">
	<input type="submit" name="changeShareSecurityNFS" value="_(Apply)_" disabled>
	<input type="button" value="_(Done)_" onclick="done()">
  </span>
</form>

<?if ($sec_nfs[$name]['security']=='private'):?>
<form class="shade" id="nfsHostListForm" markdown="1" method="POST" name="otherForm" action="/update.htm" target="progressFrame">
<input type="hidden" name="shareName" value="<?=htmlspecialchars($name)?>">

_(Rule)_:
: <textarea name="shareHostListNFS" cols="40" rows="5" style="width:45%" placeholder="Example: *(rw,sec=sys,insecure,anongid=100,anonuid=99,no_root_squash,lock)"><?= htmlspecialchars($sec_nfs[$name]['hostList']) ?></textarea>

:nfs_security_rules_help:

&nbsp;
: <span class="buttons-spaced">
	<input type="submit" name="changeShareAccessNFS" value="_(Apply)_" disabled>
	<input type="button" value="_(Done)_" onclick="done()">
  </span>
</form>
<?endif;?>
</div>
</div>

<script>
$(function() {
	/* Initialize dropdown for NFS and check for hostList cookie. */
	initDropdownNFS(false);

	if ($.cookie('hostList') != null) {
		var host = $('textarea[name="shareHostListNFS"]');
		if (host.length) {
			host.val($.cookie('hostList'));
			setTimeout(function() {
				host.trigger('change');
			}, 100);
		}
		$.removeCookie('hostList');
	}

	/* Add submit listener to nfsHostListForm if it exists */
	var form = document.getElementById('nfsHostListForm');
	if (form) {
		form.addEventListener('submit', function(event) {
			var textarea = document.querySelector('textarea[name="shareHostListNFS"]');
			if (textarea) {
				var lines = textarea.value.split('\n');
				var cleanedLines = lines.map(function(line) {
					return line.replace(/[\r\s]+/g, '');
				}).filter(function(line) {
					return line.length > 0;
				});
				textarea.value = cleanedLines.join(' ');
			}
		});
	}

	/* Conditionally bind click event to tabs */
	<?if ($tabbed):?>
	$('#tab<?= $path == 'Shares/Share' ? 2 : 1 ?>').on('click', function() {
		initDropdownNFS(true);
	});
	<?endif;?>
});

/* Function to initialize or reset the NFS dropdown */
function initDropdownNFS(reset) {
	/* Check if reset is required and destroy existing dropdown if true */
	if (reset) {
		$('#nfs1').dropdownchecklist('destroy');
	}
	/* Initialize or re-initialize the dropdown with specified options */
	$("#nfs1").dropdownchecklist({
		firstItemChecksAll: true,
		emptyText: "_(select)_...",
		width: <?=$width[0]?>,
		explicitClose: "..._(close)_"
	});
}

/* Function to read NFS configuration based on selected options and copy to this share. */
function readNFS() {
	/* Access the form for NFS editing */
	var form = document.nfs_edit;

	/* Retrieve selected NFS name from the dropdown */
	var name = $('select[name="readnfs"]').val();

	/* Perform a GET request to fetch NFS configuration data */
	$.get('/webGui/include/ProtocolData.php', {protocol: 'nfs', name: name}, function(json) {
		/* Parse the JSON response */
		var data = $.parseJSON(json);
		var textarea = $('textarea[name="shareHostListNFS"]');

		/* Update form fields with fetched data */
		form.shareExportNFS.value = data.export;
		form.shareSecurityNFS.value = data.security;

		/* Check if hostList is not empty and save it in a cookie */
		if (data.hostList != '') {
			$.cookie('hostList', data.hostList);
		}

        /* Replace all spaces in data.hostList with new lines. */
        var formattedHostList = data.hostList.replace(/ /g, '\n');

		/* Update textarea content. Use data from 'hostList'. */
		textarea.val(formattedHostList);

		/* Trigger change event on select elements to update UI */
		$(form).find('select').trigger('change');

	    /* Trigger an input event as if the user had typed in the textarea. */
	    textarea.trigger('input');
	});
}

/* Function to write NFS settings based on user selection to other shares. */
function writeNFS(data, n, i) {
	if (data) {
		if (n < i) {
			$.post('/update.htm', data[n], function() {
				setTimeout(function() { writeNFS(data, ++n, i); }, 3000);
			});
		} else {
		  toggleButton('writenfs', false);
		  $('div.spinner.fixed').hide();
		}
	} else {
		var data = [];

		/* Get the setting from the share config. */
		var hostList = $('textarea[name="shareHostListNFS"]').val().trim();

		/* Replace all new lines in data.hostList with spaces. */
		var formattedHostList = <?= json_encode($sec_nfs[$name]['hostList']); ?>.replace(/\n/g, ' ');

		$('select#nfs1 option').each(function() {
			if ($(this).prop('selected') && $(this).val() != '(_(All)_)') {
				data.push({
				  shareName: $(this).val(),
				  shareExportNFS: '<?=addslashes(htmlspecialchars($sec_nfs[$name]['export']))?>',
				  shareSecurityNFS: '<?=addslashes(htmlspecialchars($sec_nfs[$name]['security']))?>',
				  changeShareSecurityNFS: 'Apply'
				});

				data.push({
					shareName: $(this).val(),
					shareHostListNFS: formattedHostList,
					changeShareSecurityNFS: 'Apply'
				});
			}
		});
		toggleButton('writenfs', true);
		$('div.spinner.fixed').show('slow');
		writeNFS(data, 0, data.length);
	}
}
</script>
