|
- <?php
- /*
- PHP por David Ramos García, Open6Hosting <dramos@open6hosting.com>
- SQL y expresiones regulares por Pablo Sarria Pérez, Open6Hosting <pablo@sarriaperez.com>
-
- 2017, All rights reserved.
- */
-
- require_once '../../lib/config.inc.php';
- require_once '../../lib/app.inc.php';
- //INICIO---CLASE PARA LOS LIMITES--------------------------------------------------------------------------------------------
- require_once 'clases/limites.inc.php';
- //FIN------CLASE PARA LOS LIMITES--------------------------------------------------------------------------------------------
- //require 'pdf_o6h.php';
-
- //Variable para cargar los distintos formularios.
- $tform_def_file = "form/new_service_webdns.tform.php";
-
- //Check permissions for module
- $app->auth->check_module_permissions('webdns');
-
- //Check the module permissions and redirect if not allowed.
- /*if(!stristr($_SESSION['s']['user']['modules'],'customdns')) {
- header('Location: ../index.php');
- die;
- }*/
-
- //Loading classes a usar.
- $app->uses('tpl,tform,tform_actions,remoting,tools_sites,remoting_lib,remoting_dns');
- $app->load('tform_actions');
-
-
- class page_action extends tform_actions {
-
- public $estaLogeado;
-
- function onShowNew() {
- global $app;
- //if($_SESSION['s']['user']['typ'] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])) unset($this->dataRecord["client_group_id"]);
- //unset($_SESSION['s_old']);
- //echo('Data record '. $this->dataRecord["username_prefix"] . print_r($this->dataRecord));
- //$sesion = $_SESSION;
- /*$sesionDe = $_SESSION['s']['user']['typ'];
- $grupo = $_SESSION["s"]["user"]["default_group"];
- print_r('La session de ' . $sesionDe);
- print(', su grupo es ' . $grupo);*/
- //print_r($sesion);
- //------LIMITES--------------------------------------------------------------------------------------------------
- $this->estaLogeado = $_SESSION['s']['user']['typ'];
- // we will check only users, not admins
- if($this->estaLogeado == 'user') {
- $client_group_id = $_SESSION["s"]["user"]["default_group"];
- $limitado = new limites($client_group_id);
- $limitado->limitesLoad();
-
- }
- //------LIMITES--------------------------------------------------------------------------------------------------
- parent::onShowNew();
- }
-
-
- function onShowEnd() {
- global $app, $conf, $interfaceConf;
-
- $this->tratarVariablesPrefix();
- $app->uses('getconf,tools_sites');
- $global_config = $app->getconf->get_global_config('sites');
- $ftpuser_prefix = $app->tools_sites->replacePrefix($global_config['ftpuser_prefix'], $this->dataRecord);
-
- if ($this->dataRecord['username'] != ""){
- /* REMOVE the restriction */
- $app->tpl->setVar("username", $app->tools_sites->removePrefix($this->dataRecord['username'], $this->dataRecord['username_prefix'], $ftpuser_prefix));
- }
-
- if($this->dataRecord['username'] == "") {
- $app->tpl->setVar("username_prefix", $ftpuser_prefix);
- } else {
- $app->tpl->setVar("username_prefix", $app->tools_sites->getPrefix($this->dataRecord['username_prefix'], $ftpuser_prefix, $global_config['ftpuser_prefix']));
- }
- //Get the database user prefix
- $app->uses('getconf,tools_sites');
- $global_config = $app->getconf->get_global_config('sites');
- //$this->valor_prefix = $dbuser_prefix = $app->tools_sites->replacePrefix($global_config['dbuser_prefix'], $this->dataRecord);
- //$this->valor_prefix_ftp = $ftpuser_prefix = $app->tools_sites->replacePrefix($global_config['ftpuser_prefix'], $this->dataRecord);
- //echo('PRe antes ' . $ftpuser_prefix . ' DataRecord ' . print_r($this->dataRecord));
- //echo('PRe antes2 ' . print_r($global_config));
-
- //* Client: If the logged in user is not admin and has no sub clients (no reseller)
- if ($_SESSION["s"]["user"]["typ"] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])) {
- // Get the limits of the client
- $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
- $client = $app->db->queryOneRecord("SELECT client.company_name, client.contact_name, client.client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ?", $client_group_id);
- //echo('PRe antes2 ' . print_r($global_config));
- // Fill the client select field
- /* $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
- $records = $app->db->queryAllRecords($sql, $client['client_id']);
- $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
- $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contact_name'].'</option>';
- //$tmp_data_record = $app->tform->getDataRecord($this->id);
- if(is_array($records)) {
- foreach( $records as $rec) {
- $selected = @(is_array($this->dataRecord) && ($rec["groupid"] == $this->dataRecord['client_group_id'] || $rec["groupid"] == $this->dataRecord['sys_groupid']))?'SELECTED':'';
- $client_select .= "<option value='$rec[groupid]' $selected>$rec[contactname]</option>\r\n";
- }
- }
- $app->tpl->setVar("client_group_id", $client_select);*/
- //* Reseller: If the logged in user is not admin and has sub clients (reseller)
- }elseif ($_SESSION["s"]["user"]["typ"] != 'admin' && $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
- // Get the limits of the client
- $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
- $client = $app->db->queryOneRecord("SELECT client.company_name, client.contact_name, client.client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ?", $client_group_id);
- //echo('PRe antes2 ' . print_r($global_config));
- // Fill the client select field
- $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
- $records = $app->db->queryAllRecords($sql, $client['client_id']);
- $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
- $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contact_name'].'</option>';
- //$tmp_data_record = $app->tform->getDataRecord($this->id);
- if(is_array($records)) {
- foreach( $records as $rec) {
- $selected = @(is_array($this->dataRecord) && ($rec["groupid"] == $this->dataRecord['client_group_id'] || $rec["groupid"] == $this->dataRecord['sys_groupid']))?'SELECTED':'';
- $client_select .= "<option value='$rec[groupid]' $selected>$rec[contactname]</option>\r\n";
- }
- }
- $app->tpl->setVar("client_group_id", $client_select);
- } elseif($_SESSION["s"]["user"]["typ"] == 'admin') {
- // Fill the client select field
- $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND sys_group.client_id > 0 ORDER BY client.company_name, client.contact_name, sys_group.name";
- $clients = $app->db->queryAllRecords($sql);
- $client_select = "<option value='0'></option>";
- //$tmp_data_record = $app->tform->getDataRecord($this->id);
- if(is_array($clients)) {
- foreach( $clients as $client) {
- //$selected = @($client["groupid"] == $tmp_data_record["sys_groupid"])?'SELECTED':'';
- $selected = @(is_array($this->dataRecord) && ($client["groupid"] == $this->dataRecord['client_group_id'] || $client["groupid"] == $this->dataRecord['sys_groupid']))?'SELECTED':'';
- $client_select .= "<option value='$client[groupid]' $selected>$client[contactname]</option>\r\n";
- }
- }
- $app->tpl->setVar("client_group_id", $client_select);
- }
- // echo('Prefix Global ' . $this->valor_prefix);
- if ($this->dataRecord['database_user'] != ""){
- /* REMOVE the restriction */
- //echo(' (1)Remove las restrinciones');
- $app->tpl->setVar("database_user", $app->tools_sites->removePrefix($this->dataRecord['database_user'], $this->dataRecord['database_user_prefix'], $dbuser_prefix));
- }
-
- if($this->dataRecord['database_user'] == "") {
- $app->tpl->setVar("database_user_prefix", $dbuser_prefix);
- //echo(' (2)user DB vacío ');
- } else {
- //echo(' (3)user DB con algo ' . $this->dataRecord['database_user_prefix']);
- $app->tpl->setVar("database_user_prefix", $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']));
- $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']);
- $datos_prefix = $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']);
- //echo(' Datos prefix ' . $datos_prefix);
- $fields['database_user_prefix'] = $datos_prefix;
- }
-
- if ($this->dataRecord['username'] != ""){
- /* REMOVE the restriction */
- $app->tpl->setVar("username", $app->tools_sites->removePrefix($this->dataRecord['username'], $this->dataRecord['username_prefix'], $ftpuser_prefix));
- }
-
- if($this->dataRecord['username'] == "") {
- $app->tpl->setVar("username_prefix", $ftpuser_prefix);
- } else {
- $app->tpl->setVar("username_prefix", $app->tools_sites->getPrefix($this->dataRecord['username_prefix'], $ftpuser_prefix, $global_config['ftpuser_prefix']));
- }
-
- parent::onShowEnd();
- }
-
-
- public $valor_prefix;
- public $valor_prefix_ftp;
-
- function tratarVariablesPrefix() {
- global $app, $conf, $interfaceConf;
-
- //Get the database name and database user prefix
- $app->uses('getconf,tools_sites');
- $global_config = $app->getconf->get_global_config('sites');
- $dbuser_prefix = $app->tools_sites->replacePrefix($global_config['dbuser_prefix'], $this->dataRecord);
- $ftpuser_prefix = $app->tools_sites->replacePrefix($global_config['ftpuser_prefix'], $this->dataRecord);
-
- $this->dataRecord['username_prefix'] = $ftpuser_prefix;
- $this->dataRecord['database_user_prefix'] = $dbuser_prefix;
- //$valor2 = $this->dataRecord['database_user_prefix'] = $dbuser_prefix;
-
- $this->valor_prefix = $this->dataRecord['database_user_prefix'] = $dbuser_prefix;
- $this->valor_prefix_ftp = $this->dataRecord['username_prefix'] = $ftpuser_prefix;
-
- //echo('(1)Prefix ' . $this->valor_prefix . '(2)Prefix ftp ' . $this->valor_prefix_ftp );
-
- if(strlen($dbuser_prefix . $this->dataRecord['database_user']) > 16)
- $app->tform->errorMessage .= str_replace('{user}', htmlentities($dbuser_prefix . $this->dataRecord['database_user'], ENT_QUOTES, 'UTF-8'),
- $app->tform->wordbook["database_user_error_len"]).'<br />';
-
- //Check database user against blacklist
- $dbuser_blacklist = array($conf['db_user'], 'mysql', 'root');
- if(is_array($dbuser_blacklist) && in_array($dbuser_prefix . $this->dataRecord['database_user'], $dbuser_blacklist)) {
- $app->tform->errorMessage .= $app->lng('Database user not allowed.').'<br />';
- }
-
- /* restrict the names */
- /* crop user names if they are too long -> mysql: user: 16 chars / db: 64 chars */
- if ($app->tform->errorMessage == ''){
- $this->dataRecord['database_user'] = substr($dbuser_prefix . $this->dataRecord['database_user'], 0, 16);
- }
-
- $this->dataRecord['server_id'] = 0; // we need this on all servers
-
- //echo('Usuarios ' .$this->dataRecord['database_user'] . ' Prefix ' . $this->dataRecord['database_user_prefix'] . ' Mas ' . $dbuser_prefix);
- if ($this->dataRecord['database_user'] != ""){
- /* REMOVE the restriction */
- $app->tpl->setVar("database_user", $app->tools_sites->removePrefix($this->dataRecord['database_user'], $this->dataRecord['database_user_prefix'], $dbuser_prefix));
- }
-
- if($this->dataRecord['database_user'] == "") {
- $app->tpl->setVar("database_user_prefix", $dbuser_prefix);
- } else {
- $app->tpl->setVar("database_user_prefix", $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']));
- }
- //* Reseller: If the logged in user is not admin and has sub clients (is a reseller)
- if($_SESSION["s"]["user"]["typ"] != 'admin' && $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
- $this->valor_prefix = $dbuser_prefix;
- }
- }
-
-
- public $dominio;
- public $subdominio;
- public $es_subdominio = false;
- public $subdom_error = false;
- public $dominio_error = false;
- public $no_ip = false;
-
- //Campos para PDF
- public $usuario_db_txt;
- public $nombre_db_txt;
- public $pass_db_txt;
- public $usuario_ftp_txt;
- public $pass_ftp_txt;
- public $nombre_user_ftp;
- public $ip4_pdf;
- public $url_db;
-
-
- function generaNombreFTP(){
-
- $this->tratarVariablesPrefix();
-
- //echo ('PreFIX Valor ' . $dbuser_prefix_valor);
- //Cadena de caractares para construir el nombre.
- $cadena = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
-
- //Obtengo la longitud de las cadenas
- $longitudCadena=strlen($cadena);
-
- //Variable para el nombre
- $nombre = "";
- //Longitud para el nombre
- $longitudNombre=8;
-
- //Creo el nombre
- for($i=1 ; $i<=$longitudNombre ; $i++){
- //Número aleatorio entre 0 y la longitud de la cadena de caracteres-1
- $pos=rand(0,$longitudCadena-1);
- //Formo la nombre en cada iteracción del bucle, añadiendo a la cadena $nombre
- //la letra correspondiente a la posición $pos en la cadena de caracteres definida.
- $nombre .= substr($cadena,$pos,1);
- }
- return $nombre;
- }
-
-
- function generaPass(){
- //Cadena de caractares para construir las password.
- $cadena = "abcdefghijklmnopqrstuvwxyz!@#_ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
- $cadSpeciales = "!@#_";
-
- //Obtengo la longitud de las cadenas
- $longitudCadena = strlen($cadena);
- $longSpeciales = strlen($cadSpeciales);
-
- //Variable para la password
- $pass = "";
- //Longitud para la password
- $longitudPass=13;
-
- //Creo la password
- for($i=1 ; $i<=$longitudPass ; $i++){
- //Número aleatorio entre 0 y la longitud de la cadena de caracteres-1
- $pos=rand(0,$longitudCadena-1);
- //Formo la password en cada iteracción del bucle, añadiendo a la cadena $pass
- //la letra correspondiente a la posición $pos en la cadena de caracteres definida.
- $pass .= substr($cadena,$pos,1);
- //Añado algún caracter especial en los últimos cuatro caracteres
- for($i2=13;$i2<=$i; $i2++){
- $poSpecial=rand(0,$longSpeciales-1);
- $pass .= substr($cadSpeciales, $poSpecial, 1);
- }
- }
- return $pass;
- }
-
-
- function generaNombreBD(){
-
- $this->tratarVariablesPrefix();
-
- //echo ('PreFIX Valor ' . $dbuser_prefix_valor);
- //Cadena de caractares para construir las nombre.
- $cadena = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
- //$cadSpeciales = "!@#_";
-
- //Obtengo la longitud de las cadenas
- $longitudCadena=strlen($cadena);
- //$longSpeciales = strlen($cadSpeciales);
-
- //Variable para la nombre
- $nombre = "";
- //Longitud para la nombre
- $longitudNombre=8;
-
- //Creo el nombre
- for($i=1 ; $i<=$longitudNombre ; $i++){
- //Número aleatorio entre 0 y la longitud de la cadena de caracteres-1
- $pos=rand(0,$longitudCadena-1);
- //Formo la nombre en cada iteracción del bucle, añadiendo a la cadena $nombre
- //la letra correspondiente a la posición $pos en la cadena de caracteres definida.
- $nombre .= substr($cadena,$pos,1);
-
- }
- return $this->valor_prefix . $nombre;
- }
-
-
- /*function comprobarPass($claveGenerada){
- //compruebo que el tamaño del string sea válido.
- if (strlen($claveGenerada)<3 || strlen($claveGenerada)>20){
- echo $claveGenerada . " no es válida0<br>";
- return false;
- }
-
- //compruebo que los caracteres sean los permitidos
- $alphachars = "abcdefghijkmnopqrstuvwxyz";
- $upperchars = "ABCDEFGHJKLMNPQRSTUVWXYZ";
- $numchars = "23456789";
- $specialchars = "!@#_";
-
- //$permitidos = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
-
-
- if (ereg("^[a-zA-Z0-9\-_]{3,20}$", $claveGenerada)) {
- echo $claveGenerada . " es válido<br>";
- return true;
- } else {
- echo $claveGenerada . " NO válido<br>";
- return false;
- }
-
- echo $claveGenerada . " es válido<br>";
- return true;
- }*/
-
- function crearBaseDatosFtp($remoto){
- global $app, $conf;
-
- $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
-
- $app->uses('ini_parser,getconf');
- $server_config_array = $app->getconf->get_global_config();
-
- $generated_usernameBBDD = $this->generaNombreBD();
- //print "<pre>"; print_r($generated_usernameBBDD); print "</pre>\n";
- $sitio_id = $app->db->queryOneRecord(
- 'SELECT domain_id, domain FROM web_domain WHERE domain = "'.$fields['domain'].'"');
- //print_r($fields);
- //echo(' Campo en formulario ' . $fields['database_user_prefix']);
- //print "<pre>"; print_r($camDnsRR); print "</pre>\n";
- // echo(' El nuevo prefix ' . $this->valor_prefix_ftp);
- $clavePass = $this->generaPass();
- //*Recupero todos los prefix necesarios
- /*$app->uses('getconf,tools_sites');
- $global_config = $app->getconf->get_global_config('sites');
- $ftpuser_prefix = $app->tools_sites->replacePrefix($global_config['ftpuser_prefix'], $this->dataRecord);*/
-
- //echo('Cliente ' . $this->cli_id . ' cli grupo ' . $this->cli_grupo_id . ' sys user ' . $this->sys_usuario_id . ' sys grupo ' . $this->sys_grupo_id);
- //añado database user con su prefix
- $db_user_params = array(
- 'server_id' => $this->bbdd_serv,
- 'sysgroup_id' => $this->cli_grupo_id, //$this->sys_grupo_id,
- 'sys_userid' => $this->sys_usuario_id,
- 'sys_perm_other' => '-',
- 'database_user' => $generated_usernameBBDD,
- 'database_user_prefix' => $this->valor_prefix,
- 'database_password' => $clavePass
- );
-
- $this->usuario_db_txt = $db_user_params['database_user'];
- $this->pass_db_txt = $db_user_params['database_password'];
-
- //print "<pre> USUARIO BBDD "; print_r($db_user_params); print "</pre>\n";
- //print "<br>". $this->cli_id;
- //print "<br>". $this->usuario_db_txt;
- //print "<br>". $this->pass_db_txt;
- //print "<pre>"; print_r($fields); print "</pre>\n";
-
- //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO
- //DE LO QUE SE QUIERE CREAR EN ESTE CASO SITIO WEB
- $tform_def_file = "../sites/form/database_user.tform.php";
- $app->tform->loadFormDef($tform_def_file);
-
- $db_user_id = $remoto->insert_query('../sites/form/database_user.tform.php',
- $this->cli_id, $db_user_params, 'sites:web_database_user:on_after_insert');
- //echo('El id ' . $this->id);
- //$remoto2 = new remote_actions;
- $remoto->sites_database_user_after_add($this->cli_grupo_id, $db_user_params);
- //echo(' El cliente en webdns ' . $this->cli_id);
-
- // add database
- $paramsBD = array(
- 'server_id' => $this->bbdd_serv, //$camDnsRR['server_id'],
- 'sysgroup_id' => $this->cli_grupo_id, //$this->sys_grupo_id, //$fields['client_group_id'],
- 'parent_domain_id' => $sitio_id['domain_id'],
- 'type' => 'mysql',
- 'database_quota' => '-1',
- 'database_name' => $generated_usernameBBDD,
- 'database_name_prefix' => $this->valor_prefix,
- 'database_user_id' => $db_user_id,
- 'database_charset' => 'utf8',
- 'remote_access' => 'n',
- 'remote_ips' => '-1',
- 'active' => 'y'
- );
- //print "<pre> BBDD "; print_r($paramsBD); print "</pre>\n";
-
- $this->nombre_db_txt = $paramsBD['database_name'];
- //IMPORTANTE. COMPROBAR EL VALOR QUE HAY QUE ENVIAR, SI ES CLI GRUPO Ó CLI ID
- $db_id = $remoto->sites_database_add($this->cli_id, /*$this->cli_id,/*$fields['client_group_id'],*/ $paramsBD);
-
- $this->urlBBDD($db_id, $this->bbdd_serv);
- //echo('Id de la BBDD ' . $db_id);
- // get site data para usarlo en la creación de la cuenta ftp, otra forma de cargar una tupla dandole un id
- //$app->uses('remoting_lib');
- // $app->remoting_lib->loadFormDef('../sites/form/web_vhost_domain.tform.php');
- // $site_data = $app->remoting_lib->getDataRecord($sitio_id);
- // $site_data = $remoto->getDataRecordWebDNS($sitio_id);
-
- $this->nombre_user_ftp = $this->generaNombreFTP();
- // add ftp user
- $ftp_params = array(
- 'server_id' => $this->web_serv, //$camDnsRR['server_id'],
- 'parent_domain_id' => $sitio_id['domain_id'],
- 'username' => $this->valor_prefix_ftp . $this->nombre_user_ftp,
- 'username_prefix' => $this->valor_prefix_ftp,
- 'password' => $clavePass,
- 'quota_size' => '-1',
- 'dir' => $site_data['0']['document_root'],
- 'uid' => $site_data['0']['system_user'],
- 'gid' => $site_data['0']['system_group'],
- 'sys_groupid' => $site_data['0']['sys_groupid'],
- 'quota_files' => '-1',
- 'ul_ratio' => '-1',
- 'dl_ratio' => '-1',
- 'ul_bandwidth' => '-1',
- 'dl_bandwidth' => '-1',
- 'active' => 'y',
- );
- $this->usuario_ftp_txt = $ftp_params['username'];
- $this->pass_ftp_txt = $ftp_params['password'];
- //print "<pre> FTP "; print_r($ftp_params); print "</pre>\n";
- //print "<pre>"; print_r($site_data); print "</pre>\n";
- //echo('El grupo del usuario es ' . $this->cli_grupo_id);
- $tform_def_file = "../sites/form/ftp_user.tform.php";
- $app->tform->loadFormDef($tform_def_file);
-
- $remoto->insert_query('../sites/form/ftp_user.tform.php', $this->cli_id,/*$fields['client_group_id'],*/ $ftp_params);
-
- $app->uses('sites_ftp_user_plugin');
- global $app;
- //Register for the events
- $app->plugin->registerEvent('sites:ftp_user:on_after_insert');
- //Lo lanzo yo.
- $remoto->sites_ftp_user_after_insert();
- echo '<br><div class="alert alert-success"><br>
- Altas de BBDD y FTP, ¡Correctas!<br><br>
- Usuario BBDD: <b>'. $this->usuario_db_txt .'</b><br>Contraseña: <b>' . $this->pass_db_txt . '
- </b><br>Nombre BBDD: <b>' . $this->nombre_db_txt . '</b><br>
- <br>Usuario FTP: <b>'. $this->usuario_ftp_txt .'</b><br>Contraseña: <b>' . $this->pass_ftp_txt . '</b><br><br>
- </div></br>';
-
- //$hoy = date("d-m-Y H:i:s");
-
- $html_resultado = '<br><br><b>BBDD</b><br>
- Usuario: <b>'. $this->usuario_db_txt .'</b><br>
- Nombre Base de Datos: <b>' . $this->nombre_db_txt .'</b><br>
- Clave: <b>' . $this->pass_db_txt . '</b><br><br>
- <b>FTP</b><br>
- Usuario: <b>'. $this->usuario_ftp_txt .'</b><br>
- Clave: <b>' . $this->pass_ftp_txt . '</b><br><br>
- <b> </b><br>Nuevo dominio: <b>'. $fields['domain'].'</b><br><br>';
-
- $eldom = $fields['domain'];
- echo '<form method="post" id="formulario" action="webdns/pdf_o6h.php" target="_blank">';
- echo '<input id="pdf_power" name="pdf_power" type="hidden" value="'.$html_resultado.'">';
- echo '<input id="nombre_bd" name="nombre_bd" type="hidden" value="'.$this->nombre_db_txt.'">';
- echo '<input id="usuario_bd" name="usuario_bd" type="hidden" value="'.$this->usuario_db_txt.'">';
- echo '<input id="pass_bd" name="pass_bd" type="hidden" value="'.$this->pass_db_txt.'">';
- echo '<input id="usuario_ftp" name="usuario_ftp" type="hidden" value="'.$this->usuario_ftp_txt.'">';
- echo '<input id="pass_ftp" name="pass_ftp" type="hidden" value="'.$this->pass_ftp_txt.'">';
- echo '<input id="ip4" name="ip4" type="hidden" value="'.$this->ip4_pdf.'">';
- echo '<input id="url_db" name="url_db" type="hidden" value="'.$this->url_db.'">';
- echo '<input id="dominio_nuevo" name="dominio_nuevo" type="hidden" value="'.$eldom.'">';
- echo '<input type="submit" class="btn btn-default formbutton-success" value="Descargar PDF">';
- echo '</form>';
-
- echo '<div id="resp"></div>';
-
- }
-
-
- function urlBBDD($idBBDD, $servidor_id){
-
- global $app, $conf;
-
- $dbData = $app->db->queryOneRecord(
- "SELECT server_id, database_name FROM web_database WHERE database_id = ?", $idBBDD);
- $serverData = $app->db->queryOneRecord(
- "SELECT server_name FROM server WHERE server_id = ?", $servidor_id);
-
- $app->uses('getconf');
- $global_config = $app->getconf->get_global_config('sites');
- $web_config = $app->getconf->get_server_config($servidor_id, 'web');
- //print "<pre>"; print_r($global_config); print "</pre>\n";
- //print "<pre>"; print_r($web_config); print "</pre>\n";
- /*
- * We only redirect to the login-form, so there is no need, to check any rights
- */
-
- if($global_config['phpmyadmin_url'] != '') {
- $phpmyadmin_url = $global_config['phpmyadmin_url'];
- $phpmyadmin_url = str_replace(array('[SERVERNAME]', '[DATABASENAME]'), array($serverData['server_name'], $dbData['database_name']), $phpmyadmin_url);
- //header('Location: '.$phpmyadmin_url);
- $this->url_db = $phpmyadmin_url;
- //print('la url ' . $phpmyadmin_url);
- } /*else {
- isset($_SERVER['HTTPS'])? $http = 'https' : $http = 'http';
- if($web_config['server_type'] == 'nginx') {
- //header('Location: http://' . $serverData['server_name'] . ':8081/phpmyadmin');
- print('la url http://' . $serverData['server_name'] . ':8081/phpmyadmin');
- } else {
- //header('Location: ' . $http . '://' . $serverData['server_name'] . '/phpmyadmin');
- print('la url http://' . $serverData['server_name'] . ':8081/phpmyadmin');
- }
- }*/
- }
-
- //Expresiones regulares para comprobar si es subdominio
- function comprobarSubDominios($subdom) {
- global $app, $conf;
-
- $patronSubDominos = "/(.*?)\.(.*)$/";
- $patronWWW = "/^w{3}/";
-
- //Se comprueba que no tenga 3 w "www" al principio del nombre del dominio o subdomino
- $encontradoWWW = preg_match($patronWWW, $subdom, $coincidencias);
- if($encontradoWWW){
- $app->tform->errorMessage = $app->tform->wordbook['error_dominio_www'];
- return;
- }
- //print "<pre>"; print_r($subdom); print "</pre>\n";
-
- //Si el dominio tiene mas de dos puntos, es incorrecto
- if(substr_count($subdom,".") > 2) {
- $this->es_subdominio = false;
- $this->dominio_error = true;
- $app->tform->errorMessage = $app->tform->wordbook['error_dominio_mas_puntos'];
- //return;
-
- }else if(substr_count($subdom,".") == 2){
- $this->encontrado = preg_match($patronSubDominos, $subdom, $coincidencias);
- //print "<pre>"; print_r($coincidencias); print "</pre>\n";
-
- $this->subdominio = $coincidencias[0];
- $this->dominio = $coincidencias[2];
-
- $this->es_subdominio = true;
- }
-
- return $this->es_subdominio;
- }
-
-
- public $cli_id;
- public $cli_grupo_id;
- public $sys_usuario_id;
- public $sys_grupo_id;
-
- function controlUserGrupoId(){
- global $app, $conf;
-
- $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
-
- //* Client: If the logged in user is not admin and has no sub clients (no reseller)
- if($_SESSION["s"]["user"]["typ"] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])) {
-
- $this->cli_id = $_SESSION["s"]["user"]["client_id"];
- $this->cli_grupo_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
- $this->sys_usuario_id = $_SESSION["s"]["user"]["sys_userid"];
- $this->sys_grupo_id = $_SESSION["s"]["user"]["sys_groupid"];
- //echo('Es cliente cli_id ' . $this->cli_id . ' cli_grupo_id ' . $this->cli_grupo_id . ' sys_usuario ' . $this->sys_usuario_id . ' sys_grupo ' . $this->sys_grupo_id);
-
- } else {
- //Captura de los distintos ids del cliente y usuario de sistema.
- //combinando un query a las dos tablas sys_group y sys_user que comparten el client_id.
- //print "<pre>Seleccionado: "; print_r($fields['client_group_id']); print "</pre>\n";
- if($fields['client_group_id']==0) {
- //En la tabla sys_user el client_id 0 es admin. En sys_group este valor es 0
- $this->cli_id = 0;
- $this->cli_grupo_id = 1;
- $this->sys_usuario_id = 1;//$this->cli_id;
- $this->sys_grupo_id = 0; //$this->cli_grupo_id;//0
- //echo('Quien es ' . $_SESSION["s"]["user"]["typ"]);
- }else{
- //echo('Quien es else ' . $_SESSION["s"]["user"]["typ"]);
- $client = $app->db->queryOneRecord(
- 'SELECT sys_user.userid, sys_user.sys_userid, sys_user.sys_groupid, sys_user.default_group, sys_user.client_id
- FROM sys_group, sys_user
- WHERE sys_group.client_id = sys_user.client_id and sys_group.groupid = ?', $fields['client_group_id']);
-
- $this->cli_id = $client['client_id'];
- $this->cli_grupo_id = $client['default_group'];
- $this->sys_usuario_id = $client['userid'];//$client['sys_userid'];
- $this->sys_grupo_id = $this->cli_grupo_id;//$client['sys_groupid'];
- //echo('Es cliente cli_id ' . $this->cli_id . ' cli_grupo_id ' . $this->cli_grupo_id . ' sys_usuario ' . $this->sys_usuario_id . ' sys_grupo ' . $this->sys_grupo_id);
- }
- }
- //print "<pre>Valores : "; print_r($this->cli_id); print "</pre>\n";
- //print " cli_id " . $this->cli_id . ' cli_grupo ' . $this->cli_grupo_id . ' sys_usuario ' . $this->sys_usuario_id . ' sys grupo ' . $this->sys_grupo_id;
-
- }
-
- //Crear subdominio
- function crearSubDominio($remoto, $campoSubDominio){
- global $app, $conf;
-
- $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
- //COMO LE PASO EL DOMINIO CORRECTO NO ES NECESARIO PONER EL % EN LA SQL AÑADO EL PUNTO.
- //EL PROBLEMA ES QUE CON UN DOMINIO .COM TOMA POR VALIDO UN .CO POR EL %
- //NO --> ('SELECT server_id, name FROM dns_rr WHERE name LIKE "'.$this->dominio.'%"');
- $existeDominioParaSubDominio = $app->db->queryOneRecord(
- 'SELECT server_id, name FROM dns_rr WHERE name LIKE "'.$this->dominio.'."');
-
- // print "<pre>En crearSubDominio campo que se le pasa subdominio es: "; print_r($campoSubDominio); print "</pre>\n";
- //Compruebo que el subdominio no existe consultando la tabla web_domain.
- $existeSubDominioWeb = $app->db->queryOneRecord(
- 'SELECT domain_id, domain FROM web_domain
- WHERE domain = "'.$campoSubDominio.'"');
-
- //Compruebo que el subdominio no existe consultando la tabla dns_rr
- $existeSubDominioTipoA = $app->db->queryOneRecord(
- 'SELECT name, type FROM dns_rr
- WHERE name = "'.$campoSubDominio.'" AND type = "A"');
-
- if(!$existeDominioParaSubDominio['name']){
- $this->subdom_error = true;
- $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
- // print "<pre>Error En crearSubDominio campo comprobacion dns_rr es: "; print_r($existeDominioParaSubDominio); print "</pre>\n";
- $this->onError();
- return;
- }
- // print "<pre>En crearSubDominio campo comprobacion dns_rr es: "; print_r($existeDominioParaSubDominio); print "</pre>\n";
- //print '<pre>El Sub existe '. $existeSubDominio['domain'];
- if($existeSubDominioWeb['domain']){
- $this->subdom_error = true;
- $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
- $this->onError();
- return $this->subdom_error;
- }
-
- if($existeSubDominioTipoA['name']){
- $this->subdom_error = true;
- $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
- $this->onError();
- return $this->subdom_error;
- }
-
- //$camDominio = $app->db->queryOneRecord('SELECT domain_id, domain FROM domain WHERE domain = "'.$this->dominio.'"');
- $camDominio = $app->db->queryOneRecord('SELECT origin FROM dns_soa WHERE origin LIKE "'.$this->dominio.'."');
- //$camDominio = $app->db->queryOneRecord('SELECT origin FROM dns_soa WHERE origin LIKE "'.$campoSubDominio.'%"');
- $camDnsRR = $app->db->queryOneRecord('SELECT server_id, zone FROM dns_rr WHERE name LIKE "'.$this->dominio.'."');
-
- //Para los registros tipo A la ip tiene que ser tipo IPv4
- $camServIP = $app->db->queryOneRecord(
- "SELECT ip_address FROM server_ip
- WHERE server_id = ".$camDnsRR['server_id']." AND ip_type='IPv4'");
-
- //print_r($camDominio);
- //print_r($camDnsRR);
-
- //Si el dominio NO existe mostramos mensaje de error y salimos de la ejecución
- if(!$camDominio['origin']){
- $this->subdom_error = true;
- $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
- $this->onError();
- //return;
- //print 'No existe el dominio';
- return $this->subdom_error;
-
- } else {
- //Parametros para la creación de subdominios
- $paramSubDominios = array(
- 'server_id' => $camDnsRR['server_id'],
- 'zone' => $camDnsRR['zone'],
- 'name' => $this->subdominio,
- 'type' => 'a',
- 'data' => $camServIP['ip_address'],
- //'aux' => '0',
- 'ttl' => '3600',
- 'active' => 'y',
- //comento el campo stamp, ya que introducia solo ceros en la bbdd
- //'stamp' => time(),
- 'serial' => '1',
- );
-
- //echo ('<br>El client_id GLOBAL ' . $this->cli_id . " <br>");
- // client group id
- /*$res = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($fields['client_group_id']));
- $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);//$res['groupid'];
- echo ('El client group id seleccion ' . $client_group_id . " <br>");
- echo ('El groupid de la tabla sys_group ' . $res['groupid'] . " ");*/
- //print "<pre>"; print_r($paramSubDominios); print "</pre>\n";
- //Inserto en bbdd usando la clase remoto que se la he pasado en parámetros de la función
- //$resultado = $remoto->insert_query('../dns/form/dns_a.tform.php', $fields['client_id'], $paramSubDominios);
- $resultado = $remoto->insert_query('form/dns_a_webdns.tform.php', $this->cli_id, /*$fields['client_group_id'],*/ $paramSubDominios);
- $remoto->dns_registro_tipo_a_after_insert($this->cli_grupo_id);
- echo '<br><div class="alert alert-success"><br>
- Se ha dado de alta Web y Subdominio, <b>'.$this->subdominio.'</b>, ¡Correctamente!
- <br><br></div></br>';
-
- //$this->onShow();
- }
- }
-
- function crearSitioWebSubdominio($remoto){
- global $app, $conf;
-
- $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
-
- /* print "<pre>DNS SERVER ";print_r($this->dns_serv);print "</pre>\n";
- print "<pre>WEB SERVER ";print_r($this->web_serv);print "</pre>\n";
- print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
- print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
- print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
- print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";
- print "<pre>IP6 WEB LA OTRA ";print_r($this->ip6_ultima['ip_address']);print "</pre>\n";
- */
- //add site
- $paramsite = array(
- //"sys_userid" => $this->sys_usuario_id,
- //"sys_groupid" => $this->cli_grupo_id,
- 'type' => 'vhost',
- 'domain' => $fields['domain'], //$this->subdominio,
- 'server_id' => $this->web_serv, //$server_id,
- 'ip_address' => '*',
- 'ipv6_address' =>$this->ip6_servidor_web['ip_address'],
- 'traffic_quota' => '-1',
- 'hd_quota' => '0',
- 'cgi' => 'y',
- 'ssi' => 'y',
- 'suexec' => 'y',
- 'ruby' => 'n',
- 'python' => 'n',
- 'perl' => 'n',
- 'errordocs' => '1',
- 'subdomain' => '',
- 'php' => 'php-fpm',
- 'fastcgi_php_version' => '',
- 'seo_redirect' => '',
- 'rewrite_to_https' => 'n',
- 'allow_override' => 'All',
- 'http_port' => 80,
- 'https_port' => 443,
- 'apache_directives' => '',
- 'nginx_directives' => '',
- 'php_fpm_use_socket' => 'y',
- 'pm' => 'ondemand',
- 'pm_max_children' => 10,
- 'pm_start_servers' => 1,
- 'pm_min_spare_servers' => 1,
- 'pm_max_spare_servers' => 5,
- 'pm_process_idle_timeout' => 10,
- 'pm_max_requests' => 0,
- 'custom_php_ini' => '',
- 'active' => 'y',
- 'document_root' => '-',
- 'system_user' => '-',
- 'system_group' => '-',
- 'log_retention' => 30,
- 'client_group_id' => $this->cli_grupo_id, //$client_group_id,
- );
-
- //print "<pre> Parametros:"; print_r($paramsite); print "</pre>\n";
- /*print '<pre> cliente id ' . $fields['client_id'];
- print "<pre>";print_r($fields);print "</pre>\n" . $fields['client_id'];*/
- //print '<pre>DNS IPV6 ' . $dns_ip_servidor_ipv6['ip_address'];
-
-
- //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO
- //DE LO QUE SE QUIERE CREAR EN ESTE CASO SITIO WEB
- $tform_def_file = "../sites/form/web_vhost_domain.tform.php";
- $app->tform->loadFormDef($tform_def_file);
- //El último parámetro es para lanzar un evento que llama a la función on_after_insert que prepara
- //los campos document_root, system_user y system_group
- //$site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php', $fields['client_group_id'], $paramsite, 'sites:web_vhost_domain:on_after_insert');
- $site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php',
- $this->cli_id, /*$cliente_id_seleccionado,*/
- $paramsite, 'sites:web_vhost_domain:on_after_insert');
-
- //IMPORTANTE. HAY QUE CARGAR EL FORMULARIO DE WEBDNS PARA QUE ENCUENTRE EL TAB.
- $tform_def_file = "form/new_service_webdns.tform.php";
- $app->tform->loadFormDef($tform_def_file);
- }
-
- public $ip4_servidor_dns;
- public $ip6_servidor_dns;
- public $ip4_servidor_web;
- public $ip6_servidor_web;
- public $ip4_servidor_bbdd;
- public $ip6_servidor_bbdd;
- public $ip4_servidor_ftp;
- public $ip6_servidor_ftp;
- public $dns_serv;
- public $web_serv;
- public $bbdd_serv;
- public $ftp_serv;
-
- function tieneServidorIPs(){
- global $app, $conf;
-
- $this->controlUserGrupoId();
-
- $app->uses('getconf');
- $global_config_sitio = $app->getconf->get_global_config('sites');
- $global_config_dns = $app->getconf->get_global_config('dns');
-
- if(!$global_config_dns['default_dnsserver']) {
- $app->tform->errorMessage = $app->tform->wordbook['error_no_servidor_default']. 'DNS.';
- $this->onError();
- return true;
- } else if(!$global_config_sitio['default_webserver']) {
- $app->tform->errorMessage = $app->tform->wordbook['error_no_servidor_default']. 'WEB.';
- $this->onError();
- return true;
- } else if(!$global_config_sitio['default_dbserver']) {
- $app->tform->errorMessage = $app->tform->wordbook['error_no_servidor_default']. 'DB.';
- $this->onError();
- return true;
- }
-
- //print "<pre>WEB SERVER por defecto ";print_r($global_config_sitio);print "</pre>\n";
- //print "<pre>DNS SERVER por defecto ";print_r($global_config_dns);print "</pre>\n";
-
- //El cliente 1 es admin.
- //Recupero los servidores asignados por defecto y se los asigno a admin o al usuario
- //que no tenga asignado ninguno.
- if($this->cli_id == 0) {
- $this->dns_serv = $global_config_dns['default_dnsserver'];//1;
- $this->web_serv = $global_config_sitio['default_webserver'];//1;
- $this->bbdd_serv = $global_config_sitio['default_dbserver'];//1;
- $this->ftp_serv = $global_config_sitio['default_webserver'];//1;
- //print "<pre>tieneServidorIPs el cli_id "; print_r($this->cli_id . ' el servidor ' . $this->dns_serv); print "</pre>\n";
- }else{
- $servidores = $app->db->queryOneRecord(
- "SELECT client_id, dns_servers, web_servers, db_servers FROM client
- WHERE client_id = ". $this->cli_id);
-
- $this->dns_serv = $servidores['dns_servers'];
- $this->web_serv = $servidores['web_servers'];
- $this->bbdd_serv = $servidores['db_servers'];
- //para el ftp el servidor es el mismo que para el sitio web.
- $this->ftp_serv = $servidores['web_servers'];
-
- //Si el cliente no tiene asignado un servidor se añade por defecto al 1
- if(!$this->dns_serv){
- $this->dns_serv = $global_config_dns['default_dnsserver'];//1;
-
- }
- //Si el cliente no tiene asignado un servidor se añade por defecto al 1
- if(!$this->web_serv){
- $this->web_serv = $global_config_sitio['default_webserver'];//1;
- }
- //Si el cliente no tiene asignado un servidor se añade por defecto al 1
- if(!$this->bbdd_serv){
- $this->bbdd_serv = $global_config_sitio['default_dbserver'];//1;
- }
- //Si el cliente no tiene asignado un servidor se añade por defecto al 1
- if(!$this->ftp_serv){
- $this->ftp_serv = $global_config_sitio['default_webserver'];//1;
- }
- }
- /*print "<pre>DNS SERVER ";print_r($this->dns_serv);print "</pre>\n";
- print "<pre>WEB SERVER ";print_r($this->web_serv);print "</pre>\n";
- print "<pre>DB SERVER ";print_r($this->bbdd_serv);print "</pre>\n";
- print "<pre>FTP SERVER ";print_r($this->ftp_serv);print "</pre>\n";*/
-
- //El cliente 1 es admin
- //Captura de las ips del servidor dns
- if($this->cli_id == 0){
- //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
- //Alguno de los dos tiene que existir por configuración de ispconfig.
- $this->ip4_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
- $this->ip6_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
-
- if(!$this->ip4_servidor_dns){
- $this->ip4_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
- }
- if(!$this->ip6_servidor_dns){
- $this->ip6_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
- }
- }else{//Comprobamos si el cliente tiene servidor asignado, si no lo tiene asignamos el que admin a seleccionado
- //para este servidor.
- $this->ip4_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address
- FROM server_ip
- WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
- $this->ip6_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address
- FROM server_ip
- WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->dns_serv.'"AND ip_type="IPv6"');
-
- //si no tiene asignado le damos el de admin.
- if(!$this->ip4_servidor_dns){
- //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1. Es admin ya que este cliente no tiene ip4 ni ip6 asignadas
- //Tomamos las de admin.
- //Alguno de los dos tiene que existir por configuración de ispconfig.
- $this->ip4_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
-
- if(!$this->ip4_servidor_dns){
- $this->ip4_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
- }
- }
- if(!$this->ip6_servidor_dns){
- //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1. Es admin ya que este cliente no tiene ip4 ni ip6 asignadas
- //Tomamos las de admin.
- //Alguno de los dos tiene que existir por configuración de ispconfig.
- //$this->ip4_servidor_dns = $app->db->queryOneRecord('SELECT ip_type, ip_address FROM server_ip WHERE client_id = "0" AND ip_type="IPv4"');
- $this->ip6_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
-
- if(!$this->ip6_servidor_dns){
- $this->ip6_servidor_dns = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
- }
- }
- }
-
- //Captura de las ips del servidor web
- if($this->cli_id == 0){
- //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
- //Alguno de los dos tiene que existir por configuración de ispconfig.
- $this->ip4_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
- $this->ip6_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
-
- /*if(!$this->ip4_servidor_web){
- $this->ip4_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
- }
- if(!$this->ip6_servidor_web){
- $this->ip6_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
- }*/
- }else{//Comprobamos si el cliente tiene servidor asignado
- $this->ip4_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address
- FROM server_ip
- WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
- $this->ip6_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address
- FROM server_ip
- WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->web_serv.'"AND ip_type="IPv6"');
-
- //si no tiene asignado le damos el de admin.
- if(!$this->ip4_servidor_web){
- $this->ip4_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
-
- /*if(!$this->ip4_servidor_web){
- $this->ip4_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
- }*/
- }
- if(!$this->ip6_servidor_web){
- $this->ip6_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
-
- /*if(!$this->ip6_servidor_web){
- $this->ip6_servidor_web = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
- }*/
- }
- }
- //Captura de las ips del servidor bbdd
- if($this->cli_id == 0){
- //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
- //Alguno de los dos tiene que existir por configuración de ispconfig.
- $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
- $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
-
- /*if(!$this->ip4_servidor_bbdd){
- $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
- }
- if(!$this->ip6_servidor_bbdd){
- $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
- }*/
- }else{//Comprobamos si el cliente tiene servidor asignado
- $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address
- FROM server_ip
- WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
- $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address
- FROM server_ip
- WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->bbdd_serv.'"AND ip_type="IPv6"');
-
- //si no tiene asignado le damos el de admin.
- if(!$this->ip4_servidor_bbdd){
- //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1. Es admin ya que este cliente no tiene ip4 ni ip6 asignadas
- //Tomamos las de admin.
- //Alguno de los dos tiene que existir por configuración de ispconfig.
- $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
-
- /*if(!$this->ip4_servidor_bbdd){
- $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
- }*/
- }
- if(!$this->ip6_servidor_bbdd){
- $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
-
- /*if(!$this->ip6_servidor_bbdd){
- $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
- 'SELECT ip_type, ip_address FROM server_ip
- WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
- }*/
- }
- }
- //para el servidor ftp no se hacen comprobaciones
- //ya que las ips son las mismas que para el servidor web.
-
-
- //$la_ip4 = $app->db->queryOneRecord("SELECT ip_type, ip_address FROM server_ip WHERE ip_type='IPv4'");
- $this->ip4_pdf = $this->ip4_servidor_dns['ip_address'];//$dns_ip_servidor['ip_address'];//$la_ip4['ip_address'];
- /*print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
- print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
- print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
- print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";
- print "<pre>IP4 BBDD ";print_r($this->ip4_servidor_bbdd);print "</pre>\n";
- print "<pre>IP6 BBDD ";print_r($this->ip6_servidor_bbdd);print "</pre>\n";
- echo('El cliente ' . $this->cli_id . '<br>');*/
- if(!$this->ip4_servidor_dns['ip_address']){
-
- $servicio_dns = $app->db->queryOneRecord(
- 'SELECT server_id, dns_server, server_name FROM server
- WHERE server_id = "'.$this->dns_serv.'"');
-
- $nom_serv_dns = $servicio_dns['server_name'];
-
- $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_dns;
- $this->onError();
- return true;
- }
- if(!$this->ip6_servidor_dns['ip_address']){
-
- $servicio_dns = $app->db->queryOneRecord(
- 'SELECT server_id, dns_server, server_name FROM server
- WHERE server_id = "'.$this->dns_serv.'"');
-
- $nom_serv_dns = $servicio_dns['server_name'];
-
- $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor '. $nom_serv_dns;
- $this->onError();
- return true;
- }
- if(!$this->ip4_servidor_web['ip_address']){
-
- $servidor_web = $app->db->queryOneRecord(
- 'SELECT server_id, web_server, server_name FROM server
- WHERE server_id = "'.$this->web_serv.'"');
-
- $nom_serv_web = $servidor_web['server_name'];
-
- $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_web;
- $this->onError();
- return true;
- }
- if(!$this->ip6_servidor_web['ip_address']){
-
- $servidor_web = $app->db->queryOneRecord(
- 'SELECT server_id, web_server, server_name FROM server
- WHERE server_id = "'.$this->web_serv.'"');
-
- $nom_serv_web = $servidor_web['server_name'];
-
- $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor ' . $nom_serv_web;
- $this->onError();
- return true;
- }
- if(!$this->ip4_servidor_bbdd['ip_address']){
-
- $servicio_db = $app->db->queryOneRecord(
- 'SELECT server_id, db_server, server_name FROM server
- WHERE server_id = "'.$this->bbdd_serv.'"');
-
- $nom_serv_db = $servicio_db['server_name'];
-
- $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_db;
- $this->onError();
- return true;
- }
- if(!$this->ip6_servidor_bbdd['ip_address']){
-
- $servicio_db = $app->db->queryOneRecord(
- 'SELECT server_id, db_server, server_name FROM server
- WHERE server_id = "'.$this->bbdd_serv.'"');
-
- $nom_serv_db = $servicio_db['server_name'];
-
- $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor ' . $nom_serv_db;
- $this->onError();
- return true;
- }
- return false;
- }
-
- //Comprueba si los servidores asignados al usuario seleccionado tiene los servicios activos para cada caso.
- function servidoresActivados(){
- global $app, $conf;
-
- $servicio_web = $app->db->queryOneRecord(
- 'SELECT server_id, web_server, server_name FROM server
- WHERE server_id = "'.$this->web_serv.'"');
-
- $nom_serv_web = $servicio_web['server_name'];
-
- $servicio_dns = $app->db->queryOneRecord(
- 'SELECT server_id, dns_server, server_name FROM server
- WHERE server_id = "'.$this->dns_serv.'"');
-
- $nom_serv_dns = $servicio_dns['server_name'];
-
- $servicio_ftp = $app->db->queryOneRecord(
- 'SELECT server_id, file_server, server_name FROM server
- WHERE server_id = "'.$this->ftp_serv.'"');
-
- $nom_serv_ftp = $servicio_ftp['server_name'];
-
- $servicio_db = $app->db->queryOneRecord(
- 'SELECT server_id, db_server, server_name FROM server
- WHERE server_id = "'.$this->bbdd_serv.'"');
-
- $nom_serv_db = $servicio_db['server_name'];
-
- //print "<pre>Servidor WEB ";print_r($servicio_web);print "</pre>\n";
- if($servicio_web['web_server'] == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_web . ' el servicio WEB.';
- $this->onError();
- return true;
- }
- //print "<pre>Servidor DNS ";print_r($servicio_dns);print "</pre>\n";
- if($servicio_dns['dns_server'] == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_dns . ' el servicio DNS.';
- $this->onError();
- return true;
- }
- //print "<pre>Servidor FTP ";print_r($servicio_ftp);print "</pre>\n";
- if($servicio_ftp['file_server'] == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_ftp . ' el servicio FTP.';
- $this->onError();
- return true;
- }
- //print "<pre>Servidor DB ";print_r($servicio_db);print "</pre>\n";
- if($servicio_db['db_server'] == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_db . ' el servicio DB.';
- $this->onError();
- return true;
- }
-
- /*$servidores = $app->db->queryAllRecords(
- 'SELECT server_id, server_name, web_server, dns_server, file_server, db_server FROM server');
-
- foreach($servidores as $servidor){
- $serv_web = $servidor['web_server'];
- $serv_dns = $servidor['dns_server'];
- $serv_ftp = $servidor['file_server'];
- $serv_db = $servidor['db_server'];
- $nombre_server = $servidor['server_name'];
- //print "<pre>Todos los servidores ";print_r($servidor);print "</pre>\n";
- //Si alguno de los servidores no esta activo, mostramos error.
- if($serv_web == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nombre_server . ' el servicio WEB';
- $this->onError();
- return true;
- } else if($serv_dns == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nombre_server . ' el servicio DNS';
- $this->onError();
- return true;
- } else if($serv_ftp == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nombre_server . ' el servicio FTP';
- $this->onError();
- return true;
- } else if($serv_db == 0){
- $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nombre_server . ' el servicio DB';
- $this->onError();
- return true;
- }*/
-
- //}
- return false;
- }
-
- //Comprobación de que tenemos instalada nuestra plantilla
- function plantillaWebDNS(){
- global $app;
-
- if(!$app->db->queryOneRecord("SELECT name FROM dns_template WHERE name = 'webdns'")) {
- $app->tform->errorMessage = $app->tform->wordbook['error_plantilla_webdns'];
- $this->onError();
- return true;
- }
- }
-
- //Comprueba que no exista el dominio y que no tenga sitio web, puede tener sitio web y no tener dns.
- function existeDominio($campos){
- global $app, $conf;
-
- if($app->db->queryOneRecord('SELECT * FROM dns_soa WHERE origin LIKE "'.$campos['domain'].'."')) {
- $app->tform->errorMessage = $app->tform->wordbook['domain_error_unique'];
- }
-
- if($app->db->queryOneRecord('SELECT domain_id, domain FROM web_domain WHERE domain = "'.$campos['domain'].'"')) {
- $app->tform->errorMessage = $app->tform->wordbook['error_sitio_web_existe'];
- }
- //IMPORTANTE. AQUI CONTROLAMOS LOS ERRORES QUE SE VALIDAN EN EL FORMULARIO, EN ESTE CASO EL CAMPO DEL DOMINIO.
- if($app->tform->errorMessage)
- {
- $this->onError();
- return true;
- }
- }
-
- public $ip4_ultima;
- public $ip6_ultima;
- //Creación del las dns y sitio web para un dominio.
- function crearDnsSitioWeb($remoto){
- global $app, $conf;
- $remote = new remote_actions;
- //Carga de los campos del formulario.
- $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
-
- //Carga del formulario dns_soa para guardar en base de datos.
- $tform_def_file = "../dns/form/dns_soa.tform.php";
- $app->tform->loadFormDef($tform_def_file);
-
- //Carga y seleccion de dns_template, si no esta creado se informa de que tiene que crearse.
- $template_record = $app->db->queryOneRecord(
- "SELECT * FROM dns_template WHERE visible = 'Y' AND name = 'webdns'"); /*'open6hosting'");*/
-
-
- /*print "<pre>DNS SERVER ";print_r($this->dns_serv);print "</pre>\n";
- print "<pre>WEB SERVER ";print_r($this->web_serv);print "</pre>\n";
- print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
- print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
- print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
- print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";*/
-
- //Si el servidor es el que tiene asignado el cliente o el de admin por defecto, le damos esta ip4
- if($this->dns_serv && $this->ip4_servidor_dns){
- $this->ip4_ultima = $this->ip4_servidor_dns;
- }
-
- if($this->dns_serv && $this->ip6_servidor_dns){
- $this->ip6_ultima = $this->ip6_servidor_dns;
- }
-
- if($this->web_serv && $this->ip4_servidor_web){
- $this->ip4_ultima = $this->ip4_servidor_web;
- }
-
- if($this->web_serv && $this->ip6_servidor_web){
- $this->ip6_ultima = $this->ip6_servidor_web;
- }
-
- $tpl_content = $template_record['template'];
- // Reemplazo la variable que nos encontramos en base de datos por el valor que se ha introducido en el formulario
- $tpl_content = str_replace('{DOMAIN}', $fields['domain'], $tpl_content);
-
- //Carga de los datos en las variables de las ips.
- $tpl_content = str_replace('{IP}', $this->ip4_ultima['ip_address'],/*$dns_ip_servidor['ip_address'],*/ $tpl_content);
- $tpl_content = str_replace('{IPV6}', $this->ip6_ultima['ip_address'], /*$dns_ip_servidor_ipv6['ip_address'],*/ $tpl_content);
-
-
- $enable_dnssec = 'N';//(($_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
-
- // Insert the soa record
- $sys_userid = $this->cli_id;//$cliente_id_seleccionado;//$fields['client_group_id'];
- $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" => $this->sys_usuario_id,//$sysUsuarioId,//$fields['client_group_id'],
- "sys_groupid" => $this->cli_grupo_id,//$cliente_groupid,//$client_group_id,
- "sys_perm_user" => 'riud',
- "sys_perm_group" => 'riud',
- "sys_perm_other" => '',
- "server_id" => $this->dns_serv, //$dns_servidor,//$server_id,//$dns_servidor, //$server_id,//$dns_servidor['default_dnsserver'],
- "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');
-
- $remote->dns_soa_after_insert($dns_soa_id, $this->cli_grupo_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" => $this->sys_usuario_id,//$sysUsuarioId, //$fields['client_group_id'],
- "sys_groupid" => $this->cli_grupo_id,//$cliente_groupid, //$client_group_id,
- "sys_perm_user" => 'riud',
- "sys_perm_group" => 'riud',
- "sys_perm_other" => '',
- "server_id" => $this->dns_serv,
- "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');
-
- $remote->dns_rr_after_insert($dns_rr_id, $this->cli_grupo_id);
- }
- }
- //sites_web_domain_add
- $tform_def_file = "../sites/form/web_vhost_domain.tform.php";
- $app->tform->loadFormDef($tform_def_file);
-
- //print_r($fields);
- //echo('La sesión user id ' . $_SESSION['s']['user']['userid']);
- // add site
- $paramsite = array(
- 'type' => 'vhost',
- 'domain' => $fields['domain'],
- 'server_id' => $this->web_serv,// $web_servidor, //$server_id,//$dns_servidor['default_webserver'],
- //IMPORTANTE. Aquí no se ponen los campos sys_userid ni sys_groupid, el evento on_after_insert
- //'sys_userid' => $sysUsuarioId, //$fields['client_group_id'],//$sys_userid,
- //'sys_groupid' => $cliente_groupid,
- 'ip_address' => '*', //$dns_ip_servidor['ip_address'],
- 'ipv6_address' => $this->ip6_servidor_web['ip_address'], //$this->ip6_ultima['ip_address'], //$dns_ip_servidor_ipv6['ip_address'],
- 'traffic_quota' => '-1',
- 'hd_quota' => '0',
- 'cgi' => 'y',
- 'ssi' => 'y',
- 'suexec' => 'y',
- 'ruby' => 'n',
- 'python' => 'n',
- 'perl' => 'n',
- 'errordocs' => '1',
- 'subdomain' => 'www',
- 'php' => 'php-fpm',
- 'fastcgi_php_version' => '',
- 'seo_redirect' => '',
- 'rewrite_to_https' => 'n',
- 'allow_override' => 'All',
- 'http_port' => 80,
- 'https_port' => 443,
- 'apache_directives' => '',
- 'nginx_directives' => '',
- 'php_fpm_use_socket' => 'y',
- 'pm' => 'ondemand',
- 'pm_max_children' => 10,
- 'pm_start_servers' => 1,
- 'pm_min_spare_servers' => 1,
- 'pm_max_spare_servers' => 5,
- 'pm_process_idle_timeout' => 10,
- 'pm_max_requests' => 0,
- 'custom_php_ini' => '',
- 'active' => 'y',
- 'document_root' => '-',
- 'system_user' => '-',
- 'system_group' => '-',
- 'log_retention' => 30,
- 'client_group_id' => $this->cli_grupo_id,//$cliente_groupid, //$client_group_id,
- );
-
- //print 'Valores: ' . $dns_ip_servidor_ipv6 . " " . $formulario . " Parametros: " ;
- //print "<pre>"; print_r($paramsite); print "</pre>\n";
-
- /*print '<pre> cliente id ' . $fields['client_id'];
- print "<pre>";print_r($fields);print "</pre>\n";*/
- //print "<pre>Formulario ";print_r($formulario);print "</pre>\n";
-
- //$this->crearBaseDatosFtp($remote);
- //print 'DNS IPV6 ' . $dns_ip_servidor_ipv6['ip_address'];
-
- //IMPORTANTE. El último parámetro es para lanzar un evento que llama a la función on_after_insert
- //que prepara los campos document_root, system_user y system_group
- //$site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php', $fields['client_group_id'], $paramsite, 'sites:web_vhost_domain:on_after_insert');
-
- //IMPORTANTE. ESTE ES EL ÚNICO PLUGING QUE FUNCIONA.
- $site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php',
- $this->cli_id, /*$cliente_id_seleccionado,*/
- $paramsite, 'sites:web_vhost_domain:on_after_insert');
- //print 'Sitio id '. $site_id;
- }
-
- function onSubmit() {
- global $app, $conf;
-
- /*$sesionesLog = $_SESSION["s"]["user"]["typ"];
- $sesionesLog2 = $_SESSION["s"]["user"];
- $sesiones = $_SESSION;
- $sesionId = $_SESSION["s"]["id"];*/
-
- //print_r($sesiones);
- //print('la ssessison es ' .$ssionId);
- //print_r($sesionesLog2);
-
- //echo('(Sub)Prefix ' . $this->valor_prefix . '(Sub)Prefix ftp ' . $this->valor_prefix_ftp );
- if($this->plantillaWebDNS()){
- return;
- }
- //Carga de campos del formulario.
- $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
-
- //Creo la clase remote para usar las librerias
- $remote = new remote_actions;
-
- /*$sitiosBoom = new sitios_remoting;
- $sitiosBoom->test();*/
-
- if($this->tieneServidorIPs()){
- return;
- }
- if($this->servidoresActivados()){
- return;
- }
- //------INICIO LIMITES--------------------------------------------------------------------------------------------------
- $limitado = new limites($this->cli_grupo_id);
- $tieneLimitesDNS = $limitado->limClienteDns();
- $tieneLimitesWeb = $limitado->limClienteWebDominio();
- $tieneLimitesDB = $limitado->limClienteDB();
-
- if($tieneLimitesDNS || $tieneLimitesWeb || $tieneLimitesDB){
- return;
- }
- //------FIN LIMITES-----------------------------------------------------------------------------------------------------
- if($this->existeDominio($fields)){
- return;
- }
-
- //Esta variable nos llega por jQuery desde el htm para el control de errores en la vista.
- if($_POST['create'] != 1)
- {
- $app->tform->errorMessage = 'DUMMY';
- $app->tpl->setVar($this->dataRecord);
- $this->onShow();
- return;
- }
-
- /*echo ('Lo seleccionado ' . $fields['client_group_id'] . " <br>");
- echo ('Tabla sys_group --> client id ' . $this->cli_id . " <br>");
- echo ('Tabla sys_group --> groupid ' . $this->cli_grupo_id . " <br>");
-
- echo ('Tabla sys_user --> userid ' . $this->sys_usuario_id . " <br>");
- echo ('Tabla sys_user --> sys_groupid ' . $this->sys_grupo_id . " <br>");*/
- //print "Subdomino: " . $this->subdomino . "</p>\n Dominio: " . $this->domino;
- if($this->comprobarSubDominios($fields['domain'])){
-
- $this->crearSubDominio($remote, $fields['domain']);
- if(!$this->subdom_error){
- $this->crearSitioWebSubdominio($remote);
-
- //if($_SESSION["s"]["user"]["typ"] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])){
- // $this->crearBaseDatosFtpClientes($remote);
- //}else{
- $this->crearBaseDatosFtp($remote);
- //}
- }
-
- } else {
- if(!$this->dominio_error){
- $this->crearDnsSitioWeb($remote);
- //$variablePHP = "<script> document.write(test) </script>";
- //Si todo va bien, el resultado de la web y dns
- echo '<br><div class="alert alert-success"><br>
- Altas Web y DNS del dominio <b>'.$fields['domain'].'</b>, ¡Creadas correctamente!
- <br><br></div></br>';
-
- //IMPORTANTE, es necesario cargar nuestro formulario para poder ejecutar la función que crea
- //la base de datos y el ftp ya que hay datos que tomamos de el antes de ejecutarla.
- $app->tform->loadFormDef('form/new_service_webdns.tform.php');
- //if(!$app->auth->is_admin()){
- //if($_SESSION["s"]["user"]["typ"] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])){
- //$this->crearBaseDatosFtpClientes($remote);
- //}else{
- //echo('Esto es mental ' . $app->auth->is_admin());
- $this->crearBaseDatosFtp($remote);
- //}
- //}
- }else{
- $this->onError();
- return;
- }
-
- }
- //parent::onSubmit();
- }
- }
-
- /*class sitios_remoting extends remoting_sites {
- public function test(){
- echo('Texto test');
- }
- }*/
-
-
- class remote_actions extends remoting {
- public function insert_query($formdef_file, $client_id, $params, $event_identifier = '') {
- global $app;
-
- /*$sql = $this->insertQueryPrepare($formdef_file, $client_id, $params);
- echo(' Query ' . $sql);
- $app->uses('remoting_lib');
- $app->remoting_lib->loadUserProfile();*/
- //return $app->db->query($sql);//$this->insertQueryExecute($sql, $params, $event_identifier);
- //echo(' insertQueryPrepare ' . $this->insertQueryExecute($sql, $params, $event_identifier));
- return $this->insertQueryWebDNS($formdef_file, $client_id, $params, $event_identifier);
- }
-
- function insertQueryWebDNS($formdef_file, $client_id, $params, $event_identifier = '') {
- //$sql = $app->remoting->insertQueryPrepare($formdef_file, $client_id, $params);
- $sql = $this->insertQueryPrepareWebDNS($formdef_file, $client_id, $params);
- if($sql !== false) return $this->insertQueryExecuteWebDNS($sql, $params, $event_identifier);
- else return false;
- }
-
- function insertQueryPrepareWebDNS($formdef_file, $client_id, $params) {
- global $app;
-
- $app->uses('remoting_lib');
-
- //* load the user profile of the client
- //$app->remoting_lib->loadUserProfile($client_id);
-
- //* Load the form definition
- $app->remoting_lib->loadFormDef($formdef_file);
- //echo(' Base de datos ' . $app->remoting_lib->loadFormDef($formdef_file));
- //* Get the SQL query
- $sql = $app->remoting_lib->getSQL($params, 'INSERT', 0);
- /*if($app->remoting_lib->errorMessage != '') {
- throw new SoapFault('data_processing_error', $app->remoting_lib->errorMessage);
- return false;
- }*/
- $app->log('Executed insertQueryPrepareWebDNS', LOGLEVEL_DEBUG);
- return $sql;
- }
-
- function insertQueryExecuteWebDNS($sql, $params, $event_identifier = '') {
- global $app;
-
- $app->uses('remoting_lib');
-
- $app->db->query($sql);
-
- /*if($app->db->errorMessage != '') {
- throw new SoapFault('database_error', $app->db->errorMessage . ' '.$sql);
- return false;
- }*/
-
- if ( isset($params['_primary_id'] ))
- $insert_id = $params['_primary_id'];
- else
- $insert_id = $app->db->insertID();
-
- // set a few values for compatibility with tform actions, mostly used by plugins
- $this->id = $insert_id;
- $this->dataRecord = $params;
- $app->log('Executed insertQueryExecute, raising events now if any: ' . $event_identifier, LOGLEVEL_DEBUG);
- if($event_identifier != '') $app->plugin->raiseEvent($event_identifier, $this);
-
- //$app->uses('tform');
- //* Save changes to Datalog
- if($app->remoting_lib->formDef["db_history"] == 'yes') {
- //$new_rec = $app->remoting_lib->getDataRecord($insert_id);
- $new_rec = $this->getDataRecordWebDNS($insert_id);
- $app->remoting_lib->datalogSave('INSERT', $primary_id, array(), $new_rec);
- }
- return $insert_id;
- }
-
- function sites_ftp_user_after_insert() {
- global $app, $conf;
-
- $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
- //echo(' Valor FTP ' . $this->dataRecord["parent_domain_id"]);
- $server_id = $app->functions->intval($web["server_id"]);
- $dir = $web["document_root"];
- $uid = $web["system_user"];
- $gid = $web["system_group"];
-
- // Check system user and group
- if($app->functions->is_allowed_user($uid) == false || $app->functions->is_allowed_group($gid) == false) {
- $app->error('Invalid system user or group');
- }
-
- // The FTP user shall be owned by the same group then the website
- $sys_groupid = $app->functions->intval($web['sys_groupid']);
-
- $sql = "UPDATE ftp_user SET server_id = ?, dir = ?, uid = ?, gid = ?, sys_groupid = ? WHERE ftp_user_id = ?";
- $app->db->query($sql, $server_id, $dir, $uid, $gid, $sys_groupid, $this->id);
- }
-
- function dns_rr_after_insert($dns_rr_id, $cliente_grupo_id) {
- global $app, $conf;
- //echo(' el cliente grupo id ' . $cliente_grupo_id . ' el id tupla en dns_rr ' . $dns_rr_id);
- if($_SESSION["s"]["user"]["typ"] == 'user') {
- $app->db->datalogUpdate('dns_rr', array("sys_userid" => $cliente_grupo_id,
- "sys_groupid" => $cliente_grupo_id), 'id', $dns_rr_id);
- }
-
- if($_SESSION["s"]["user"]["typ"] == 'admin') {
- $app->db->datalogUpdate('dns_rr', array("sys_userid" => 1, //$cliente_grupo_id,
- "sys_groupid" => $cliente_grupo_id), 'id', $dns_rr_id);
- }
- }
-
- function dns_soa_after_insert($dns_soa_id, $cliente_grupo_id) {
- global $app, $conf;
- //echo(' el cliente grupo id ' . $cliente_grupo_id . ' el id tupla en dns_rr ' . $dns_soa_id . ' sys usuario ' . $sys_usuario_id);
- if($_SESSION["s"]["user"]["typ"] == 'user') {
- $app->db->datalogUpdate('dns_soa', array("sys_userid" => $cliente_grupo_id,
- "sys_groupid" => $cliente_grupo_id), 'id', $dns_soa_id);
- }
-
- if($_SESSION["s"]["user"]["typ"] == 'admin') {
- $app->db->datalogUpdate('dns_soa', array("sys_userid" => 1, //$cliente_grupo_id,
- "sys_groupid" => $cliente_grupo_id), 'id', $dns_soa_id);
- }
- }
-
- function dns_registro_tipo_a_after_insert($cli_grupo_id) {
- global $app, $conf;
- //echo(' el valor zone ' . $this->dataRecord["zone"]);
- //* Set the sys_groupid of the rr record to be the same then the sys_groupid of the soa record
- if($_SESSION["s"]["user"]["typ"] == 'user') {
- $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
- $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $soa['sys_groupid']), 'id', $this->id);
- }
- /*if($_SESSION["s"]["user"]["typ"] == 'admin') {
- $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
- $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $soa['sys_groupid']), 'id', $this->id);
- }*/
- if($app->auth->has_clients($_SESSION['s']['user']['userid'])) {
- $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
- $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $cli_grupo_id), 'id', $this->id);
- }
- //* Update the serial number of the SOA record
- /*$soa_id = $app->functions->intval($_POST["zone"]);
- $serial = $app->validate_dns->increase_serial($soa["serial"]);
- $app->db->datalogUpdate('dns_soa', array("serial" => $serial), 'id', $soa_id);*/
- }
-
- public function sites_database_user_after_add($client_id, $params){
- global $app, $conf;
- //echo('Plugeando');
- // if($_SESSION["s"]["user"]["typ"] == 'user' /*&& isset($this->dataRecord["client_group_id"])*/) {
- //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
- $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
- /* }
- if($_SESSION["s"]["user"]["typ"] == 'admin'/* && isset($this->dataRecord["client_group_id"])*///) {
- //echo('Plugeando ' .$app->functions->intval($this->dataRecord["client_group_id"]) . ' y ' . $client_id . ' id ' . $this->id);
- //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
- /* $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
- }
- if($app->auth->has_clients($_SESSION['s']['user']['userid'])/* && isset($this->dataRecord["client_group_id"])*///) {
- //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
- /* $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
- }
-
- $app->uses('sites_web_database_user_plugin');
- global $app;
- //Register for the events
- $app->plugin->registerEvent('sites:web_database_user:on_after_update', 'sites_web_database_user_plugin', 'sites_web_database_user_edit');
- $app->plugin->registerEvent('sites:web_database_user:on_after_insert', 'sites_web_database_user_plugin', 'sites_web_database_user_edit');
- */
- }
-
- public function sites_database_user_add($session_id, $client_id, $params, $event_identifier = '') {
- global $app;
- /*if(!$this->checkPerm($session_id, 'sites_database_user_add')) {
- throw new SoapFault('permission_denied', 'You do not have the permissions to access this function.');
- return false;
- }*/
- //echo(' la tablita ' . $this->formDef['db_table']);
- return $this->insertQueryWebDNS('../sites/form/database_user.tform.php', $client_id, $params, $event_identifier);
- }
-
- function getDataRecordWebDNS($primary_id) {
- global $app;
- $escape = '`';
- //$this->loadUserProfile();
- if(@is_numeric($primary_id)) {
- if($primary_id > 0) {
- // Return a single record
- //return $this->getDataRecordPadreWebDNS($primary_id);
- return $app->tform->getDataRecord($primary_id);
- //return parent::getDataRecord($primary_id);
- } elseif($primary_id == -1) {
- // Return a array with all records
- $sql = "SELECT * FROM ??";
- return $app->db->queryAllRecords($sql, $this->formDef['db_table']);
- } else {
- throw new SoapFault('invalid_id', 'The ID has to be > 0 or -1.');
- return array();
- }
- } elseif (@is_array($primary_id) || @is_object($primary_id)) {
- if(@is_object($primary_id)) $primary_id = get_object_vars($primary_id); // do not use cast (array)xxx because it returns private and protected properties!
- $sql_offset = 0;
- $sql_limit = 0;
- $sql_where = '';
- $params = array($this->formDef['db_table']);
- foreach($primary_id as $key => $val) {
- if($key == '#OFFSET#') $sql_offset = $app->functions->intval($val);
- elseif($key == '#LIMIT#') $sql_limit = $app->functions->intval($val);
- elseif(stristr($val, '%')) {
- $sql_where .= "?? like ? AND ";
- } else {
- $sql_where .= "?? = ? AND ";
- }
- $params[] = $key;
- $params[] = $val;
- }
- $sql_where = substr($sql_where, 0, -5);
- if($sql_where == '') $sql_where = '1';
- //$sql = "SELECT * FROM ?? WHERE ".$sql_where. " AND " . $this->getAuthSQLWebDNS('r', $this->formDef['db_table']);
- $sql = "SELECT * FROM ?? WHERE ".$sql_where. " AND " . $this->getAuthSQL('r', $this->formDef['db_table']);
- if($sql_offset >= 0 && $sql_limit > 0) $sql .= ' LIMIT ' . $sql_offset . ',' . $sql_limit;
- return $app->db->queryAllRecords($sql, true, $params);
- } else {
- $this->errorMessage = 'The ID must be either an integer or an array.';
- return array();
- }
- }
-
- /*function getDataRecordPadreWebDNS($primary_id) {
- global $app;
- $escape = '`';
- $sql = "SELECT * FROM ?? WHERE ?? = ? AND ".$this->getAuthSQLWebDNS('r', $this->formDef['db_table']);
- return $app->db->queryOneRecord($sql, $this->formDef['db_table'], $this->formDef['db_table_idx'], $primary_id);
- }*/
-
- function getAuthSQLWebDNS($perm, $table = '') {
- if($_SESSION["s"]["user"]["typ"] == 'admin' || $_SESSION['s']['user']['mailuser_id'] > 0) {
- return '1';
- } else {
- if ($table != ''){
- $table = ' ' . $table . '.';
- }
- $groups = ( $_SESSION["s"]["user"]["groups"] ) ? $_SESSION["s"]["user"]["groups"] : 0;
- $sql = '(';
- $sql .= "(" . $table . "sys_userid = ".$_SESSION["s"]["user"]["userid"]." AND " . $table . "sys_perm_user like '%$perm%') OR ";
- $sql .= "(" . $table . "sys_groupid IN (".$groups.") AND " . $table ."sys_perm_group like '%$perm%') OR ";
- $sql .= $table . "sys_perm_other like '%$perm%'";
- $sql .= ')';
-
- return $sql;
- }
- }
-
- public function sites_database_add($client_id, $params){
- global $app, $conf;
-
- //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO
- //DE LO QUE SE QUIERE CREAR EN ESTE CASO SITIO WEB
- $tform_def_file = "../sites/form/database.tform.php";
- $app->tform->loadFormDef($tform_def_file);
-
- $app->remoting_lib->loadFormDef('../sites/form/database.tform.php');
- //$app->tform->formDef('../sites/form/database.tform.php');
- //$sql = $app->remoting->insertQueryPrepare('../sites/form/database.tform.php', $client_id, $params);
- $sql = $this->insertQueryPrepareWebDNS('../sites/form/database.tform.php', $client_id, $params);
-
- if($sql !== false) {
- $app->uses('sites_database_plugin');
- //print_r($sql);
- $this->id = 0;
- $this->dataRecord = $params;
- //$app->uses('sites_database_plugin');
-
-
- //$app->sites_database_plugin->processDatabaseInsert($this);
- //$retval = $this->insertQueryExecute($sql, $params);
- $retval = $this->insertQueryExecuteWebDNS($sql, $params);
- $app->sites_database_plugin->processDatabaseInsert($this);
- //$app->plugin->raiseEvent('sites:web_database:on_after_insert', $this);
- // 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();
-
-
- //IMPORTENTE, es necesario estas líneas para que el botón del pdf funcione. Activa el javascript
- //echo '<script type="text/javascript">';
- //echo 'alert (password(7, false, 1));';
- //echo '</script>';
-
-
- ?>
-
- <!--IMPORTENTE, es necesario estas líneas para que el botón del pdf funcione. Activa el javascript -->
- <script type="text/javascript">
-
- /*var test = "PARALACLAVE";
- function getRandomInt(min, max){
- return Math.floor(Math.random() * (max - min + 1)) + min;
- }
-
- var clave = password(7, false, 1);
- function password(minLength, special, num_special){
- minLength = minLength || 10;
- if(minLength < 8) minLength = 8;
- var maxLength = minLength + 5;
- var length = getRandomInt(minLength, maxLength);
-
- var alphachars = "abcdefghijkmnopqrstuvwxyz";
- var upperchars = "ABCDEFGHJKLMNPQRSTUVWXYZ";
- var numchars = "23456789";
- var specialchars = "!@#_";
-
- if(num_special == undefined) num_special = 0;
- if(special != undefined && special == true) {
- num_special = Math.floor(Math.random() * (length / 4)) + 1;
- }
- var numericlen = getRandomInt(1, 2);
- var alphalen = length - num_special - numericlen;
- var upperlen = Math.floor(alphalen / 2);
- alphalen = alphalen - upperlen;
- var password = "";
-
- for(i = 0; i < alphalen; i++) {
- password += alphachars.charAt(Math.floor(Math.random() * alphachars.length));
- }
-
- for(i = 0; i < upperlen; i++) {
- password += upperchars.charAt(Math.floor(Math.random() * upperchars.length));
- }
-
- for(i = 0; i < num_special; i++) {
- password += specialchars.charAt(Math.floor(Math.random() * specialchars.length));
- }
-
- for(i = 0; i < numericlen; i++) {
- password += numchars.charAt(Math.floor(Math.random() * numchars.length));
- }
-
- password = password.split('').sort(function() { return 0.5 - Math.random(); }).join('');
-
- return password;
- }*/
-
- </script>
|