<?php

//////////////////////////////////////////////////////////////
//===========================================================
// api_credential_create_theme.php
//===========================================================
// SOFTACULOUS VIRTUALIZOR
// Version : 1.0
// Inspired by the DESIRE to be the BEST OF ALL
// ----------------------------------------------------------
// Started by: Alons
// Date:	   8th Mar 2010
// Time:	   23:00 hrs
// Site:	   https://www.virtualizor.com/ (SOFTACULOUS VIRTUALIZOR)
// ----------------------------------------------------------
// Please Read the Terms of use at https://www.virtualizor.com
// ----------------------------------------------------------
//===========================================================
// (c)Softaculous Ltd.
//===========================================================
//////////////////////////////////////////////////////////////

if(!defined('VIRTUALIZOR')){

	die('Hacking Attempt');

}

function api_credential_create_theme(){

	global $cluster, $globals, $l, $fetched_api_data, $error, $api_create_acl_theme, $acls, $user;
	softheader($l['<title>']);
	
	$acl_langs = [
		'act_cat_admin_dash' => __('Admin Dashboard'),
		'act_cat_vs' => __('Virtual Server'),
		'act_cat_ippools' => __('IP Pools'),
		'act_cat_servers' => __('Servers and Server Groups'),
		'act_cat_storage' => __('Storages'),
		'act_cat_backups' => __('Server and VPS Backups'),
		'act_cat_plans' => __('Plans'),
		'act_cat_users' => __('Users'),
		'act_cat_media' => __('Media and Media Groups'),
		'act_cat_config' => __('Configuration'),
		'act_cat_pdns' => __('PowerDNS'),
		'act_cat_procs' => __('Process and Services'),
		'act_cat_logs' => __('Logs'),
		'act_cat_haproxy' => __('Domain Forwarding'),
		'act_cluster_statistics' => __('View Cluster Statistics'),
		'act_server_statistics' => __('View Server Statistics'),
		'act_vs' => __('List Virtual Server'),
		'act_vsresources' => __('View VPS Resources'),
		'act_addvs' => __('Add Virtual Server'),
		'act_rebuildvs' => __('Rebuild Virtual Server'),
		'act_editvs' => __('Edit Virtual Server'),
		'act_deletevs' => __('Delete Virtual Server'),
		'act_startvs' => __('Start Virtual Server'),
		'act_stopvs' => __('Stop Virtual Server'),
		'act_restartvs' => __('Restart Virtual Server'),
		'act_poweroffvs' => __('PowerOff Virtual Server'),
		'act_suspendvs' => __('Suspend Virtual Server'),
		'act_unsuspendvs' => __('Unsuspend Virtual Server'),
		'act_vnc' => __('Virtual Server. VNC'),
		'act_migrate' => __('Migrate Virtual Server'),
		'act_ippool' => __('View IP Pools'),
		'act_addippool' => __('Add IP Pool'),
		'act_editippool' => __('Edit IP Pool'),
		'act_deleteippool' => __('Delete IP Pool'),
		'act_ips' => __('View IPs'),
		'act_addips' => __('Add IPs'),
		'act_editips' => __('Edit IPs'),
		'act_deleteips' => __('Delete IPs'),
		'act_servers' => __('View Servers'),
		'act_addserver' => __('Add Server'),
		'act_editserver' => __('Edit Server'),
		'act_deleteserver' => __('Delete Server'),
		'act_sg' => __('View Server Groups'),
		'act_addsg' => __('Add Server Group'),
		'act_editsg' => __('Edit Server Group'),
		'act_deletesg' => __('Delete Server Group'),
		'act_rebootserver' => __('Reboot Server'),
		'act_manageserver' => __('Manage Server'),
		'act_terminal' => __('Terminal'),
		'act_support_access' => __('Support Access'),
		'act_storage' => __('View Storages'),
		'act_volumes' => __('Volumes'),
		'act_addstorage' => __('Add Storage'),
		'act_editstorage' => __('Edit Storage'),
		'act_deletestorage' => __('Delete Storage'),
		'act_databackup' => __('View DB Backups'),
		'act_performdatabackup' => __('Perform DB Backups'),
		'act_dldatabackup' => __('Download DB Backups'),
		'act_deletedatabackup' => __('Delete DB Backups'),
		'act_vpsbackupsettings' => __('Edit VPS Backup Settings'),
		'act_vpsbackups' => __('View VPS Backups'),
		'act_restorevpsbackup' => __('Restore VPS Backups'),
		'act_deletevpsbackup' => __('Delete VPS Backups'),
		'act_backupservers' => __('View Backup Servers'),
		'act_addbackupserver' => __('Add Backup Server'),
		'act_editbackupservsers' => __('Edit Backup Server'),
		'act_deletebackupserver' => __('Delete Backup Server'),
		'act_plans' => __('View Plans'),
		'act_addplan' => __('Add Plan'),
		'act_editplan' => __('Edit Plan'),
		'act_deleteplan' => __('Delete Plan'),
		'act_dnsplans' => __('View DNS Plans'),
		'act_adddnsplan' => __('Add DNS Plan'),
		'act_editdnsplan' => __('Edit DNS Plan'),
		'act_deletednsplan' => __('Delete DNS Plan'),
		'act_add_dnsrecord' => __('Add DNS Record'),
		'act_users' => __('View Users'),
		'act_adduser' => __('Add User'),
		'act_edituser' => __('Edit User'),
		'act_deleteuser' => __('Delete User'),
		'act_suspend_user' => __('Suspend User'),
		'act_unsuspend_user' => __('Unsuspend User'),
		'act_list_api' => __('List API Credential'),
		'act_create_api' => __('Create API Credential'),
		'act_api_credential_edit' => __('Edit API Credential'),
		'act_show_api_log' => __('API Logs'),
		'act_ostemplates' => __('View Templates'),
		'act_os' => __('View Template Browser'),
		'act_addtemplate' => __('Add Templates'),
		'act_edittemplate' => __('Edit templates'),
		'act_deletetemplate' => __('Delete Templates'),
		'act_createtemplate' => __('Create Templates'),
		'act_iso' => __('View ISO List'),
		'act_addiso' => __('Add ISOs'),
		'act_editiso' => __('Edit ISOs'),
		'act_deleteiso' => __('Delete ISOs'),
		'act_mg' => __('View Media Groups'),
		'act_addmg' => __('Add Media Groups'),
		'act_editmg' => __('Edit Media Groups'),
		'act_deletemg' => __('Delete Media Groups'),
		'act_list_distros' => __('View Distro List'),
		'act_add_distro' => __('Add Distros'),
		'act_synciso' => __('Sync ISO'),
		'act_config' => __('Edit General Settings'),
		'act_emailsettings' => __('Edit Email Settings'),
		'act_adminacl' => __('View Admin ACLs'),
		'act_add_admin_acl' => __('Add Admin ACL'),
		'act_edit_admin_acl' => __('Edit Admin ACL'),
		'act_delete_admin_acl' => __('Delete Admin ACL'),
		'act_serverinfo' => __('View Server Info'),
		'act_licenseinfo' => __('View License Info'),
		'act_hostname' => __('View Hostname'),
		'act_changehostname' => __('Edit Hostname'),
		'act_maintenance' => __('Maintenance Mode'),
		'act_kernconfig' => __('Edit Kernel Config'),
		'act_defaultvsconf' => __('Default VPS Config'),
		'act_twofactauth' => __('Two Factor Authentication'),
		'act_updates' => __('Perform Updates'),
		'act_emailtemps' => __('View email templates'),
		'act_editemailtemps' => __('Edit email templates'),
		'act_ssl' => __('View SSL files'),
		'act_editssl' => __('Edit SSL fIles'),
		'act_createssl' => __('Create SSL Certificate'),
		'act_importvs' => __('Import VS'),
		'act_phpmyadmin' => __(' Access PhpMyAdmin'),
		'act_ssh' => __('Access SSH'),
		'act_pdns' => __('View DNS Servers'),
		'act_managepdns' => __('Manage DNS Servers'),
		'act_addpdns' => __('Add DNS Servers'),
		'act_editpdns' => __('Edit DNS Server'),
		'act_deletepdns' => __('Delete DNS Servers'),
		'act_rdns' => __('Add Reverse DNS Zones'),
		'act_procs' => __('Manage processes'),
		'act_services' => __('Manage services'),
		'act_webserver' => __('Restart webserver'),
		'act_network' => __('Restart network service'),
		'act_sendmail' => __('Restart mail server'),
		'act_mysqld' => __('Restart MySQL'),
		'act_iptables' => __('Restart IPTables'),
		'act_logs' => __('View Logs'),
		'act_deletelogs' => __('Delete logs'),
		'act_userlogs' => __('View User logs'),
		'act_deleteuserlogs' => __('Delete User logs'),
		'act_loginlogs' => __('View Login logs'),
		'act_deleteloginlogs' => __('Delete login logs'),
		'act_iplogs' => __('View IP Logs'),
		'act_deliplogs' => __('Delete IP Logs'),
		'act_checkall' => __('Check all'),
		'act_save' => __('Save'),
		'cat_recipe' => __('Recipes'),
		'act_recipes' => __('View Recipes'),
		'act_addrecipe' => __('Add Recipe'),
		'act_editrecipe' => __('Edit Recipe'),
		'act_backup_plans' => __('List Backup Plans'),
		'act_addbackup_plan' => __('Add Backup Plan'),
		'act_editbackup_plan' => __('Edit Backup Plan'),
		'act_deletebackup_plan' => __('Delete Backup Plans'),
		'act_haproxy' => __('Domain Forwarding'),
		'act_euiso' => __('Enduser ISO'),
		'act_orphaneddisk' => __('List Orphaned Disks'),
		'act_deleteorphaneddisk' => __('Delete Orphaned Disks'),
		'act_ha' => __('High Availability'),
		'act_load_balancer' => __('Load Balancer'),
		'act_manage_load_balancer' => __('Manage Load Balancer'),
		'act_multivirt' => __('Multi Virtualization'),
		'act_webuzo' => __('Webuzo Settings'),
		'act_billing' => __('Billing Settings'),
		'act_resource_pricing' => __('Resource Billing'),
		'act_invoices' => __('Invoices'),
		'act_transactions' => __('Transactions'),
		'act_addinvoice' => __('Add Invoice'),
		'act_addtransaction' => __('Add Transaction'),
		'cat_admin_dash' => __('Admin Dashboard'),
		'cat_vs' => __('Virtual Server'),
		'cat_ippools' => __('IP Pools'),
		'cat_servers' => __('Servers and Server Groups'),
		'cat_storage' => __('Storages'),
		'cat_backups' => __('Server and VPS Backups'),
		'cat_plans' => __('Plans'),
		'cat_users' => __('Users'),
		'cat_media' => __('Media and Media Groups'),
		'cat_config' => __('Configuration'),
		'cat_pdns' => __('PowerDNS'),
		'cat_procs' => __('Process and Services'),
		'cat_logs' => __('Logs'),
		'cat_haproxy' => __('Domain Forwarding'),
		'cat_billing' => __('Billing'),
		'cat_vpsfirewall' => __('VPS Firewall'),
		'act_firewall_plans' => __('List Firewall Plans'),
		'act_addfirewall_plan' => __('Add Firewall Plan'),
		'act_editfirewall_plan' => __('Edit Firewall Plan'),
		'act_deletefirewall_plan' => __('Delete Firewall Plan'),
		'act_vpsfirewallconfig' => __('VPSFirewall Config'),
		'cat_passthrough' => __('Passthrough'),
		'act_passthrough' => __('View Passthough Devices'),
		'act_addpassthrough' => __('Add Passthrough'),
		'act_editpassthrough' => __('Edit Passthrough'),
		'act_deletepassthrough' => __('Delete Passthrough'),
		'cat_nodefirewall' => __('Node Firewall'),
		'act_serverfirewall_status' => __('Server Firewall Status'),
		'act_firewall' => __('Native firewall'),
	];

	$fetched_key = '';
	$fetched_value = '';
	error_handle($error);
		
	//r_print($api_create_acl_theme);
	echo '
	<script>

		$(document).ready(function(){
			'.(!empty($user['uid']) ? 'show_acl("'.$user['uid'].'")' : '').'
		});

		function validater(){
			var api_cred = $("#api_generator").serialize();
			if(!empty(api_cred)){
				$.ajax({
					url: "'.$globals['index'].'&act=create_api&api=json",
					data:api_cred+"&api_generator_submit=1",
					dataType : "json",
					method : "POST",
					success:function(data){
						
						if("error" in data) {
							setTimeout(function(){var error = "";
							error = "<ul>";
							for (var k in data["error"]) {
								error += "<li>"+data["error"][k]+"</li>"; 
							}
							error += "</ul>";
							showalert(\''.__J('Failed to generate api pair.').'\'+error ,"1");
							return;} ,200);
						}else{
							setTimeout(function(){
							showalert(\''.__J('API pair generated successfully! Return to <a href="index.php?act=list_api">List API Overview</a>').'\');
							return;} ,200);
						}
					}
				});	
			}
		}
		
	</script>
	<script>
		function show_all_info(uid){
			$("input:checkbox").prop("checked", false);
			$("[id^=cat_]").show();
			$(".col-sm-3.cb_state").slideDown();
			if(!empty(uid)){
				showalert("'.__J('No ACL record(s) found for this user!').'",2);
			}
			
		}
		function show_acl(uid){
			if(!empty(uid) && uid > 0){
				$("#progress_bar").fadeIn();
				$.ajax({
					type: "POST",
					url: "'.$globals['index'].'act=create_api&uid="+uid+"&api=json",
					dataType : "json",
					success:function(res){
						var acl_action = res["api_create_acl_theme"]["acl_actions"];
						if(empty(res["api_create_acl_theme"])){
							$("#unsupported").show();
							return false;
						}
						if(res["api_create_acl_theme"]["acl_state"] == "show_all"){
							show_all_info(uid);
						}else{
							$("input:checkbox").prop("checked", false);
							if(!empty(acl_action)){
								var actions = "";
								$(".col-sm-3.cb_state").hide();
								$("[id^=cat_]").hide();
								$.each(acl_action, function( acl_key , acl_value) {
									$("#"+acl_key+"_m").slideDown();
									$("#"+acl_key).prop("checked", true);
									$("#"+acl_key+"_m").parent().parent().parent().show();
								});
							}
						}
						displayer_true(uid);
						$("#progress_bar").fadeOut();
					}
				});
				
			}
			//Owner
			if(empty(uid)){
				show_all_info(uid);
			}

			if(uid < 0){
				$("input:checkbox").prop("checked", false);
				$("[id^=cat_]").hide();
			}

		}

		function displayer_true(uid){
			if(uid < 0){
			$("#action_field").slideUp();
			$("#ip_field").slideUp();
			$("#logging").slideUp();
			}else{
			$("#action_field").slideDown();
			$("#ip_field").slideDown();
			$("#logging").slideDown();
			}
		}

	</script>';

	$breadcrumb = ['list_api', 'create_api'];

	$GLOBALS['breadcrumbs'] = ['dashboard', 'lm_list_api', 'lms_create_api'];
	
	echo page_header(__('Create API Credential'), 'fas fa-laptop-code', '', 0, 0, '');

		if(empty($api_create_acl_theme['acl_state']) && !empty($user['uid'])){
			//No ACl permission given hence do not render anything
			echo '
				<div class="col-12" id="unsupported" style="display:none">
					<div class="notice"><b>Note : </b> &nbsp; '.__('You don\'t have the permission to create api pairs.').'</div>
				</div>
			';
			goto end_of_acl;
		}

		echo '
		<div class="card mx-3 mb-3">
			<div id="progress_bar" style="display:none;">
				<br/>
				<center>
					<font id="progress_txt" size="4">'.__('Please wait, Action in Progress.').'</font>
				</center>
				<div class="my-2" align="center">
					<div class="progress w-50">
						<div class="progress-bar bg-primary progress-bar-striped progress-bar-animated w-100">
						</div>
					</div>
				</div>
				<center>
					'.__('You will be notified once the Action is Completed.').'
				</center>
			</div>
			<form accept-charset="'.$globals['charset'].'" onsubmit="validater(); return false;" id = "api_generator" name="api_generator" method="post" action="" class="form-horizontal">';
			echo'<div class="row mx-auto my-3">';
				if(empty($user['uid'])){
					echo '
					<div class="col-sm-6">
						<label class="control-label">'.__('Select User').'&nbsp;</label>
						<select class="custom-select virt-select" name="user_uuid" id="user_uuid" onchange="show_acl(this.value); displayer_true(this.value);">
							<option value="-1" selected="selected">'.__('Select the user').'</option>
							<option value="0" '.(POSTselect('user_uuid', 0)).'>'.__('Yourself').'</option>';
								foreach($fetched_api_data as $fetched_key => $fetched_value){
									echo '
									<option value="'.$fetched_value['uid'].'" '.(POSTselect('user_uuid', $fetched_value['uid'])).'>'.$fetched_value['email'].'</option> ';
								}
						echo '
						</select>
					</div>';
				}
				echo'<div class="col-sm-6" id="ip_field" style="display:none">
					<label class="control-label">'.__('IP Address').'&nbsp;</label>
					<input type="text" class="form-control" id="ip_value" name="ip_value" value="'.POSTval('ip_value', '').'" size="30">
				</div>
				<div class="col-sm-6 mt-2" id="logging" style="display:none">
					<div class="row mx-auto">
						<div class="col-sm-6 p-0">
							<label class="control-label">'.__('Enable logging').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('When enabled, logs will be generated for this API Pair').'"><i class="fas text-primary fa-info-circle"></i></a></label>
						</div>
						<div class="col-sm-6 d-flex justify-content-end p-0">
							'.get_switch('logging').'
						</div>
					</div>
				</div>	
				<div class="col-sm-6 mt-2" id="action_field" style="display:none">
					<div class="row mx-auto">
						<div class="col-sm-6 p-0">
							<label class="control-label">'.__('Actions').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('Select to check all actions for this API credential').'"><i class="fas text-primary fa-info-circle"></i></a></label>
						</div>
						<div class="col-sm-6 d-flex justify-content-end p-0">
							'.get_switch('select_all', '' , 'select_all', array('chk_it' => 1), '', 'select_all').'
						</div>
					</div>
				</div>	
				<div class="col-sm-12">
					<div class ="row w-100 mx-auto" id ="acl_actions">';
						foreach($acls as $acl_grp => $acl_cat){
							echo '
							<div class="col-sm-12 px-0 py-2" id="'.$acl_grp.'" style="display:none;">
								<div class="card shadow-none py-2">
									<div class="card-body py-2">
										<h5 class="card-title">'.$acl_langs[$acl_grp].'</h5>
									</div>
									<div class="row mx-auto w-100">';
										foreach($acl_cat as $acl_key => $acl_value){
										echo '
											<div class="col-sm-3 cb_state" id="'.$acl_value.'_m" name="'.$acl_value.'_m">
												'.get_checkbox("acl_cb[$acl_value]", $acl_langs[$acl_value],$acl_value).'
											</div>';
										}
									echo '
									</div>
								</div>
							</div>';
						}
					echo'</div>
				</div>
			</div>
	
			<center>
				<input type="submit" name="api_generator_submit" class="go_btn m-4" value='.__('Generate API Pair').'>
			</center>
		</form>';

	end_of_acl:
	//form body close
	echo '</div>
	</div>';
	softfooter();

}

