SQL y expresiones regulares por Pablo Sarria Pérez, Open6Hosting 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'); //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; /*$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'); //* 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); //* 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); // 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 = ''; //$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 .= "\r\n"; } } $app->tpl->setVar("client_group_id", $client_select); //* Es Admin } 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 = ""; //$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 .= "\r\n"; } } $app->tpl->setVar("client_group_id", $client_select); } 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'])); $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']); $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; $this->valor_prefix = $this->dataRecord['database_user_prefix'] = $dbuser_prefix; $this->valor_prefix_ftp = $this->dataRecord['username_prefix'] = $ftpuser_prefix; 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"]).'
'; //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.').'
'; } /* 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 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(); //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(); //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
"; 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
"; return true; } else { echo $claveGenerada . " NO válido
"; return false; } echo $claveGenerada . " es válido
"; 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(); $sitio_id = $app->db->queryOneRecord( 'SELECT domain_id, domain FROM web_domain WHERE domain = "'.$fields['domain'].'"'); $clavePass = $this->generaPass(); //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 "
 USUARIO BBDD "; print_r($db_user_params); print "
\n"; //print "
". $this->cli_id; //print "
". $this->usuario_db_txt; //print "
". $this->pass_db_txt; //print "
"; print_r($fields); print "
\n"; //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO //DE LO QUE SE QUIERE CREAR EN ESTE CASO BBDD. NO FUNCIONA SE LANZA EL AFTER INSERT EN NUESTRA FUNCION. $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'); $remoto->sites_database_user_after_add($this->cli_grupo_id, $db_user_params); $global_web_config = $app->getconf->get_server_config($this->web_serv, 'server'); $ip4_bbdd = $global_web_config; //echo(' ip4 bbdd ' . print_r($ip4_bbdd)); // add database $paramsBD = array( 'server_id' => $this->bbdd_serv, //$camDnsRR['server_id'], 'sysgroup_id' => $this->cli_grupo_id, //$this->sys_grupo_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' => 'y', 'remote_ips' => $ip4_bbdd['ip_address'], //'-1', 'active' => 'y' ); $this->nombre_db_txt = $paramsBD['database_name']; $db_id = $remoto->sites_database_add($this->cli_id, /*$this->cli_grupo_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'); //IMPORTANTE. AL NO PODER USAR LA FUNCION getDataRecord YA QUE NOS HACE ADMIN. //TENGO QUE LANZAR LA FUNCION sites_ftp_user_after_insert PARA SOLUCIONAR ESTE PROBLEMA Y NO getDataRecord(). //$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 "
 FTP "; print_r($ftp_params); print "
\n"; //print "
"; print_r($site_data); print "
\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. NO FUNCIONA. //$app->plugin->registerEvent('sites:ftp_user:on_after_insert'); //LO LANZAMOS DE NUESTRA FUNCION EXTRAIDA Y MODIFICADA DEL PLUGING QUE SE TENDRÍA QUE EJECUTAR PERO NO LO HACE.WHY? $remoto->sites_ftp_user_after_insert(); echo '

Altas de BBDD y FTP, ¡Correctas!

Usuario BBDD: '. $this->usuario_db_txt .'
Contraseña: ' . $this->pass_db_txt . '
Nombre BBDD: ' . $this->nombre_db_txt . '

Usuario FTP: '. $this->usuario_ftp_txt .'
Contraseña: ' . $this->pass_ftp_txt . '


'; //$hoy = date("d-m-Y H:i:s"); $html_resultado = '

BBDD
Usuario: '. $this->usuario_db_txt .'
Nombre Base de Datos: ' . $this->nombre_db_txt .'
Clave: ' . $this->pass_db_txt . '

FTP
Usuario: '. $this->usuario_ftp_txt .'
Clave: ' . $this->pass_ftp_txt . '


Nuevo dominio: '. $fields['domain'].'

'; $eldom = $fields['domain']; //Ahora en dirección ftp para el pdf ponemos el nombre del domino. $this->ip4_pdf = $eldom; echo '
'; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo '
'; echo '
'; } 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 "
"; print_r($global_config); print "
\n"; //print "
"; print_r($web_config); print "
\n"; 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); } } //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 "
"; print_r($subdom); print "
\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 "
"; print_r($coincidencias); print "
\n"; $this->subdominio = $coincidencias[1]; $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; //Control del usuario logeado y captura de sus variables de systema. 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"]["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 "
Seleccionado: "; print_r($fields['client_group_id']); print "
\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 "
Valores : "; print_r($this->cli_id); print "
\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 "
En crearSubDominio campo que se le pasa subdominio es: "; print_r($campoSubDominio); print "
\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 "
Error En crearSubDominio campo comprobacion dns_rr es: "; print_r($existeDominioParaSubDominio); print "
\n"; $this->onError(); return; } // print "
En crearSubDominio campo comprobacion dns_rr es: "; print_r($existeDominioParaSubDominio); print "
\n"; //print '
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);
		$this->ip4_ultima = $this->ip4_servidor_dns['ip_address'];
		//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 $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' => $this->ip4_ultima, //$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 ('
El client_id GLOBAL ' . $this->cli_id . "
"); // 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 . "
"); echo ('El groupid de la tabla sys_group ' . $res['groupid'] . " ");*/ //print "
"; print_r($paramSubDominios); print "
\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 '

Se ha dado de alta Web y Subdominio, '.$this->subdominio.', ¡Correctamente!


'; //$this->onShow(); } } function crearSitioWebSubdominio($remoto){ global $app, $conf; $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true); /* print "
DNS SERVER ";print_r($this->dns_serv);print "
\n"; print "
WEB SERVER ";print_r($this->web_serv);print "
\n"; print "
IP4 DNS ";print_r($this->ip4_servidor_dns);print "
\n"; print "
IP6 DNS ";print_r($this->ip6_servidor_dns);print "
\n"; print "
IP4 WEB ";print_r($this->ip4_servidor_web);print "
\n"; print "
IP6 WEB ";print_r($this->ip6_servidor_web);print "
\n"; print "
IP6 WEB LA OTRA ";print_r($this->ip6_ultima['ip_address']);print "
\n"; */ //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' => 'none', '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' => 'dynamic', 'pm_max_children' => 10, 'pm_start_servers' => 1, 'pm_min_spare_servers' => 1, 'pm_max_spare_servers' => 1, 'pm_process_idle_timeout' => 10, 'pm_max_requests' => 10, '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 "
 Parametros:"; print_r($paramsite); print "
\n"; /*print '
 cliente id ' . $fields['client_id'];
		print "
";print_r($fields);print "
\n" . $fields['client_id'];*/ //print '
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 "
WEB SERVER por defecto ";print_r($global_config_sitio);print "
\n"; //print "
DNS SERVER por defecto ";print_r($global_config_dns);print "
\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 "
tieneServidorIPs el cli_id "; print_r($this->cli_id . ' el servidor ' . $this->dns_serv); print "
\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 que hay en la configuración por defecto 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 que hay en la configuración por defecto 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 que hay en la configuración por defecto 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 que hay en la configuración por defecto if(!$this->ftp_serv){ $this->ftp_serv = $global_config_sitio['default_webserver'];//1; } } /*print "
DNS SERVER ";print_r($this->dns_serv);print "
\n"; print "
WEB SERVER ";print_r($this->web_serv);print "
\n"; print "
DB SERVER ";print_r($this->bbdd_serv);print "
\n"; print "
FTP SERVER ";print_r($this->ftp_serv);print "
\n";*/ //Captura de las ips del servidor dns de la variable global para ello. /* $global_dns_config = $app->getconf->get_server_config($this->dns_serv, 'server'); $this->ip4_servidor_dns = $global_dns_config['ip_address']; $this->ip6_servidor_dns = $global_dns_config['v6_prefix'];*/ //El cliente 1 es admin 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{ // $this->ip4_servidor_dns = $global_dns_config['ip_address']; //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"'); //echo(' la ip6 ' . $this->ip6_ultima); //si no tiene asignado le damos el de admin. /* if(!$this->ip4_servidor_dns){ // $this->ip4_servidor_dns = $global_dns_config['ip_address']; //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"'); }*/ } $this->ip6_ultima = $this->ip6_servidor_dns['ip_address']; } //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"'); }*/ } //Cargamos variable para el pdf $this->ip4_pdf = $this->ip4_servidor_web['ip_address']; 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"'); //echo(' (1) la ip4 bbdd ' . print_r($this->ip4_servidor_bbdd)); //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"'); //echo(' (2) la ip4 bbdd ' . print_r($this->ip4_servidor_bbdd)); /*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'"); //$dns_ip_servidor['ip_address'];//$la_ip4['ip_address']; /*print "
IP4 DNS ";print_r($this->ip4_servidor_dns);print "
\n"; print "
IP6 DNS ";print_r($this->ip6_servidor_dns);print "
\n"; print "
IP4 WEB ";print_r($this->ip4_servidor_web);print "
\n"; print "
IP6 WEB ";print_r($this->ip6_servidor_web);print "
\n"; print "
IP4 BBDD ";print_r($this->ip4_servidor_bbdd);print "
\n"; print "
IP6 BBDD ";print_r($this->ip6_servidor_bbdd);print "
\n"; echo('El cliente ' . $this->cli_id . '
');*/ if(!$this->ip4_servidor_dns['ip_address']){ //si no tiene servidor dns en la lista de ips se toma el servidor por defecto web y se usan sus ips $global_web_config = $app->getconf->get_server_config($this->web_serv, 'server'); $this->ip4_servidor_dns = $global_web_config; //$this->ip6_servidor_dns = $global_web_config; /*$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;*/ } //Si no tiene ip6 asignada tomamos la del servidor web if(!$this->ip6_servidor_dns['ip_address']){ $this->ip6_servidor_dns = $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"'); //si no tiene servidor dns en la lista de ips se toma el servidor por defecto web y se usan sus ips // $global_web_config = $app->getconf->get_server_config($this->web_serv, 'server'); //$this->ip4_servidor_dns = $global_web_config; // $this->ip6_servidor_dns = $global_web_config['v6_prefix']; // $this->ip6_ultima = $this->ip6_servidor_dns; //echo(' la ip6 ' . $this->ip6_servidor_dns); /* $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']){ //Si no hay ip4 en la lista de ips, tomamos esta de la configuración principal. $global_web_config = $app->getconf->get_server_config($this->web_serv, 'server'); $this->ip4_servidor_web = $global_web_config; //Cargamos variable para el pdf $this->ip4_pdf = $this->ip4_servidor_web['ip_address']; 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']){ $global_bbdd_config = $app->getconf->get_server_config($this->bbdd_serv, 'server'); $this->ip4_servidor_bbdd = $global_bbdd_config; //echo(' (3) la ip4 bbdd ' . print_r($this->ip4_servidor_bbdd)); //Como la ip4 para las bbdd es la ip4 para el sitio web, no es necesario esta comprobación /* 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 "
Servidor WEB ";print_r($servicio_web);print "
\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 "
Servidor DNS ";print_r($servicio_dns);print "
\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 "
Servidor FTP ";print_r($servicio_ftp);print "
\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 "
Servidor DB ";print_r($servicio_db);print "
\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; } 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 "
DNS SERVER ";print_r($this->dns_serv);print "
\n"; print "
WEB SERVER ";print_r($this->web_serv);print "
\n"; print "
IP4 DNS ";print_r($this->ip4_servidor_dns);print "
\n"; print "
IP6 DNS ";print_r($this->ip6_servidor_dns);print "
\n"; print "
IP4 WEB ";print_r($this->ip4_servidor_web);print "
\n"; print "
IP6 WEB ";print_r($this->ip6_servidor_web);print "
\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['ip_address']; //} //echo(' ips ' . $this->ip4_ultima . ' ip4dns ' . $this->ip4_servidor_dns); //if($this->dns_serv && $this->ip6_servidor_dns){ $this->ip6_ultima = $this->ip6_servidor_dns['ip_address']; //} //echo(' ip4 ' . $this->ip4_ultima['ip_address'] . ' ip6 ' . $this->ip6_ultima); //if($this->web_serv && $this->ip4_servidor_web){ //$this->ip4_ultima = $this->ip4_servidor_dns;//$this->ip4_servidor_web; //} //if($this->web_serv && $this->ip6_servidor_web){ //$this->ip6_ultima = $this->ip4_servidor_dns;//$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, $tpl_content); $tpl_content = str_replace('{IPV6}', $this->ip6_ultima, $tpl_content); $enable_dnssec = '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, "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->sys_usuario_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->sys_usuario_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' => 'n', 'ssi' => 'n', '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' => 'dynamic', 'pm_max_children' => 10, 'pm_start_servers' => 1, 'pm_min_spare_servers' => 1, 'pm_max_spare_servers' => 1, 'pm_process_idle_timeout' => 10, 'pm_max_requests' => 10, '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 "
"; print_r($paramsite); print "
\n"; /*print '
 cliente id ' . $fields['client_id'];
		print "
";print_r($fields);print "
\n";*/ //print "
Formulario ";print_r($formulario);print "
\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); 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; 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; } if($this->comprobarSubDominios($fields['domain'])){ $this->crearSubDominio($remote, $fields['domain']); if(!$this->subdom_error){ $this->crearSitioWebSubdominio($remote); $this->crearBaseDatosFtp($remote); } } else { if(!$this->dominio_error){ $this->crearDnsSitioWeb($remote); //Si todo va bien, el resultado de la web y dns echo '

Altas Web y DNS del dominio '.$fields['domain'].', ¡Creadas correctamente!


'; //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'); $this->crearBaseDatosFtp($remote); }else{ $this->onError(); return; } } } } 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); } //------------------------------------------------------------------------------------------------------------ //IMPORTANTE. FUNCIONES EXTRAIDAS Y MODIFICADAS DE ISPCONFIG PARA SOLUCIONAR EL PROBLEMA DE AUTOLOGEO A ADMIN. //------------------------------------------------------------------------------------------------------------ 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_usuario_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_usuario_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_usuario_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_usuario_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; } } //---------------------------------------------------------------------------------- //IMPORTANTE. ESTA FUNCION ES COMO LO HACE ISPCONFIG NO EXTRAIDA PERO SI MODIFICADA. //---------------------------------------------------------------------------------- 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 ''; ?>