Skip to content
new_service.php 26 KiB
Newer Older
Kristián Feldsam's avatar
Kristián Feldsam committed
<?php
/*
Copyright (c) 2016, Kristián Feldsam, FELDSAM s.r.o. <info@feldsam.cz>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of ISPConfig nor the names of its contributors
      may be used to endorse or promote products derived from this software without
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


/******************************************
* Begin Form configuration
******************************************/

$tform_def_file = "form/new_service.tform.php";

/******************************************
* End Form configuration
******************************************/

require_once '../../lib/config.inc.php';
require_once '../../lib/app.inc.php';

//* Check permissions for module
$app->auth->check_module_permissions('wizard');

// Loading classes
$app->uses('tpl,tform,remoting');
$app->load('tform_actions');

class page_action extends tform_actions {

	function onShowEnd() {
		global $app, $conf;

		$fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);

		// select first template as default
		if($fields['dns_template_id'] == 0)
		{
			$first_template = $app->db->queryOneRecord("SELECT template_id FROM dns_template WHERE visible = 'Y' ORDER BY name ASC");
			$fields['dns_template_id'] = $first_template['template_id'];
		}

		$template_record = $app->db->queryOneRecord("SELECT * FROM dns_template WHERE template_id = ?", $fields['dns_template_id']);
		$fields = explode(',', $template_record['fields']);
		if(is_array($fields)) {
			foreach($fields as $field) {
				$app->tpl->setVar($field."_VISIBLE", 1);
				$field = strtolower($field);
				$app->tpl->setVar($field, $_POST['dns_'.$field]);
			}
		}

		$global_config = $app->getconf->get_global_config('sites');
		$shelluser_prefix = $global_config['shelluser_prefix'];
		$app->tpl->setVar("username_prefix", $shelluser_prefix, true);

Kristián Feldsam's avatar
Kristián Feldsam committed
		parent::onShowEnd();
	}

	function onSubmit() {
		global $app, $conf;

		$fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
Helmo's avatar
Helmo committed
               $client_domain_exists = FALSE;
Kristián Feldsam's avatar
Kristián Feldsam committed

		// check for domain unique name
Helmo's avatar
Helmo committed
               if($app->db->queryOneRecord('SELECT domain_id FROM domain WHERE domain = ?', $fields['domain'])) {
                       $client_domain_exists = TRUE;
                       // Check use as web domain.
                       if($app->db->queryOneRecord('SELECT domain_id FROM web_domain WHERE domain = ?', $fields['domain'])) {
                               $app->tform->errorMessage = $app->tform->wordbook['domain_error_unique'] . 'b';
                       }
                       elseif($fields['mail'] && $app->db->queryOneRecord('SELECT domain_id FROM mail_domain WHERE domain = ?', $fields['domain'])) {
                               $app->tform->errorMessage = $app->tform->wordbook['domain_error_unique']. 'a';
                       }
                       else {
                               // Exists as client domain, not with a website.
                       }
Kristián Feldsam's avatar
Kristián Feldsam committed
		}
		
		if($app->tform->errorMessage)
		{
			$this->onError();
			return;
		}

		if($_POST['create'] != 1)
		{	
			$app->tform->errorMessage = 'DUMMY';
			$app->tpl->setVar($this->dataRecord);
			$this->onShow();
			return;
		}
		
		// Domain OK, continue
		$remote = new remote_actions;
		
		// load template
		$template = $app->db->queryOneRecord("SELECT * FROM wizard_template WHERE template_id = ? LIMIT 0,1", $fields['template_id']);
		
		// client prefix and group id
		$res = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($fields['client_id']));
		$client_group_id = $res['groupid'];
Kristián Feldsam's avatar
Kristián Feldsam committed
		// add domain
		if (!$client_domain_exists) {
			$domain_id = $remote->insert_query('../client/form/domain.tform.php', $fields['client_id'], array('domain' => $fields['domain']));
		}

		$min_password_length = 8;
		if(isset($server_config_array['misc']['min_password_length'])) $min_password_length = $server_config_array['misc']['min_password_length'];
Kristián Feldsam's avatar
Kristián Feldsam committed
		
		// DNS Zone
		if($fields['dns'])
		{
			if(isset($_POST['dns_ns1']) && $_POST['dns_ns1'] != ''){
				$_POST['dns_ns1'] = $app->functions->idn_encode($_POST['dns_ns1']);
				$_POST['dns_ns1'] = strtolower($_POST['dns_ns1']);
			}
			if(isset($_POST['dns_ns2']) && $_POST['dns_ns2'] != ''){
				$_POST['dns_ns2'] = $app->functions->idn_encode($_POST['dns_ns2']);
				$_POST['dns_ns2'] = strtolower($_POST['dns_ns2']);
			}
			if(isset($_POST['dns_email']) && $_POST['dns_email'] != ''){
				$_POST['dns_email'] = $app->functions->idn_encode($_POST['dns_email']);
				$_POST['dns_email'] = strtolower($_POST['dns_email']);
			}
		
			$dns_error = '';
		
			if(isset($_POST['dns_ip']) && $_POST['dns_ip'] == '') $dns_error .= $app->lng('error_ip_empty').'<br />';
		
			if(isset($_POST['dns_ipv6']) && $_POST['dns_ipv6'] == '') $dns_error .= $app->lng('error_ipv6_empty').'<br />';
		
			if(isset($_POST['dns_ns1']) && $_POST['dns_ns1'] == '') $dns_error .= $app->lng('error_ns1_empty').'<br />';
			elseif(isset($_POST['ns1']) && !preg_match('/^[\w\.\-]{2,64}\.[a-zA-Z0-9]{2,30}$/', $_POST['ns1'])) $dns_error .= $app->lng('error_ns1_regex').'<br />';
		
			if(isset($_POST['dns_ns2']) && $_POST['dns_ns2'] == '') $dns_error .= $app->lng('error_ns2_empty').'<br />';
			elseif(isset($_POST['ns2']) && !preg_match('/^[\w\.\-]{2,64}\.[a-zA-Z0-9]{2,30}$/', $_POST['ns2'])) $dns_error .= $app->lng('error_ns2_regex').'<br />';
		
			if(isset($_POST['dns_email']) && $_POST['dns_email'] == '') $dns_error .= $app->lng('error_email_empty').'<br />';
			elseif(isset($_POST['dns_email']) && filter_var($_POST['dns_email'], FILTER_VALIDATE_EMAIL) === false) $dns_error .= $app->lng('error_email_regex').'<br />';
		
			// check for dns errors
			if($dns_error)
			{
				$app->tform->errorMessage = $dns_error;
				$this->onError();
				return;
			}

Kristián Feldsam's avatar
Kristián Feldsam committed
			$tform_def_file = "../dns/form/dns_soa.tform.php";
Kristián Feldsam's avatar
Kristián Feldsam committed
			$app->tform->loadFormDef($tform_def_file);		
			
			// replace template placeholders
			$template_record = $app->db->queryOneRecord("SELECT * FROM dns_template WHERE template_id = ?", $fields['dns_template_id']);
			$tpl_content = $template_record['template'];
			$tpl_content = str_replace('{DOMAIN}', $fields['domain'], $tpl_content);
			if($_POST['dns_ip'] != '') $tpl_content = str_replace('{IP}', $_POST['dns_ip'], $tpl_content);
			if($_POST['dns_ipv6'] != '') $tpl_content = str_replace('{IPV6}',$_POST['dns_ipv6'],$tpl_content);
			if($_POST['dns_ns1'] != '') $tpl_content = str_replace('{NS1}', $_POST['dns_ns1'], $tpl_content);
			if($_POST['dns_ns2'] != '') $tpl_content = str_replace('{NS2}', $_POST['dns_ns2'], $tpl_content);
			if($_POST['dns_email'] != '') $tpl_content = str_replace('{EMAIL}', $_POST['dns_email'], $tpl_content);
			
			$enable_dnssec = (($_POST['dns_dnssec'] == 'Y') ? 'Y' : 'N');
		
			// Parse the template
			$tpl_rows = explode("\n", $tpl_content);
			$section = '';
			$vars = array();
			$vars['xfer']='';
			$dns_rr = array();
			foreach($tpl_rows as $row) {
				$row = trim($row);
				if(substr($row, 0, 1) == '[') {
					if($row == '[ZONE]') {
						$section = 'zone';
					} elseif($row == '[DNS_RECORDS]') {
						$section = 'dns_records';
					} else {
						die('Unknown section type');
					}
				} else {
					if($row != '') {
						// Handle zone section
						if($section == 'zone') {
							$parts = explode('=', $row);
							$key = trim($parts[0]);
							$val = trim($parts[1]);
							if($key != '') $vars[$key] = $val;
						}
						// Handle DNS Record rows
						if($section == 'dns_records') {
							$parts = explode('|', $row);
							$dns_rr[] = array(
								'name' => $parts[1],
								'type' => $parts[0],
								'data' => $parts[2],
								'aux'  => $parts[3],
								'ttl'  => $parts[4]
							);
						}
					}
				}
		
			} // end foreach
		
			$dns_error = '';
		
			if($vars['origin'] == '') $dns_error .= $app->lng('error_origin_empty').'<br />';
			if($vars['ns'] == '') $dns_error .= $app->lng('error_ns_empty').'<br />';
			if($vars['mbox'] == '') $dns_error .= $app->lng('error_mbox_empty').'<br />';
			if($vars['refresh'] == '') $dns_error .= $app->lng('error_refresh_empty').'<br />';
			if($vars['retry'] == '') $dns_error .= $app->lng('error_retry_empty').'<br />';
			if($vars['expire'] == '') $dns_error .= $app->lng('error_expire_empty').'<br />';
			if($vars['minimum'] == '') $dns_error .= $app->lng('error_minimum_empty').'<br />';
			if($vars['ttl'] == '') $dns_error .= $app->lng('error_ttl_empty').'<br />';
		
			// check for dns errors
			if($dns_error)
			{
				$app->tform->errorMessage = $dns_error;
				$this->onError();
				return;
			}
		
			// Insert the soa record
			$sys_userid = $_SESSION['s']['user']['userid'];
			$origin = $vars['origin'];
			$ns = $vars['ns'];
			$mbox = str_replace('@', '.', $vars['mbox']);
			$refresh = $vars['refresh'];
			$retry = $vars['retry'];
			$expire = $vars['expire'];
			$minimum = $vars['minimum'];
			$ttl = $vars['ttl'];
			$xfer = $vars['xfer'];
			$also_notify = $vars['also_notify'];
			$update_acl = $vars['update_acl'];
			$serial = $app->validate_dns->increase_serial(0);
	
			$insert_data = array(
				"sys_userid" => $sys_userid,
				"sys_groupid" => $client_group_id,
				"sys_perm_user" => 'riud',
				"sys_perm_group" => 'riud',
				"sys_perm_other" => '',
				"server_id" => $template['dns_server_id'],
				"origin" => $origin,
				"ns" => $ns,
				"mbox" => $mbox,
				"serial" => $serial,
				"refresh" => $refresh,
				"retry" => $retry,
				"expire" => $expire,
				"minimum" => $minimum,
				"ttl" => $ttl,
				"active" => 'Y',
				"xfer" => $xfer,
				"also_notify" => $also_notify,
				"update_acl" => $update_acl,
				"dnssec_wanted" => $enable_dnssec
			);
			$dns_soa_id = $app->db->datalogInsert('dns_soa', $insert_data, 'id');
	
			// Insert the dns_rr records
			if(is_array($dns_rr) && $dns_soa_id > 0) {
				foreach($dns_rr as $rr) {
					$insert_data = array(
						"sys_userid" => $sys_userid,
						"sys_groupid" => $client_group_id,
						"sys_perm_user" => 'riud',
						"sys_perm_group" => 'riud',
						"sys_perm_other" => '',
						"server_id" => $template['dns_server_id'],
						"zone" => $dns_soa_id,
						"name" => $rr['name'],
						"type" => $rr['type'],
						"data" => $rr['data'],
						"aux" => $rr['aux'],
						"ttl" => $rr['ttl'],
						"active" => 'Y'
					);
					$dns_rr_id = $app->db->datalogInsert('dns_rr', $insert_data, 'id');
				}
Kristián Feldsam's avatar
Kristián Feldsam committed
			
				if($fields['dkim'])
				{
					$insert_data = array(
						"sys_userid" => $sys_userid,
						"sys_groupid" => $client_group_id,
						"sys_perm_user" => 'riud',
						"sys_perm_group" => 'riud',
						"sys_perm_other" => '',
						"server_id" => $template['dns_server_id'],
						"zone" => $dns_soa_id,
						"name" => $fields['dkim_selector'].'._domainkey.'.$fields['domain'].'.',
						"type" => 'TXT',
						"data" => 'v=DKIM1; t=s; p='.str_replace(array('-----BEGIN PUBLIC KEY-----','-----END PUBLIC KEY-----',"\r","\n"), '', $_POST['dkim_public']),
						"aux" => 0,
						"ttl" => 86400,
						"active" => 'Y'
					);
					$dns_rr_id = $app->db->datalogInsert('dns_rr', $insert_data, 'id');
				}
Kristián Feldsam's avatar
Kristián Feldsam committed
			}
			
			$tform_def_file = "form/new_service.tform.php";
			$app->tform->loadFormDef($tform_def_file);
		}
			
		if($fields['mail'])
Kristián Feldsam's avatar
Kristián Feldsam committed
		{	
Kristián Feldsam's avatar
Kristián Feldsam committed
			// add mail domain
			$params = array(
				'server_id' => 	$template['mail_server_id'],
				'domain' => $fields['domain'],
Kristián Feldsam's avatar
Kristián Feldsam committed
				'dkim' => $fields['dkim'],
				'dkim_private' => $_POST['dkim_private'],
				'dkim_public' => $_POST['dkim_public'],
				'dkim_selector' => $fields['dkim_selector'],
Kristián Feldsam's avatar
Kristián Feldsam committed
				'active' => 'y'
			);
Kristián Feldsam's avatar
Kristián Feldsam committed
			$mail_domain_id = $remote->insert_query('../mail/form/mail_domain.tform.php', $fields['client_id'], $params);
			
			if($template['policy'])
			{
				$params = array(
					'server_id' => $template['mail_server_id'],
					'policy_id' => $template['policy'],
					'priority' => 5,
					'email' => '@'.$fields['domain'],
					'fullname' => '@'.$fields['domain'],
					'local' => 'Y',
				);
				
				$remote->insert_query('../mail/form/spamfilter_users.tform.php', $fields['client_id'], $params);
			}
			
			if($fields['mailboxes'])
			{
				$mailboxes = explode(',', $fields['mailboxes']);
				$mailbox_passwords = array();
				
				foreach($mailboxes as $alias)
				{
					$alias   = strtolower($app->functions->idn_encode($alias));
					$mailbox = $alias.'@'.$fields['domain'];

					// validate, on error skip
					if( ! preg_match('/^[_a-z0-9][\w\.\-_\+@]{1,63}$/', $mailbox)) continue;
					
					$mailbox_passwords[$mailbox] = $app->auth->get_random_password($min_password_length, true);
Kristián Feldsam's avatar
Kristián Feldsam committed
					
					$params = array(
						'server_id' => $template['mail_server_id'],
						'uid' => -1,
						'gid' => -1,
						'email' => $mailbox,
						'login' => $mailbox,
						'password' => $mailbox_passwords[$mailbox],
						'quota' => $template['mailbox_quota']*1024*1024,
						'postfix' => 'y',
						'disableimap' => ($template['enableimap'] == 'y' ? 'n' : 'y'),
						'disablepop3' => ($template['enablepop3'] == 'y' ? 'n' : 'y'),
						'disablesmtp' => ($template['enablesmtp'] == 'y' ? 'n' : 'y'),
						'maildir' => '/var/vmail/'.$fields['domain'].'/'.$alias,
						'maildir_format' => 'maildir',
Kristián Feldsam's avatar
Kristián Feldsam committed
						'homedir' => '/var/vmail',
						'backup_interval' => 'none',
Kristián Feldsam's avatar
Kristián Feldsam committed
					);
					
					$remote->insert_query('../mail/form/mail_user.tform.php', $fields['client_id'], $params);
				}
			}
		}
		
		// add site
		$params = array(
			'type' => 'vhost',
			'domain' => $fields['domain'],
			'server_id' => $template['web_server_id'],
			'ip_address' => $template['ip_address'],
			'ipv6_address' => $template['ipv6_address'],
			'traffic_quota' => $template['traffic_quota'],
			'hd_quota' => $template['hd_quota'],
			'cgi' => $template['cgi'],
			'ssi' => $template['ssi'],
			'suexec' => $template['suexec'],
			'ruby' => $template['ruby'],
			'python' => $template['python'],
			'perl' => $template['perl'],
			'errordocs' => $template['errordocs'],
			'subdomain' => $fields['subdomain'] == 'template' ? $template['subdomain'] : $fields['subdomain'],
Kristián Feldsam's avatar
Kristián Feldsam committed
			'php' => $template['php'],
			'server_php_id' => $template['server_php_id'],
Kristián Feldsam's avatar
Kristián Feldsam committed
			'seo_redirect' => $template['seo_redirect'],
			'rewrite_to_https' => $template['rewrite_to_https'],
			'allow_override' => $template['allow_override'],
			'http_port' => $template['http_port'],
			'https_port' => $template['https_port'],
			'log_retention' => $template['log_retention'],
Kristián Feldsam's avatar
Kristián Feldsam committed
			'apache_directives' => $template['apache_directives'],
			'nginx_directives' => $template['nginx_directives'],
			'php_fpm_use_socket' => $template['php_fpm_use_socket'],
			'pm' => $template['pm'],
			'pm_max_children' => $template['pm_max_children'],
			'pm_start_servers' => $template['pm_start_servers'],
			'pm_min_spare_servers' => $template['pm_min_spare_servers'],
			'pm_max_spare_servers' => $template['pm_max_spare_servers'],
			'pm_process_idle_timeout' => $template['pm_process_idle_timeout'],
			'pm_max_requests' => $template['pm_max_requests'],
			'custom_php_ini' => $template['custom_php_ini'],
			'active' => 'y',
			'document_root' => '-',
			'system_user' => '-',
			'system_group' => '-',
			'client_group_id' => $client_group_id,
		);
		
Helmo's avatar
Helmo committed
               try {
                       $site_id = $remote->insert_query('../sites/form/web_vhost_domain.tform.php', $fields['client_id'], $params, 'sites:web_vhost_domain:on_after_insert');
               } catch (SoapFault $e) {
                       $app->tform->errorMessage = $e->getMessage();
                       $this->onError();
                       return;
               }
Kristián Feldsam's avatar
Kristián Feldsam committed
		
		// get site data
		$app->uses('remoting_lib');
		$app->remoting_lib->loadFormDef('../sites/form/web_vhost_domain.tform.php');
		$site_data = $app->remoting_lib->getDataRecord($site_id);

		$app->uses('getconf,tools_sites');
		$global_config = $app->getconf->get_global_config('sites');

		$client_shell_prefix = $app->tools_sites->replacePrefix($global_config['shelluser_prefix'], array('client_group_id' => $client_group_id));
		$client_ftp_prefix = $app->tools_sites->replacePrefix($global_config['ftpuser_prefix'], array('client_group_id' => $client_group_id));
		$client_db_prefix = $app->tools_sites->replacePrefix($global_config['dbuser_prefix'], array('client_group_id' => $client_group_id));

		if (empty($fields['username'])) {
			// generate username
			$generated_username = substr(sha1(rand()), 0, 8);
		}
		else {
			$generated_username = $fields['username'];
		}
Kristián Feldsam's avatar
Kristián Feldsam committed
		
		if($fields['db'])
		{
			// add database user
			$db_user_params = array(
				'server_id' => 	$template['database_server_id'],
				'database_user' => $client_db_prefix . $generated_username,
				'database_user_prefix' => $client_db_prefix,
Helmo's avatar
Helmo committed
				'database_password' => $app->auth->get_random_password($min_password_length, true),
Kristián Feldsam's avatar
Kristián Feldsam committed
			);
Helmo's avatar
Helmo committed
                       try {
                               $db_user_id = $remote->insert_query('../sites/form/database_user.tform.php', $fields['client_id'], $db_user_params, 'sites:web_database_user:on_after_insert');
                        } catch (SoapFault $e) {
                               $app->tform->errorMessage = $e->getMessage();
                               $this->onError();
                               return;
                        }
Kristián Feldsam's avatar
Kristián Feldsam committed
			
			// add database
			$params = array(
				'server_id' => 	$template['database_server_id'],
				'parent_domain_id' => $site_id,
				'type' => $fields['db_type'],
				'database_quota' => $template['database_quota'],
				'database_name' => $db_user_params['database_user'],
				'database_name_prefix' => $db_user_params['database_user_prefix'],
Kristián Feldsam's avatar
Kristián Feldsam committed
				'database_user_id' => $db_user_id,
				'database_charset' => $template['database_charset'],
				'remote_access' => $template['database_remote_access'],
				'remote_ips' => $template['database_remote_ips'],
				'active' => 'y'
			);
Helmo's avatar
Helmo committed
                       try {
                               $remote->sites_database_add($fields['client_id'], $params);
                        } catch (SoapFault $e) {
                               $app->tform->errorMessage = $e->getMessage();
                               $this->onError();
                               return;
                        }
Kristián Feldsam's avatar
Kristián Feldsam committed
		}
		
		if($fields['ftp']) {
			// add ftp user
			$ftp_params = array(
				'server_id' => 	$template['web_server_id'],
				'parent_domain_id' => $site_id,
				'username' => $client_ftp_prefix . $generated_username,
Helmo's avatar
Helmo committed
				'username_prefix' => $client_ftp_prefix,
Helmo's avatar
Helmo committed
				'password' => $app->auth->get_random_password($min_password_length, true),
Kristián Feldsam's avatar
Kristián Feldsam committed
				'quota_size' => $template['hd_quota'],
				'dir' => $site_data['document_root'],
				'uid' => $site_data['system_user'],
				'gid' => $site_data['system_group'],
				'sys_groupid' => $site_data['sys_groupid'],
				'quota_files' => $template['quota_files'],
				'ul_ratio' => $template['ul_ratio'],
				'dl_ratio' => $template['dl_ratio'],
				'ul_bandwidth' => $template['ul_bandwidth'],
				'dl_bandwidth' => $template['dl_bandwidth'],
				'active' => 'y',
			);
Helmo's avatar
Helmo committed
                       try {
                               $remote->insert_query('../sites/form/ftp_user.tform.php', $fields['client_id'], $ftp_params);
                        } catch (SoapFault $e) {
                               $app->tform->errorMessage = $e->getMessage();
                               $this->onError();
                               return;
                        }
Kristián Feldsam's avatar
Kristián Feldsam committed
		}
		
		if($fields['ssh']) {
			// add ssh user
			$ssh_params = array(
				'server_id' => 	$template['web_server_id'],
				'parent_domain_id' => $site_id,
				'quota_size' => $template['hd_quota'],
				'dir' => $site_data['document_root'],
				'puser' => $site_data['system_user'],
				'pgroup' => $site_data['system_group'],
				'sys_groupid' => $site_data['sys_groupid'],
				'chroot' => $template['shell_chroot'],
				'shell' => $template['shell'],
				'active' => 'y',
				'username' => $client_shell_prefix . $generated_username,
Helmo's avatar
Helmo committed
				'username_prefix' => $client_shell_prefix,
Kristián Feldsam's avatar
Kristián Feldsam committed
			);
			
			// username, password
			if(isset($ftp_params)) {
				$ssh_params['password'] = $ftp_params['password'];
			} else {
				$ssh_params['password'] = $app->auth->get_random_password($min_password_length, true);
Kristián Feldsam's avatar
Kristián Feldsam committed
			}
			
			$remote->insert_query('../sites/form/shell_user.tform.php', $fields['client_id'], $ssh_params);
		}
Helmo's avatar
Helmo committed
		$webserver = $app->db->queryOneRecord("SELECT server_name FROM server WHERE web_server = 1 AND server_id = ?", $template['web_server_id']);
		$dbserver = $app->db->queryOneRecord("SELECT server_name FROM server WHERE web_server = 1 AND server_id = ?", $template['database_server_id']);

		$global_config = $app->getconf->get_global_config('sites');
		$phpmyadmin_url = $global_config['phpmyadmin_url'];
		$phpmyadmin_url = str_replace(array('[SERVERNAME]', '[DATABASENAME]'), array($dbserver['server_name'], $db_user_params['database_user']), $phpmyadmin_url);
Kristián Feldsam's avatar
Kristián Feldsam committed
		// results
		echo '
			<div class="page-header">
				<h1>New service</h1>
			</div>
			<div class="table-wrapper marginTop15">
			<p>' . $app->tform->wordbook["new_service_txt"] . '</p>
Kristián Feldsam's avatar
Kristián Feldsam committed
			<table class="table">
				<thead class="dark">
					<tr>
                                               <th colspan="3">'.$fields['domain'].'</th>
Kristián Feldsam's avatar
Kristián Feldsam committed
					</tr>
				</thead>
				<tbody>';
				if(isset($db_user_params)) {
					echo
					'<tr class="info">
						<th>DB name/user</th>
						<th>DB password</th>
                                               <th>PhpMyAdmin</th>
Kristián Feldsam's avatar
Kristián Feldsam committed
					</tr>
					<tr>
						<td>'.$db_user_params['database_user'].'</td>
						<td>'.$db_user_params['database_password'].'</td>
Helmo's avatar
Helmo committed
						<td>https://' . $webserver['server_name'] . '/phpmyadmin/</td>
Kristián Feldsam's avatar
Kristián Feldsam committed
					</tr>';
				}
				if(isset($ftp_params)) {
					echo'
					<tr class="info">
						<th>FTP user</th>
						<th>FTP password</th>
                                               <th>FTP Server</th>
Kristián Feldsam's avatar
Kristián Feldsam committed
					</tr>
					<tr>
						<td>'.$ftp_params['username'].'</td>
						<td>'.$ftp_params['password'].'</td>
                                               <td>'.$webserver['server_name'].'</td>
Kristián Feldsam's avatar
Kristián Feldsam committed
					</tr>';
				}
				if(isset($ssh_params)) {
					echo'
					<tr class="info">
						<th>SSH user</th>
						<th>SSH password</th>
Helmo's avatar
Helmo committed
						<th>SSH Server</th>
Kristián Feldsam's avatar
Kristián Feldsam committed
					</tr>
					<tr>
						<td>'.$ssh_params['username'].'</td>
						<td>'.$ssh_params['password'].'</td>
Helmo's avatar
Helmo committed
						<td>'.$webserver['server_name'].'</td>
Kristián Feldsam's avatar
Kristián Feldsam committed
					</tr>';
				}
				if(isset($mailbox_passwords) and (bool)count($mailbox_passwords))
				{
					echo '
					<tr class="info">
						<th>Mailbox</th>
						<th>Password</th>
					</tr>';
					foreach($mailbox_passwords as $mail => $pass)
					{
						echo'
						<tr>
							<td>'.$mail.'</td>
							<td>'.$pass.'</td>
						</tr>';
					}
				}
				echo'
				</tbody>
			</table>
			</div>
		';
Helmo's avatar
Helmo committed

               // Loading the template
               $app->uses('tpl');
               $app->tpl->newTemplate("templates/template_summary_plaintext.htm");

               $app->tpl->setVar('sitedomain', $fields['domain']);
               $app->tpl->setVar('database_username', $db_user_params['database_user']);
               $app->tpl->setVar('database_password', $db_user_params['database_password']);

Helmo's avatar
Helmo committed
               if(isset($ftp_params)) {
                       $app->tpl->setVar('ftp_server_name', $webserver['server_name']);
                       $app->tpl->setVar('ftp_username', $ftp_params['username']);
                       $app->tpl->setVar('ftp_password', $ftp_params['password']);
               }
Helmo's avatar
Helmo committed

               $app->tpl->setVar('ssh_server_name', $webserver['server_name']);
               $app->tpl->setVar('ssh_username', $ssh_params['username']);
               $app->tpl->setVar('ssh_password', $ssh_params['password']);
               // TODO
//             $app->tpl->setVar('mailbox_passwords', $mailbox_passwords);

               $app->tpl->pparse();
Kristián Feldsam's avatar
Kristián Feldsam committed
	private function clean_private_key($key)
	{
		return str_replace('\r\n', '', $key);
	}

Kristián Feldsam's avatar
Kristián Feldsam committed
}

class remote_actions extends remoting {
	public function insert_query($formdef_file, $client_id, $params, $event_identifier = '') {
		return $this->insertQuery($formdef_file, $client_id, $params, $event_identifier);
	}
	
	public function sites_database_add($client_id, $params)
	{
		global $app;

		$sql = $this->insertQueryPrepare('../sites/form/database.tform.php', $client_id, $params);
		if($sql !== false) {
			$app->uses('sites_database_plugin');

			$this->id = 0;
			$this->dataRecord = $params;
			$app->sites_database_plugin->processDatabaseInsert($this);

			$retval = $this->insertQueryExecute($sql, $params);
			
			// set correct values for backup_interval and backup_copies
			if(isset($params['backup_interval']) || isset($params['backup_copies'])){
				$sql_set = array();
				if(isset($params['backup_interval'])) $sql_set[] = "backup_interval = '".$app->db->quote($params['backup_interval'])."'";
				if(isset($params['backup_copies'])) $sql_set[] = "backup_copies = ".$app->functions->intval($params['backup_copies']);
				//$app->db->query("UPDATE web_database SET ".implode(', ', $sql_set)." WHERE database_id = ".$retval);
				$this->updateQueryExecute("UPDATE web_database SET ".implode(', ', $sql_set)." WHERE database_id = ".$retval, $retval, $params);
			}
			
			return $retval;
		}

		return false;
	}
}

$page = new page_action;
$page->onLoad();