ISPConfig module for simplify the creation of websites and DNS zones in a only step
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

1847 строки
75 KiB

  1. <?php
  2. /*
  3. PHP por David Ramos García, Open6Hosting <dramos@open6hosting.com>
  4. SQL y expresiones regulares por Pablo Sarria Pérez, Open6Hosting <pablo@sarriaperez.com>
  5. 2017, All rights reserved.
  6. */
  7. require_once '../../lib/config.inc.php';
  8. require_once '../../lib/app.inc.php';
  9. //INICIO---CLASE PARA LOS LIMITES--------------------------------------------------------------------------------------------
  10. require_once 'clases/limites.inc.php';
  11. //FIN------CLASE PARA LOS LIMITES--------------------------------------------------------------------------------------------
  12. //require 'pdf_o6h.php';
  13. //Variable para cargar los distintos formularios.
  14. $tform_def_file = "form/new_service_webdns.tform.php";
  15. //Check permissions for module
  16. $app->auth->check_module_permissions('webdns');
  17. //Loading classes a usar.
  18. $app->uses('tpl,tform,tform_actions,remoting,tools_sites,remoting_lib,remoting_dns');
  19. $app->load('tform_actions');
  20. class page_action extends tform_actions {
  21. public $estaLogeado;
  22. function onShowNew() {
  23. global $app;
  24. /*$sesion = $_SESSION;
  25. $sesionDe = $_SESSION['s']['user']['typ'];
  26. $grupo = $_SESSION["s"]["user"]["default_group"];
  27. print_r('La session de ' . $sesionDe);
  28. print(', su grupo es ' . $grupo);
  29. print_r($sesion);*/
  30. //------LIMITES--------------------------------------------------------------------------------------------------
  31. $this->estaLogeado = $_SESSION['s']['user']['typ'];
  32. // we will check only users, not admins
  33. if($this->estaLogeado == 'user') {
  34. $client_group_id = $_SESSION["s"]["user"]["default_group"];
  35. $limitado = new limites($client_group_id);
  36. $limitado->limitesLoad();
  37. }
  38. //------LIMITES--------------------------------------------------------------------------------------------------
  39. parent::onShowNew();
  40. }
  41. function onShowEnd() {
  42. global $app, $conf, $interfaceConf;
  43. $this->tratarVariablesPrefix();
  44. $app->uses('getconf,tools_sites');
  45. $global_config = $app->getconf->get_global_config('sites');
  46. $ftpuser_prefix = $app->tools_sites->replacePrefix($global_config['ftpuser_prefix'], $this->dataRecord);
  47. if ($this->dataRecord['username'] != ""){
  48. /* REMOVE the restriction */
  49. $app->tpl->setVar("username", $app->tools_sites->removePrefix($this->dataRecord['username'], $this->dataRecord['username_prefix'], $ftpuser_prefix));
  50. }
  51. if($this->dataRecord['username'] == "") {
  52. $app->tpl->setVar("username_prefix", $ftpuser_prefix);
  53. } else {
  54. $app->tpl->setVar("username_prefix", $app->tools_sites->getPrefix($this->dataRecord['username_prefix'], $ftpuser_prefix, $global_config['ftpuser_prefix']));
  55. }
  56. //Get the database user prefix
  57. $app->uses('getconf,tools_sites');
  58. $global_config = $app->getconf->get_global_config('sites');
  59. //* Client: If the logged in user is not admin and has no sub clients (no reseller)
  60. if ($_SESSION["s"]["user"]["typ"] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])) {
  61. // Get the limits of the client
  62. $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
  63. $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);
  64. //* Reseller: If the logged in user is not admin and has sub clients (reseller)
  65. }elseif ($_SESSION["s"]["user"]["typ"] != 'admin' && $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
  66. // Get the limits of the client
  67. $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
  68. $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);
  69. // Fill the client select field
  70. $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";
  71. $records = $app->db->queryAllRecords($sql, $client['client_id']);
  72. $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
  73. $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contact_name'].'</option>';
  74. //$tmp_data_record = $app->tform->getDataRecord($this->id);
  75. if(is_array($records)) {
  76. foreach( $records as $rec) {
  77. $selected = @(is_array($this->dataRecord) && ($rec["groupid"] == $this->dataRecord['client_group_id'] || $rec["groupid"] == $this->dataRecord['sys_groupid']))?'SELECTED':'';
  78. $client_select .= "<option value='$rec[groupid]' $selected>$rec[contactname]</option>\r\n";
  79. }
  80. }
  81. $app->tpl->setVar("client_group_id", $client_select);
  82. //* Es Admin
  83. } elseif($_SESSION["s"]["user"]["typ"] == 'admin') {
  84. // Fill the client select field
  85. $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";
  86. $clients = $app->db->queryAllRecords($sql);
  87. $client_select = "<option value='0'></option>";
  88. //$tmp_data_record = $app->tform->getDataRecord($this->id);
  89. if(is_array($clients)) {
  90. foreach( $clients as $client) {
  91. //$selected = @($client["groupid"] == $tmp_data_record["sys_groupid"])?'SELECTED':'';
  92. $selected = @(is_array($this->dataRecord) && ($client["groupid"] == $this->dataRecord['client_group_id'] || $client["groupid"] == $this->dataRecord['sys_groupid']))?'SELECTED':'';
  93. $client_select .= "<option value='$client[groupid]' $selected>$client[contactname]</option>\r\n";
  94. }
  95. }
  96. $app->tpl->setVar("client_group_id", $client_select);
  97. }
  98. if ($this->dataRecord['database_user'] != ""){
  99. /* REMOVE the restriction */
  100. $app->tpl->setVar("database_user", $app->tools_sites->removePrefix($this->dataRecord['database_user'], $this->dataRecord['database_user_prefix'], $dbuser_prefix));
  101. }
  102. if($this->dataRecord['database_user'] == "") {
  103. $app->tpl->setVar("database_user_prefix", $dbuser_prefix);
  104. } else {
  105. $app->tpl->setVar("database_user_prefix", $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']));
  106. $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']);
  107. $datos_prefix = $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']);
  108. $fields['database_user_prefix'] = $datos_prefix;
  109. }
  110. if ($this->dataRecord['username'] != ""){
  111. /* REMOVE the restriction */
  112. $app->tpl->setVar("username", $app->tools_sites->removePrefix($this->dataRecord['username'], $this->dataRecord['username_prefix'], $ftpuser_prefix));
  113. }
  114. if($this->dataRecord['username'] == "") {
  115. $app->tpl->setVar("username_prefix", $ftpuser_prefix);
  116. } else {
  117. $app->tpl->setVar("username_prefix", $app->tools_sites->getPrefix($this->dataRecord['username_prefix'], $ftpuser_prefix, $global_config['ftpuser_prefix']));
  118. }
  119. parent::onShowEnd();
  120. }
  121. public $valor_prefix;
  122. public $valor_prefix_ftp;
  123. function tratarVariablesPrefix() {
  124. global $app, $conf, $interfaceConf;
  125. //Get the database name and database user prefix
  126. $app->uses('getconf,tools_sites');
  127. $global_config = $app->getconf->get_global_config('sites');
  128. $dbuser_prefix = $app->tools_sites->replacePrefix($global_config['dbuser_prefix'], $this->dataRecord);
  129. $ftpuser_prefix = $app->tools_sites->replacePrefix($global_config['ftpuser_prefix'], $this->dataRecord);
  130. $this->dataRecord['username_prefix'] = $ftpuser_prefix;
  131. $this->dataRecord['database_user_prefix'] = $dbuser_prefix;
  132. $this->valor_prefix = $this->dataRecord['database_user_prefix'] = $dbuser_prefix;
  133. $this->valor_prefix_ftp = $this->dataRecord['username_prefix'] = $ftpuser_prefix;
  134. if(strlen($dbuser_prefix . $this->dataRecord['database_user']) > 16)
  135. $app->tform->errorMessage .= str_replace('{user}', htmlentities($dbuser_prefix . $this->dataRecord['database_user'], ENT_QUOTES, 'UTF-8'),
  136. $app->tform->wordbook["database_user_error_len"]).'<br />';
  137. //Check database user against blacklist
  138. $dbuser_blacklist = array($conf['db_user'], 'mysql', 'root');
  139. if(is_array($dbuser_blacklist) && in_array($dbuser_prefix . $this->dataRecord['database_user'], $dbuser_blacklist)) {
  140. $app->tform->errorMessage .= $app->lng('Database user not allowed.').'<br />';
  141. }
  142. /* restrict the names */
  143. /* crop user names if they are too long -> mysql: user: 16 chars / db: 64 chars */
  144. if ($app->tform->errorMessage == ''){
  145. $this->dataRecord['database_user'] = substr($dbuser_prefix . $this->dataRecord['database_user'], 0, 16);
  146. }
  147. $this->dataRecord['server_id'] = 0; // we need this on all servers
  148. if ($this->dataRecord['database_user'] != ""){
  149. /* REMOVE the restriction */
  150. $app->tpl->setVar("database_user", $app->tools_sites->removePrefix($this->dataRecord['database_user'], $this->dataRecord['database_user_prefix'], $dbuser_prefix));
  151. }
  152. if($this->dataRecord['database_user'] == "") {
  153. $app->tpl->setVar("database_user_prefix", $dbuser_prefix);
  154. } else {
  155. $app->tpl->setVar("database_user_prefix", $app->tools_sites->getPrefix($this->dataRecord['database_user_prefix'], $dbuser_prefix, $global_config['dbuser_prefix']));
  156. }
  157. //* Reseller: If the logged in user is not admin and has sub clients (is a reseller)
  158. if($_SESSION["s"]["user"]["typ"] != 'admin' && $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
  159. $this->valor_prefix = $dbuser_prefix;
  160. }
  161. }
  162. public $dominio;
  163. public $subdominio;
  164. public $es_subdominio = false;
  165. public $subdom_error = false;
  166. public $dominio_error = false;
  167. public $no_ip = false;
  168. //Campos para PDF
  169. public $usuario_db_txt;
  170. public $nombre_db_txt;
  171. public $pass_db_txt;
  172. public $usuario_ftp_txt;
  173. public $pass_ftp_txt;
  174. public $nombre_user_ftp;
  175. public $ip4_pdf;
  176. public $url_db;
  177. function generaNombreFTP(){
  178. $this->tratarVariablesPrefix();
  179. //Cadena de caractares para construir el nombre.
  180. $cadena = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
  181. //Obtengo la longitud de las cadenas
  182. $longitudCadena=strlen($cadena);
  183. //Variable para el nombre
  184. $nombre = "";
  185. //Longitud para el nombre
  186. $longitudNombre=8;
  187. //Creo el nombre
  188. for($i=1 ; $i<=$longitudNombre ; $i++){
  189. //Número aleatorio entre 0 y la longitud de la cadena de caracteres-1
  190. $pos=rand(0,$longitudCadena-1);
  191. //Formo la nombre en cada iteracción del bucle, añadiendo a la cadena $nombre
  192. //la letra correspondiente a la posición $pos en la cadena de caracteres definida.
  193. $nombre .= substr($cadena,$pos,1);
  194. }
  195. return $nombre;
  196. }
  197. function generaPass(){
  198. //Cadena de caractares para construir las password.
  199. $cadena = "abcdefghijklmnopqrstuvwxyz!@#_ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
  200. $cadSpeciales = "!@#_";
  201. //Obtengo la longitud de las cadenas
  202. $longitudCadena = strlen($cadena);
  203. $longSpeciales = strlen($cadSpeciales);
  204. //Variable para la password
  205. $pass = "";
  206. //Longitud para la password
  207. $longitudPass=13;
  208. //Creo la password
  209. for($i=1 ; $i<=$longitudPass ; $i++){
  210. //Número aleatorio entre 0 y la longitud de la cadena de caracteres-1
  211. $pos=rand(0,$longitudCadena-1);
  212. //Formo la password en cada iteracción del bucle, añadiendo a la cadena $pass
  213. //la letra correspondiente a la posición $pos en la cadena de caracteres definida.
  214. $pass .= substr($cadena,$pos,1);
  215. //Añado algún caracter especial en los últimos cuatro caracteres
  216. for($i2=13;$i2<=$i; $i2++){
  217. $poSpecial=rand(0,$longSpeciales-1);
  218. $pass .= substr($cadSpeciales, $poSpecial, 1);
  219. }
  220. }
  221. return $pass;
  222. }
  223. function generaNombreBD(){
  224. $this->tratarVariablesPrefix();
  225. //Cadena de caractares para construir las nombre.
  226. $cadena = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
  227. //$cadSpeciales = "!@#_";
  228. //Obtengo la longitud de las cadenas
  229. $longitudCadena=strlen($cadena);
  230. //$longSpeciales = strlen($cadSpeciales);
  231. //Variable para la nombre
  232. $nombre = "";
  233. //Longitud para la nombre
  234. $longitudNombre=8;
  235. //Creo el nombre
  236. for($i=1 ; $i<=$longitudNombre ; $i++){
  237. //Número aleatorio entre 0 y la longitud de la cadena de caracteres-1
  238. $pos=rand(0,$longitudCadena-1);
  239. //Formo la nombre en cada iteracción del bucle, añadiendo a la cadena $nombre
  240. //la letra correspondiente a la posición $pos en la cadena de caracteres definida.
  241. $nombre .= substr($cadena,$pos,1);
  242. }
  243. return $this->valor_prefix . $nombre;
  244. }
  245. /*function comprobarPass($claveGenerada){
  246. //compruebo que el tamaño del string sea válido.
  247. if (strlen($claveGenerada)<3 || strlen($claveGenerada)>20){
  248. echo $claveGenerada . " no es válida0<br>";
  249. return false;
  250. }
  251. //compruebo que los caracteres sean los permitidos
  252. $alphachars = "abcdefghijkmnopqrstuvwxyz";
  253. $upperchars = "ABCDEFGHJKLMNPQRSTUVWXYZ";
  254. $numchars = "23456789";
  255. $specialchars = "!@#_";
  256. //$permitidos = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
  257. if (ereg("^[a-zA-Z0-9\-_]{3,20}$", $claveGenerada)) {
  258. echo $claveGenerada . " es válido<br>";
  259. return true;
  260. } else {
  261. echo $claveGenerada . " NO válido<br>";
  262. return false;
  263. }
  264. echo $claveGenerada . " es válido<br>";
  265. return true;
  266. }*/
  267. function crearBaseDatosFtp($remoto){
  268. global $app, $conf;
  269. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  270. $app->uses('ini_parser,getconf');
  271. $server_config_array = $app->getconf->get_global_config();
  272. $generated_usernameBBDD = $this->generaNombreBD();
  273. $sitio_id = $app->db->queryOneRecord(
  274. 'SELECT domain_id, domain FROM web_domain WHERE domain = "'.$fields['domain'].'"');
  275. $clavePass = $this->generaPass();
  276. //añado database user con su prefix
  277. $db_user_params = array(
  278. 'server_id' => $this->bbdd_serv,
  279. 'sysgroup_id' => $this->cli_grupo_id, //$this->sys_grupo_id,
  280. 'sys_userid' => $this->sys_usuario_id,
  281. 'sys_perm_other' => '-',
  282. 'database_user' => $generated_usernameBBDD,
  283. 'database_user_prefix' => $this->valor_prefix,
  284. 'database_password' => $clavePass
  285. );
  286. $this->usuario_db_txt = $db_user_params['database_user'];
  287. $this->pass_db_txt = $db_user_params['database_password'];
  288. //print "<pre> USUARIO BBDD "; print_r($db_user_params); print "</pre>\n";
  289. //print "<br>". $this->cli_id;
  290. //print "<br>". $this->usuario_db_txt;
  291. //print "<br>". $this->pass_db_txt;
  292. //print "<pre>"; print_r($fields); print "</pre>\n";
  293. //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO
  294. //DE LO QUE SE QUIERE CREAR EN ESTE CASO BBDD. NO FUNCIONA SE LANZA EL AFTER INSERT EN NUESTRA FUNCION.
  295. $tform_def_file = "../sites/form/database_user.tform.php";
  296. $app->tform->loadFormDef($tform_def_file);
  297. $db_user_id = $remoto->insert_query('../sites/form/database_user.tform.php',
  298. $this->cli_id, $db_user_params, 'sites:web_database_user:on_after_insert');
  299. $remoto->sites_database_user_after_add($this->cli_grupo_id, $db_user_params);
  300. // add database
  301. $paramsBD = array(
  302. 'server_id' => $this->bbdd_serv, //$camDnsRR['server_id'],
  303. 'sysgroup_id' => $this->cli_grupo_id, //$this->sys_grupo_id,
  304. 'parent_domain_id' => $sitio_id['domain_id'],
  305. 'type' => 'mysql',
  306. 'database_quota' => '-1',
  307. 'database_name' => $generated_usernameBBDD,
  308. 'database_name_prefix' => $this->valor_prefix,
  309. 'database_user_id' => $db_user_id,
  310. 'database_charset' => 'utf8',
  311. 'remote_access' => 'n',
  312. 'remote_ips' => '-1',
  313. 'active' => 'y'
  314. );
  315. $this->nombre_db_txt = $paramsBD['database_name'];
  316. $db_id = $remoto->sites_database_add($this->cli_id, /*$this->cli_grupo_id,*/ $paramsBD);
  317. $this->urlBBDD($db_id, $this->bbdd_serv);
  318. //echo('Id de la BBDD ' . $db_id);
  319. // get site data para usarlo en la creación de la cuenta ftp, otra forma de cargar una tupla dandole un id
  320. //$app->uses('remoting_lib');
  321. //$app->remoting_lib->loadFormDef('../sites/form/web_vhost_domain.tform.php');
  322. //IMPORTANTE. AL NO PODER USAR LA FUNCION getDataRecord YA QUE NOS HACE ADMIN.
  323. //TENGO QUE LANZAR LA FUNCION sites_ftp_user_after_insert PARA SOLUCIONAR ESTE PROBLEMA Y NO getDataRecord().
  324. //$site_data = $app->remoting_lib->getDataRecord($sitio_id);
  325. //$site_data = $remoto->getDataRecordWebDNS($sitio_id);
  326. $this->nombre_user_ftp = $this->generaNombreFTP();
  327. // add ftp user
  328. $ftp_params = array(
  329. 'server_id' => $this->web_serv, //$camDnsRR['server_id'],
  330. 'parent_domain_id' => $sitio_id['domain_id'],
  331. 'username' => $this->valor_prefix_ftp . $this->nombre_user_ftp,
  332. 'username_prefix' => $this->valor_prefix_ftp,
  333. 'password' => $clavePass,
  334. 'quota_size' => '-1',
  335. 'dir' => $site_data['0']['document_root'],
  336. 'uid' => $site_data['0']['system_user'],
  337. 'gid' => $site_data['0']['system_group'],
  338. 'sys_groupid' => $site_data['0']['sys_groupid'],
  339. 'quota_files' => '-1',
  340. 'ul_ratio' => '-1',
  341. 'dl_ratio' => '-1',
  342. 'ul_bandwidth' => '-1',
  343. 'dl_bandwidth' => '-1',
  344. 'active' => 'y',
  345. );
  346. $this->usuario_ftp_txt = $ftp_params['username'];
  347. $this->pass_ftp_txt = $ftp_params['password'];
  348. //print "<pre> FTP "; print_r($ftp_params); print "</pre>\n";
  349. //print "<pre>"; print_r($site_data); print "</pre>\n";
  350. //echo('El grupo del usuario es ' . $this->cli_grupo_id);
  351. $tform_def_file = "../sites/form/ftp_user.tform.php";
  352. $app->tform->loadFormDef($tform_def_file);
  353. $remoto->insert_query('../sites/form/ftp_user.tform.php', $this->cli_id,/*$fields['client_group_id'],*/ $ftp_params);
  354. $app->uses('sites_ftp_user_plugin');
  355. global $app;
  356. //Register for the events. NO FUNCIONA.
  357. $app->plugin->registerEvent('sites:ftp_user:on_after_insert');
  358. //LO LANZAMOS DE NUESTRA FUNCION EXTRAIDA Y MODIFICADA DEL PLUGING QUE SE TENDRÍA QUE EJECUTAR PERO NO LO HACE.WHY?
  359. $remoto->sites_ftp_user_after_insert();
  360. echo '<br><div class="alert alert-success"><br>
  361. Altas de BBDD y FTP, ¡Correctas!<br><br>
  362. Usuario BBDD: <b>'. $this->usuario_db_txt .'</b><br>Contraseña: <b>' . $this->pass_db_txt . '
  363. </b><br>Nombre BBDD: <b>' . $this->nombre_db_txt . '</b><br>
  364. <br>Usuario FTP: <b>'. $this->usuario_ftp_txt .'</b><br>Contraseña: <b>' . $this->pass_ftp_txt . '</b><br><br>
  365. </div></br>';
  366. //$hoy = date("d-m-Y H:i:s");
  367. $html_resultado = '<br><br><b>BBDD</b><br>
  368. Usuario: <b>'. $this->usuario_db_txt .'</b><br>
  369. Nombre Base de Datos: <b>' . $this->nombre_db_txt .'</b><br>
  370. Clave: <b>' . $this->pass_db_txt . '</b><br><br>
  371. <b>FTP</b><br>
  372. Usuario: <b>'. $this->usuario_ftp_txt .'</b><br>
  373. Clave: <b>' . $this->pass_ftp_txt . '</b><br><br>
  374. <b> </b><br>Nuevo dominio: <b>'. $fields['domain'].'</b><br><br>';
  375. $eldom = $fields['domain'];
  376. echo '<form method="post" id="formulario" action="webdns/pdf_o6h.php" target="_blank">';
  377. echo '<input id="pdf_power" name="pdf_power" type="hidden" value="'.$html_resultado.'">';
  378. echo '<input id="nombre_bd" name="nombre_bd" type="hidden" value="'.$this->nombre_db_txt.'">';
  379. echo '<input id="usuario_bd" name="usuario_bd" type="hidden" value="'.$this->usuario_db_txt.'">';
  380. echo '<input id="pass_bd" name="pass_bd" type="hidden" value="'.$this->pass_db_txt.'">';
  381. echo '<input id="usuario_ftp" name="usuario_ftp" type="hidden" value="'.$this->usuario_ftp_txt.'">';
  382. echo '<input id="pass_ftp" name="pass_ftp" type="hidden" value="'.$this->pass_ftp_txt.'">';
  383. echo '<input id="ip4" name="ip4" type="hidden" value="'.$this->ip4_pdf.'">';
  384. echo '<input id="url_db" name="url_db" type="hidden" value="'.$this->url_db.'">';
  385. echo '<input id="dominio_nuevo" name="dominio_nuevo" type="hidden" value="'.$eldom.'">';
  386. echo '<input type="submit" class="btn btn-default formbutton-success" value="Descargar PDF">';
  387. echo '</form>';
  388. echo '<div id="resp"></div>';
  389. }
  390. function urlBBDD($idBBDD, $servidor_id){
  391. global $app, $conf;
  392. $dbData = $app->db->queryOneRecord(
  393. "SELECT server_id, database_name FROM web_database WHERE database_id = ?", $idBBDD);
  394. $serverData = $app->db->queryOneRecord(
  395. "SELECT server_name FROM server WHERE server_id = ?", $servidor_id);
  396. $app->uses('getconf');
  397. $global_config = $app->getconf->get_global_config('sites');
  398. $web_config = $app->getconf->get_server_config($servidor_id, 'web');
  399. //print "<pre>"; print_r($global_config); print "</pre>\n";
  400. //print "<pre>"; print_r($web_config); print "</pre>\n";
  401. if($global_config['phpmyadmin_url'] != '') {
  402. $phpmyadmin_url = $global_config['phpmyadmin_url'];
  403. $phpmyadmin_url = str_replace(array('[SERVERNAME]', '[DATABASENAME]'), array($serverData['server_name'], $dbData['database_name']), $phpmyadmin_url);
  404. //header('Location: '.$phpmyadmin_url);
  405. $this->url_db = $phpmyadmin_url;
  406. //print('la url ' . $phpmyadmin_url);
  407. }
  408. }
  409. //Expresiones regulares para comprobar si es subdominio
  410. function comprobarSubDominios($subdom) {
  411. global $app, $conf;
  412. $patronSubDominos = "/(.*?)\.(.*)$/";
  413. $patronWWW = "/^w{3}/";
  414. //Se comprueba que no tenga 3 w "www" al principio del nombre del dominio o subdomino
  415. $encontradoWWW = preg_match($patronWWW, $subdom, $coincidencias);
  416. if($encontradoWWW){
  417. $app->tform->errorMessage = $app->tform->wordbook['error_dominio_www'];
  418. return;
  419. }
  420. //print "<pre>"; print_r($subdom); print "</pre>\n";
  421. //Si el dominio tiene mas de dos puntos, es incorrecto
  422. if(substr_count($subdom,".") > 2) {
  423. $this->es_subdominio = false;
  424. $this->dominio_error = true;
  425. $app->tform->errorMessage = $app->tform->wordbook['error_dominio_mas_puntos'];
  426. //return;
  427. }else if(substr_count($subdom,".") == 2){
  428. $this->encontrado = preg_match($patronSubDominos, $subdom, $coincidencias);
  429. //print "<pre>"; print_r($coincidencias); print "</pre>\n";
  430. $this->subdominio = $coincidencias[1];
  431. $this->dominio = $coincidencias[2];
  432. $this->es_subdominio = true;
  433. }
  434. return $this->es_subdominio;
  435. }
  436. public $cli_id;
  437. public $cli_grupo_id;
  438. public $sys_usuario_id;
  439. public $sys_grupo_id;
  440. //Control del usuario logeado y captura de sus variables de systema.
  441. function controlUserGrupoId(){
  442. global $app, $conf;
  443. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  444. //* Client: If the logged in user is not admin and has no sub clients (no reseller)
  445. if($_SESSION["s"]["user"]["typ"] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])) {
  446. $this->cli_id = $_SESSION["s"]["user"]["client_id"];
  447. $this->cli_grupo_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
  448. $this->sys_usuario_id = $_SESSION["s"]["user"]["sys_userid"];
  449. $this->sys_grupo_id = $_SESSION["s"]["user"]["sys_groupid"];
  450. //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);
  451. } else {
  452. //Captura de los distintos ids del cliente y usuario de sistema.
  453. //combinando un query a las dos tablas sys_group y sys_user que comparten el client_id.
  454. //print "<pre>Seleccionado: "; print_r($fields['client_group_id']); print "</pre>\n";
  455. if($fields['client_group_id']==0) {
  456. //En la tabla sys_user el client_id 0 es admin. En sys_group este valor es 0
  457. $this->cli_id = 0;
  458. $this->cli_grupo_id = 1;
  459. $this->sys_usuario_id = 1;//$this->cli_id;
  460. $this->sys_grupo_id = 0; //$this->cli_grupo_id;//0
  461. //echo('Quien es ' . $_SESSION["s"]["user"]["typ"]);
  462. }else{
  463. //echo('Quien es else ' . $_SESSION["s"]["user"]["typ"]);
  464. $client = $app->db->queryOneRecord(
  465. 'SELECT sys_user.userid, sys_user.sys_userid, sys_user.sys_groupid, sys_user.default_group, sys_user.client_id
  466. FROM sys_group, sys_user
  467. WHERE sys_group.client_id = sys_user.client_id and sys_group.groupid = ?', $fields['client_group_id']);
  468. $this->cli_id = $client['client_id'];
  469. $this->cli_grupo_id = $client['default_group'];
  470. $this->sys_usuario_id = $client['userid'];//$client['sys_userid'];
  471. $this->sys_grupo_id = $this->cli_grupo_id;//$client['sys_groupid'];
  472. //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);
  473. }
  474. }
  475. //print "<pre>Valores : "; print_r($this->cli_id); print "</pre>\n";
  476. //print " cli_id " . $this->cli_id . ' cli_grupo ' . $this->cli_grupo_id . ' sys_usuario ' . $this->sys_usuario_id . ' sys grupo ' . $this->sys_grupo_id;
  477. }
  478. //Crear subdominio
  479. function crearSubDominio($remoto, $campoSubDominio){
  480. global $app, $conf;
  481. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  482. //COMO LE PASO EL DOMINIO CORRECTO NO ES NECESARIO PONER EL % EN LA SQL AÑADO EL PUNTO.
  483. //EL PROBLEMA ES QUE CON UN DOMINIO .COM TOMA POR VALIDO UN .CO POR EL %
  484. //NO --> ('SELECT server_id, name FROM dns_rr WHERE name LIKE "'.$this->dominio.'%"');
  485. $existeDominioParaSubDominio = $app->db->queryOneRecord(
  486. 'SELECT server_id, name FROM dns_rr WHERE name LIKE "'.$this->dominio.'."');
  487. // print "<pre>En crearSubDominio campo que se le pasa subdominio es: "; print_r($campoSubDominio); print "</pre>\n";
  488. //Compruebo que el subdominio no existe consultando la tabla web_domain.
  489. $existeSubDominioWeb = $app->db->queryOneRecord(
  490. 'SELECT domain_id, domain FROM web_domain
  491. WHERE domain = "'.$campoSubDominio.'"');
  492. //Compruebo que el subdominio no existe consultando la tabla dns_rr
  493. $existeSubDominioTipoA = $app->db->queryOneRecord(
  494. 'SELECT name, type FROM dns_rr
  495. WHERE name = "'.$campoSubDominio.'" AND type = "A"');
  496. if(!$existeDominioParaSubDominio['name']){
  497. $this->subdom_error = true;
  498. $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
  499. // print "<pre>Error En crearSubDominio campo comprobacion dns_rr es: "; print_r($existeDominioParaSubDominio); print "</pre>\n";
  500. $this->onError();
  501. return;
  502. }
  503. // print "<pre>En crearSubDominio campo comprobacion dns_rr es: "; print_r($existeDominioParaSubDominio); print "</pre>\n";
  504. //print '<pre>El Sub existe '. $existeSubDominio['domain'];
  505. if($existeSubDominioWeb['domain']){
  506. $this->subdom_error = true;
  507. $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
  508. $this->onError();
  509. return $this->subdom_error;
  510. }
  511. if($existeSubDominioTipoA['name']){
  512. $this->subdom_error = true;
  513. $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
  514. $this->onError();
  515. return $this->subdom_error;
  516. }
  517. //$camDominio = $app->db->queryOneRecord('SELECT domain_id, domain FROM domain WHERE domain = "'.$this->dominio.'"');
  518. $camDominio = $app->db->queryOneRecord('SELECT origin FROM dns_soa WHERE origin LIKE "'.$this->dominio.'."');
  519. //$camDominio = $app->db->queryOneRecord('SELECT origin FROM dns_soa WHERE origin LIKE "'.$campoSubDominio.'%"');
  520. $camDnsRR = $app->db->queryOneRecord('SELECT server_id, zone FROM dns_rr WHERE name LIKE "'.$this->dominio.'."');
  521. //Para los registros tipo A la ip tiene que ser tipo IPv4
  522. $camServIP = $app->db->queryOneRecord(
  523. "SELECT ip_address FROM server_ip
  524. WHERE server_id = ".$camDnsRR['server_id']." AND ip_type='IPv4'");
  525. //print_r($camDominio);
  526. //print_r($camDnsRR);
  527. //Si el dominio NO existe mostramos mensaje de error y salimos de la ejecución
  528. if(!$camDominio['origin']){
  529. $this->subdom_error = true;
  530. $app->tform->errorMessage = $app->tform->wordbook['error_no_existe_dominio_padre'];
  531. $this->onError();
  532. return $this->subdom_error;
  533. } else {
  534. //Parametros para la creación de subdominios
  535. $paramSubDominios = array(
  536. 'server_id' => $camDnsRR['server_id'],
  537. 'zone' => $camDnsRR['zone'],
  538. 'name' => $this->subdominio,
  539. 'type' => 'a',
  540. 'data' => $camServIP['ip_address'],
  541. //'aux' => '0',
  542. 'ttl' => '3600',
  543. 'active' => 'y',
  544. //comento el campo stamp, ya que introducia solo ceros en la bbdd
  545. //'stamp' => time(),
  546. 'serial' => '1',
  547. );
  548. //echo ('<br>El client_id GLOBAL ' . $this->cli_id . " <br>");
  549. // client group id
  550. /*$res = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($fields['client_group_id']));
  551. $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);//$res['groupid'];
  552. echo ('El client group id seleccion ' . $client_group_id . " <br>");
  553. echo ('El groupid de la tabla sys_group ' . $res['groupid'] . " ");*/
  554. //print "<pre>"; print_r($paramSubDominios); print "</pre>\n";
  555. //Inserto en bbdd usando la clase remoto que se la he pasado en parámetros de la función
  556. //$resultado = $remoto->insert_query('../dns/form/dns_a.tform.php', $fields['client_id'], $paramSubDominios);
  557. $resultado = $remoto->insert_query('form/dns_a_webdns.tform.php', $this->cli_id, /*$fields['client_group_id'],*/ $paramSubDominios);
  558. $remoto->dns_registro_tipo_a_after_insert($this->cli_grupo_id);
  559. echo '<br><div class="alert alert-success"><br>
  560. Se ha dado de alta Web y Subdominio, <b>'.$this->subdominio.'</b>, ¡Correctamente!
  561. <br><br></div></br>';
  562. //$this->onShow();
  563. }
  564. }
  565. function crearSitioWebSubdominio($remoto){
  566. global $app, $conf;
  567. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  568. /* print "<pre>DNS SERVER ";print_r($this->dns_serv);print "</pre>\n";
  569. print "<pre>WEB SERVER ";print_r($this->web_serv);print "</pre>\n";
  570. print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
  571. print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
  572. print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
  573. print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";
  574. print "<pre>IP6 WEB LA OTRA ";print_r($this->ip6_ultima['ip_address']);print "</pre>\n";
  575. */
  576. //add site
  577. $paramsite = array(
  578. //"sys_userid" => $this->sys_usuario_id,
  579. //"sys_groupid" => $this->cli_grupo_id,
  580. 'type' => 'vhost',
  581. 'domain' => $fields['domain'], //$this->subdominio,
  582. 'server_id' => $this->web_serv, //$server_id,
  583. 'ip_address' => '*',
  584. 'ipv6_address' =>$this->ip6_servidor_web['ip_address'],
  585. 'traffic_quota' => '-1',
  586. 'hd_quota' => '0',
  587. 'cgi' => 'y',
  588. 'ssi' => 'y',
  589. 'suexec' => 'y',
  590. 'ruby' => 'n',
  591. 'python' => 'n',
  592. 'perl' => 'n',
  593. 'errordocs' => '1',
  594. 'subdomain' => '',
  595. 'php' => 'php-fpm',
  596. 'fastcgi_php_version' => '',
  597. 'seo_redirect' => '',
  598. 'rewrite_to_https' => 'n',
  599. 'allow_override' => 'All',
  600. 'http_port' => 80,
  601. 'https_port' => 443,
  602. 'apache_directives' => '',
  603. 'nginx_directives' => '',
  604. 'php_fpm_use_socket' => 'y',
  605. 'pm' => 'ondemand',
  606. 'pm_max_children' => 10,
  607. 'pm_start_servers' => 1,
  608. 'pm_min_spare_servers' => 1,
  609. 'pm_max_spare_servers' => 5,
  610. 'pm_process_idle_timeout' => 10,
  611. 'pm_max_requests' => 0,
  612. 'custom_php_ini' => '',
  613. 'active' => 'y',
  614. 'document_root' => '-',
  615. 'system_user' => '-',
  616. 'system_group' => '-',
  617. 'log_retention' => 30,
  618. 'client_group_id' => $this->cli_grupo_id, //$client_group_id,
  619. );
  620. //print "<pre> Parametros:"; print_r($paramsite); print "</pre>\n";
  621. /*print '<pre> cliente id ' . $fields['client_id'];
  622. print "<pre>";print_r($fields);print "</pre>\n" . $fields['client_id'];*/
  623. //print '<pre>DNS IPV6 ' . $dns_ip_servidor_ipv6['ip_address'];
  624. //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO
  625. //DE LO QUE SE QUIERE CREAR EN ESTE CASO SITIO WEB
  626. $tform_def_file = "../sites/form/web_vhost_domain.tform.php";
  627. $app->tform->loadFormDef($tform_def_file);
  628. //El último parámetro es para lanzar un evento que llama a la función on_after_insert que prepara
  629. //los campos document_root, system_user y system_group
  630. //$site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php', $fields['client_group_id'], $paramsite, 'sites:web_vhost_domain:on_after_insert');
  631. $site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php',
  632. $this->cli_id, /*$cliente_id_seleccionado,*/
  633. $paramsite, 'sites:web_vhost_domain:on_after_insert');
  634. //IMPORTANTE. HAY QUE CARGAR EL FORMULARIO DE WEBDNS PARA QUE ENCUENTRE EL TAB.
  635. $tform_def_file = "form/new_service_webdns.tform.php";
  636. $app->tform->loadFormDef($tform_def_file);
  637. }
  638. public $ip4_servidor_dns;
  639. public $ip6_servidor_dns;
  640. public $ip4_servidor_web;
  641. public $ip6_servidor_web;
  642. public $ip4_servidor_bbdd;
  643. public $ip6_servidor_bbdd;
  644. public $ip4_servidor_ftp;
  645. public $ip6_servidor_ftp;
  646. public $dns_serv;
  647. public $web_serv;
  648. public $bbdd_serv;
  649. public $ftp_serv;
  650. function tieneServidorIPs(){
  651. global $app, $conf;
  652. $this->controlUserGrupoId();
  653. $app->uses('getconf');
  654. $global_config_sitio = $app->getconf->get_global_config('sites');
  655. $global_config_dns = $app->getconf->get_global_config('dns');
  656. if(!$global_config_dns['default_dnsserver']) {
  657. $app->tform->errorMessage = $app->tform->wordbook['error_no_servidor_default']. 'DNS.';
  658. $this->onError();
  659. return true;
  660. } else if(!$global_config_sitio['default_webserver']) {
  661. $app->tform->errorMessage = $app->tform->wordbook['error_no_servidor_default']. 'WEB.';
  662. $this->onError();
  663. return true;
  664. } else if(!$global_config_sitio['default_dbserver']) {
  665. $app->tform->errorMessage = $app->tform->wordbook['error_no_servidor_default']. 'DB.';
  666. $this->onError();
  667. return true;
  668. }
  669. //print "<pre>WEB SERVER por defecto ";print_r($global_config_sitio);print "</pre>\n";
  670. //print "<pre>DNS SERVER por defecto ";print_r($global_config_dns);print "</pre>\n";
  671. //El cliente 1 es admin.
  672. //Recupero los servidores asignados por defecto y se los asigno a admin o al usuario
  673. //que no tenga asignado ninguno.
  674. if($this->cli_id == 0) {
  675. $this->dns_serv = $global_config_dns['default_dnsserver'];//1;
  676. $this->web_serv = $global_config_sitio['default_webserver'];//1;
  677. $this->bbdd_serv = $global_config_sitio['default_dbserver'];//1;
  678. $this->ftp_serv = $global_config_sitio['default_webserver'];//1;
  679. //print "<pre>tieneServidorIPs el cli_id "; print_r($this->cli_id . ' el servidor ' . $this->dns_serv); print "</pre>\n";
  680. }else{
  681. $servidores = $app->db->queryOneRecord(
  682. "SELECT client_id, dns_servers, web_servers, db_servers FROM client
  683. WHERE client_id = ". $this->cli_id);
  684. $this->dns_serv = $servidores['dns_servers'];
  685. $this->web_serv = $servidores['web_servers'];
  686. $this->bbdd_serv = $servidores['db_servers'];
  687. //para el ftp el servidor es el mismo que para el sitio web.
  688. $this->ftp_serv = $servidores['web_servers'];
  689. //Si el cliente no tiene asignado un servidor se añade por defecto al que hay en la configuración por defecto
  690. if(!$this->dns_serv){
  691. $this->dns_serv = $global_config_dns['default_dnsserver'];//1;
  692. }
  693. //Si el cliente no tiene asignado un servidor se añade por defecto al que hay en la configuración por defecto
  694. if(!$this->web_serv){
  695. $this->web_serv = $global_config_sitio['default_webserver'];//1;
  696. }
  697. //Si el cliente no tiene asignado un servidor se añade por defecto al que hay en la configuración por defecto
  698. if(!$this->bbdd_serv){
  699. $this->bbdd_serv = $global_config_sitio['default_dbserver'];//1;
  700. }
  701. //Si el cliente no tiene asignado un servidor se añade por defecto al que hay en la configuración por defecto
  702. if(!$this->ftp_serv){
  703. $this->ftp_serv = $global_config_sitio['default_webserver'];//1;
  704. }
  705. }
  706. /*print "<pre>DNS SERVER ";print_r($this->dns_serv);print "</pre>\n";
  707. print "<pre>WEB SERVER ";print_r($this->web_serv);print "</pre>\n";
  708. print "<pre>DB SERVER ";print_r($this->bbdd_serv);print "</pre>\n";
  709. print "<pre>FTP SERVER ";print_r($this->ftp_serv);print "</pre>\n";*/
  710. //Captura de las ips del servidor dns de la variable global para ello.
  711. $global_dns_config = $app->getconf->get_server_config($this->dns_serv, 'server');
  712. //El cliente 1 es admin
  713. // if($this->cli_id == 0){
  714. $this->ip4_servidor_dns = $global_dns_config['ip_address'];
  715. $this->ip6_servidor_dns = $global_dns_config['v6_prefix'];
  716. //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
  717. //Alguno de los dos tiene que existir por configuración de ispconfig.
  718. /*$this->ip4_servidor_dns = $app->db->queryOneRecord(
  719. 'SELECT ip_type, ip_address FROM server_ip
  720. WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');*/
  721. /* $this->ip6_servidor_dns = $app->db->queryOneRecord(
  722. 'SELECT ip_type, ip_address FROM server_ip
  723. WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
  724. */
  725. /*if(!$this->ip4_servidor_dns){
  726. $this->ip4_servidor_dns = $app->db->queryOneRecord(
  727. 'SELECT ip_type, ip_address FROM server_ip
  728. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  729. }*/
  730. /* if(!$this->ip6_servidor_dns){
  731. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  732. 'SELECT ip_type, ip_address FROM server_ip
  733. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
  734. }
  735. }else{
  736. $this->ip4_servidor_dns = $global_dns_config['ip_address'];
  737. //Comprobamos si el cliente tiene servidor asignado, si no lo tiene asignamos el que admin a seleccionado
  738. //para este servidor.
  739. /*$this->ip4_servidor_dns = $app->db->queryOneRecord(
  740. 'SELECT ip_type, ip_address
  741. FROM server_ip
  742. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  743. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  744. 'SELECT ip_type, ip_address
  745. FROM server_ip
  746. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->dns_serv.'"AND ip_type="IPv6"');
  747. //si no tiene asignado le damos el de admin.
  748. if(!$this->ip4_servidor_dns){
  749. $this->ip4_servidor_dns = $global_dns_config['ip_address'];
  750. //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
  751. //Tomamos las de admin.
  752. //Alguno de los dos tiene que existir por configuración de ispconfig.
  753. /*$this->ip4_servidor_dns = $app->db->queryOneRecord(
  754. 'SELECT ip_type, ip_address FROM server_ip
  755. WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  756. if(!$this->ip4_servidor_dns){
  757. $this->ip4_servidor_dns = $app->db->queryOneRecord(
  758. 'SELECT ip_type, ip_address FROM server_ip
  759. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  760. }*/
  761. //}
  762. /* if(!$this->ip6_servidor_dns){
  763. //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
  764. //Tomamos las de admin.
  765. //Alguno de los dos tiene que existir por configuración de ispconfig.
  766. //$this->ip4_servidor_dns = $app->db->queryOneRecord('SELECT ip_type, ip_address FROM server_ip WHERE client_id = "0" AND ip_type="IPv4"');
  767. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  768. 'SELECT ip_type, ip_address FROM server_ip
  769. WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
  770. if(!$this->ip6_servidor_dns){
  771. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  772. 'SELECT ip_type, ip_address FROM server_ip
  773. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
  774. }
  775. }
  776. }*/
  777. //Captura de las ips del servidor web
  778. if($this->cli_id == 0){
  779. //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
  780. //Alguno de los dos tiene que existir por configuración de ispconfig.
  781. $this->ip4_servidor_web = $app->db->queryOneRecord(
  782. 'SELECT ip_type, ip_address FROM server_ip
  783. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  784. $this->ip6_servidor_web = $app->db->queryOneRecord(
  785. 'SELECT ip_type, ip_address FROM server_ip
  786. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  787. /*if(!$this->ip4_servidor_web){
  788. $this->ip4_servidor_web = $app->db->queryOneRecord(
  789. 'SELECT ip_type, ip_address FROM server_ip
  790. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  791. }
  792. if(!$this->ip6_servidor_web){
  793. $this->ip6_servidor_web = $app->db->queryOneRecord(
  794. 'SELECT ip_type, ip_address FROM server_ip
  795. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  796. }*/
  797. }else{//Comprobamos si el cliente tiene servidor asignado
  798. $this->ip4_servidor_web = $app->db->queryOneRecord(
  799. 'SELECT ip_type, ip_address
  800. FROM server_ip
  801. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  802. $this->ip6_servidor_web = $app->db->queryOneRecord(
  803. 'SELECT ip_type, ip_address
  804. FROM server_ip
  805. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->web_serv.'"AND ip_type="IPv6"');
  806. //si no tiene asignado le damos el de admin.
  807. if(!$this->ip4_servidor_web){
  808. $this->ip4_servidor_web = $app->db->queryOneRecord(
  809. 'SELECT ip_type, ip_address FROM server_ip
  810. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  811. /*if(!$this->ip4_servidor_web){
  812. $this->ip4_servidor_web = $app->db->queryOneRecord(
  813. 'SELECT ip_type, ip_address FROM server_ip
  814. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  815. }*/
  816. }
  817. if(!$this->ip6_servidor_web){
  818. $this->ip6_servidor_web = $app->db->queryOneRecord(
  819. 'SELECT ip_type, ip_address FROM server_ip
  820. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  821. /*if(!$this->ip6_servidor_web){
  822. $this->ip6_servidor_web = $app->db->queryOneRecord(
  823. 'SELECT ip_type, ip_address FROM server_ip
  824. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  825. }*/
  826. }
  827. }
  828. //Captura de las ips del servidor bbdd
  829. if($this->cli_id == 0){
  830. //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
  831. //Alguno de los dos tiene que existir por configuración de ispconfig.
  832. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  833. 'SELECT ip_type, ip_address FROM server_ip
  834. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  835. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  836. 'SELECT ip_type, ip_address FROM server_ip
  837. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  838. /*if(!$this->ip4_servidor_bbdd){
  839. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  840. 'SELECT ip_type, ip_address FROM server_ip
  841. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  842. }
  843. if(!$this->ip6_servidor_bbdd){
  844. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  845. 'SELECT ip_type, ip_address FROM server_ip
  846. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  847. }*/
  848. }else{//Comprobamos si el cliente tiene servidor asignado
  849. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  850. 'SELECT ip_type, ip_address
  851. FROM server_ip
  852. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  853. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  854. 'SELECT ip_type, ip_address
  855. FROM server_ip
  856. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->bbdd_serv.'"AND ip_type="IPv6"');
  857. //si no tiene asignado le damos el de admin.
  858. if(!$this->ip4_servidor_bbdd){
  859. //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
  860. //Tomamos las de admin.
  861. //Alguno de los dos tiene que existir por configuración de ispconfig.
  862. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  863. 'SELECT ip_type, ip_address FROM server_ip
  864. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  865. /*if(!$this->ip4_servidor_bbdd){
  866. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  867. 'SELECT ip_type, ip_address FROM server_ip
  868. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  869. }*/
  870. }
  871. if(!$this->ip6_servidor_bbdd){
  872. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  873. 'SELECT ip_type, ip_address FROM server_ip
  874. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  875. /*if(!$this->ip6_servidor_bbdd){
  876. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  877. 'SELECT ip_type, ip_address FROM server_ip
  878. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  879. }*/
  880. }
  881. }
  882. //para el servidor ftp no se hacen comprobaciones
  883. //ya que las ips son las mismas que para el servidor web.
  884. //$la_ip4 = $app->db->queryOneRecord("SELECT ip_type, ip_address FROM server_ip WHERE ip_type='IPv4'");
  885. $this->ip4_pdf = $this->ip4_servidor_web['ip_address'];//$dns_ip_servidor['ip_address'];//$la_ip4['ip_address'];
  886. /*print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
  887. print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
  888. print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
  889. print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";
  890. print "<pre>IP4 BBDD ";print_r($this->ip4_servidor_bbdd);print "</pre>\n";
  891. print "<pre>IP6 BBDD ";print_r($this->ip6_servidor_bbdd);print "</pre>\n";
  892. echo('El cliente ' . $this->cli_id . '<br>');*/
  893. /* if(!$this->ip4_servidor_dns['ip_address']){
  894. $servicio_dns = $app->db->queryOneRecord(
  895. 'SELECT server_id, dns_server, server_name FROM server
  896. WHERE server_id = "'.$this->dns_serv.'"');
  897. $nom_serv_dns = $servicio_dns['server_name'];
  898. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_dns;
  899. $this->onError();
  900. return true;
  901. }
  902. if(!$this->ip6_servidor_dns['ip_address']){
  903. $servicio_dns = $app->db->queryOneRecord(
  904. 'SELECT server_id, dns_server, server_name FROM server
  905. WHERE server_id = "'.$this->dns_serv.'"');
  906. $nom_serv_dns = $servicio_dns['server_name'];
  907. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor '. $nom_serv_dns;
  908. $this->onError();
  909. return true;
  910. }*/
  911. if(!$this->ip4_servidor_web['ip_address']){
  912. $servidor_web = $app->db->queryOneRecord(
  913. 'SELECT server_id, web_server, server_name FROM server
  914. WHERE server_id = "'.$this->web_serv.'"');
  915. $nom_serv_web = $servidor_web['server_name'];
  916. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_web;
  917. $this->onError();
  918. return true;
  919. }
  920. if(!$this->ip6_servidor_web['ip_address']){
  921. $servidor_web = $app->db->queryOneRecord(
  922. 'SELECT server_id, web_server, server_name FROM server
  923. WHERE server_id = "'.$this->web_serv.'"');
  924. $nom_serv_web = $servidor_web['server_name'];
  925. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor ' . $nom_serv_web;
  926. $this->onError();
  927. return true;
  928. }
  929. if(!$this->ip4_servidor_bbdd['ip_address']){
  930. $servicio_db = $app->db->queryOneRecord(
  931. 'SELECT server_id, db_server, server_name FROM server
  932. WHERE server_id = "'.$this->bbdd_serv.'"');
  933. $nom_serv_db = $servicio_db['server_name'];
  934. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_db;
  935. $this->onError();
  936. return true;
  937. }
  938. if(!$this->ip6_servidor_bbdd['ip_address']){
  939. $servicio_db = $app->db->queryOneRecord(
  940. 'SELECT server_id, db_server, server_name FROM server
  941. WHERE server_id = "'.$this->bbdd_serv.'"');
  942. $nom_serv_db = $servicio_db['server_name'];
  943. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor ' . $nom_serv_db;
  944. $this->onError();
  945. return true;
  946. }
  947. return false;
  948. }
  949. //Comprueba si los servidores asignados al usuario seleccionado tiene los servicios activos para cada caso.
  950. function servidoresActivados(){
  951. global $app, $conf;
  952. $servicio_web = $app->db->queryOneRecord(
  953. 'SELECT server_id, web_server, server_name FROM server
  954. WHERE server_id = "'.$this->web_serv.'"');
  955. $nom_serv_web = $servicio_web['server_name'];
  956. $servicio_dns = $app->db->queryOneRecord(
  957. 'SELECT server_id, dns_server, server_name FROM server
  958. WHERE server_id = "'.$this->dns_serv.'"');
  959. $nom_serv_dns = $servicio_dns['server_name'];
  960. $servicio_ftp = $app->db->queryOneRecord(
  961. 'SELECT server_id, file_server, server_name FROM server
  962. WHERE server_id = "'.$this->ftp_serv.'"');
  963. $nom_serv_ftp = $servicio_ftp['server_name'];
  964. $servicio_db = $app->db->queryOneRecord(
  965. 'SELECT server_id, db_server, server_name FROM server
  966. WHERE server_id = "'.$this->bbdd_serv.'"');
  967. $nom_serv_db = $servicio_db['server_name'];
  968. //print "<pre>Servidor WEB ";print_r($servicio_web);print "</pre>\n";
  969. if($servicio_web['web_server'] == 0){
  970. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_web . ' el servicio WEB.';
  971. $this->onError();
  972. return true;
  973. }
  974. //print "<pre>Servidor DNS ";print_r($servicio_dns);print "</pre>\n";
  975. if($servicio_dns['dns_server'] == 0){
  976. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_dns . ' el servicio DNS.';
  977. $this->onError();
  978. return true;
  979. }
  980. //print "<pre>Servidor FTP ";print_r($servicio_ftp);print "</pre>\n";
  981. if($servicio_ftp['file_server'] == 0){
  982. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_ftp . ' el servicio FTP.';
  983. $this->onError();
  984. return true;
  985. }
  986. //print "<pre>Servidor DB ";print_r($servicio_db);print "</pre>\n";
  987. if($servicio_db['db_server'] == 0){
  988. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_db . ' el servicio DB.';
  989. $this->onError();
  990. return true;
  991. }
  992. return false;
  993. }
  994. //Comprobación de que tenemos instalada nuestra plantilla
  995. function plantillaWebDNS(){
  996. global $app;
  997. if(!$app->db->queryOneRecord("SELECT name FROM dns_template WHERE name = 'webdns'")) {
  998. $app->tform->errorMessage = $app->tform->wordbook['error_plantilla_webdns'];
  999. $this->onError();
  1000. return true;
  1001. }
  1002. }
  1003. //Comprueba que no exista el dominio y que no tenga sitio web, puede tener sitio web y no tener dns.
  1004. function existeDominio($campos){
  1005. global $app, $conf;
  1006. if($app->db->queryOneRecord('SELECT * FROM dns_soa WHERE origin LIKE "'.$campos['domain'].'."')) {
  1007. $app->tform->errorMessage = $app->tform->wordbook['domain_error_unique'];
  1008. }
  1009. if($app->db->queryOneRecord('SELECT domain_id, domain FROM web_domain WHERE domain = "'.$campos['domain'].'"')) {
  1010. $app->tform->errorMessage = $app->tform->wordbook['error_sitio_web_existe'];
  1011. }
  1012. //IMPORTANTE. AQUI CONTROLAMOS LOS ERRORES QUE SE VALIDAN EN EL FORMULARIO, EN ESTE CASO EL CAMPO DEL DOMINIO.
  1013. if($app->tform->errorMessage)
  1014. {
  1015. $this->onError();
  1016. return true;
  1017. }
  1018. }
  1019. public $ip4_ultima;
  1020. public $ip6_ultima;
  1021. //Creación del las dns y sitio web para un dominio.
  1022. function crearDnsSitioWeb($remoto){
  1023. global $app, $conf;
  1024. $remote = new remote_actions;
  1025. //Carga de los campos del formulario.
  1026. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  1027. //Carga del formulario dns_soa para guardar en base de datos.
  1028. $tform_def_file = "../dns/form/dns_soa.tform.php";
  1029. $app->tform->loadFormDef($tform_def_file);
  1030. //Carga y seleccion de dns_template, si no esta creado se informa de que tiene que crearse.
  1031. $template_record = $app->db->queryOneRecord(
  1032. "SELECT * FROM dns_template WHERE visible = 'Y' AND name = 'webdns'"); /*'open6hosting'");*/
  1033. /*print "<pre>DNS SERVER ";print_r($this->dns_serv);print "</pre>\n";
  1034. print "<pre>WEB SERVER ";print_r($this->web_serv);print "</pre>\n";
  1035. print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
  1036. print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
  1037. print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
  1038. print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";*/
  1039. //Si el servidor es el que tiene asignado el cliente o el de admin por defecto, le damos esta ip4
  1040. /* if($this->dns_serv && $this->ip4_servidor_dns){
  1041. $this->ip4_ultima = $this->ip4_servidor_dns;
  1042. }
  1043. if($this->dns_serv && $this->ip6_servidor_dns){
  1044. $this->ip6_ultima = $this->ip6_servidor_dns;
  1045. }*/
  1046. if($this->web_serv && $this->ip4_servidor_web){
  1047. $this->ip4_ultima = $this->ip4_servidor_web;
  1048. }
  1049. if($this->web_serv && $this->ip6_servidor_web){
  1050. $this->ip6_ultima = $this->ip6_servidor_web;
  1051. }
  1052. $tpl_content = $template_record['template'];
  1053. // Reemplazo la variable que nos encontramos en base de datos por el valor que se ha introducido en el formulario
  1054. $tpl_content = str_replace('{DOMAIN}', $fields['domain'], $tpl_content);
  1055. //Carga de los datos en las variables de las ips.
  1056. $tpl_content = str_replace('{IP}', $this->ip4_ultima['ip_address'],/*$dns_ip_servidor['ip_address'],*/ $tpl_content);
  1057. $tpl_content = str_replace('{IPV6}', $this->ip6_ultima['ip_address'], /*$dns_ip_servidor_ipv6['ip_address'],*/ $tpl_content);
  1058. $enable_dnssec = 'N';
  1059. // Parse the template
  1060. $tpl_rows = explode("\n", $tpl_content);
  1061. $section = '';
  1062. $vars = array();
  1063. $vars['xfer']='';
  1064. $dns_rr = array();
  1065. foreach($tpl_rows as $row) {
  1066. $row = trim($row);
  1067. if(substr($row, 0, 1) == '[') {
  1068. if($row == '[ZONE]') {
  1069. $section = 'zone';
  1070. } elseif($row == '[DNS_RECORDS]') {
  1071. $section = 'dns_records';
  1072. } else {
  1073. die('Unknown section type');
  1074. }
  1075. } else {
  1076. if($row != '') {
  1077. // Handle zone section
  1078. if($section == 'zone') {
  1079. $parts = explode('=', $row);
  1080. $key = trim($parts[0]);
  1081. $val = trim($parts[1]);
  1082. if($key != '') $vars[$key] = $val;
  1083. }
  1084. // Handle DNS Record rows
  1085. if($section == 'dns_records') {
  1086. $parts = explode('|', $row);
  1087. $dns_rr[] = array(
  1088. 'name' => $parts[1],
  1089. 'type' => $parts[0],
  1090. 'data' => $parts[2],
  1091. 'aux' => $parts[3],
  1092. 'ttl' => $parts[4]
  1093. );
  1094. }
  1095. }
  1096. }
  1097. } // end foreach
  1098. // Insert the soa record
  1099. $sys_userid = $this->cli_id;//$cliente_id_seleccionado;//$fields['client_group_id'];
  1100. $origin = $vars['origin'];
  1101. $ns = $vars['ns'];
  1102. $mbox = str_replace('@', '.', $vars['mbox']);
  1103. $refresh = $vars['refresh'];
  1104. $retry = $vars['retry'];
  1105. $expire = $vars['expire'];
  1106. $minimum = $vars['minimum'];
  1107. $ttl = $vars['ttl'];
  1108. $xfer = $vars['xfer'];
  1109. $also_notify = $vars['also_notify'];
  1110. $update_acl = $vars['update_acl'];
  1111. $serial = $app->validate_dns->increase_serial(0);
  1112. $insert_data = array(
  1113. "sys_userid" => $this->sys_usuario_id,//$sysUsuarioId,//$fields['client_group_id'],
  1114. "sys_groupid" => $this->cli_grupo_id,//$cliente_groupid,//$client_group_id,
  1115. "sys_perm_user" => 'riud',
  1116. "sys_perm_group" => 'riud',
  1117. "sys_perm_other" => '',
  1118. "server_id" => $this->dns_serv,
  1119. "origin" => $origin,
  1120. "ns" => $ns,
  1121. "mbox" => $mbox,
  1122. "serial" => $serial,
  1123. "refresh" => $refresh,
  1124. "retry" => $retry,
  1125. "expire" => $expire,
  1126. "minimum" => $minimum,
  1127. "ttl" => $ttl,
  1128. "active" => 'Y',
  1129. "xfer" => $xfer,
  1130. "also_notify" => $also_notify,
  1131. "update_acl" => $update_acl,
  1132. "dnssec_wanted" => $enable_dnssec
  1133. );
  1134. $dns_soa_id = $app->db->datalogInsert('dns_soa', $insert_data, 'id');
  1135. $remote->dns_soa_after_insert($dns_soa_id, $this->cli_grupo_id);
  1136. // Insert the dns_rr records
  1137. if(is_array($dns_rr) && $dns_soa_id > 0) {
  1138. foreach($dns_rr as $rr) {
  1139. $insert_data = array(
  1140. "sys_userid" => $this->sys_usuario_id,//$sysUsuarioId, //$fields['client_group_id'],
  1141. "sys_groupid" => $this->cli_grupo_id,//$cliente_groupid, //$client_group_id,
  1142. "sys_perm_user" => 'riud',
  1143. "sys_perm_group" => 'riud',
  1144. "sys_perm_other" => '',
  1145. "server_id" => $this->dns_serv,
  1146. "zone" => $dns_soa_id,
  1147. "name" => $rr['name'],
  1148. "type" => $rr['type'],
  1149. "data" => $rr['data'],
  1150. "aux" => $rr['aux'],
  1151. "ttl" => $rr['ttl'],
  1152. "active" => 'Y'
  1153. );
  1154. $dns_rr_id = $app->db->datalogInsert('dns_rr', $insert_data, 'id');
  1155. $remote->dns_rr_after_insert($dns_rr_id, $this->cli_grupo_id);
  1156. }
  1157. }
  1158. //sites_web_domain_add
  1159. $tform_def_file = "../sites/form/web_vhost_domain.tform.php";
  1160. $app->tform->loadFormDef($tform_def_file);
  1161. //print_r($fields);
  1162. //echo('La sesión user id ' . $_SESSION['s']['user']['userid']);
  1163. // add site
  1164. $paramsite = array(
  1165. 'type' => 'vhost',
  1166. 'domain' => $fields['domain'],
  1167. 'server_id' => $this->web_serv,// $web_servidor, //$server_id,//$dns_servidor['default_webserver'],
  1168. //IMPORTANTE. Aquí­ no se ponen los campos sys_userid ni sys_groupid, el evento on_after_insert
  1169. //'sys_userid' => $sysUsuarioId, //$fields['client_group_id'],//$sys_userid,
  1170. //'sys_groupid' => $cliente_groupid,
  1171. 'ip_address' => '*', //$dns_ip_servidor['ip_address'],
  1172. 'ipv6_address' => $this->ip6_servidor_web['ip_address'], //$this->ip6_ultima['ip_address'], //$dns_ip_servidor_ipv6['ip_address'],
  1173. 'traffic_quota' => '-1',
  1174. 'hd_quota' => '0',
  1175. 'cgi' => 'y',
  1176. 'ssi' => 'y',
  1177. 'suexec' => 'y',
  1178. 'ruby' => 'n',
  1179. 'python' => 'n',
  1180. 'perl' => 'n',
  1181. 'errordocs' => '1',
  1182. 'subdomain' => 'www',
  1183. 'php' => 'php-fpm',
  1184. 'fastcgi_php_version' => '',
  1185. 'seo_redirect' => '',
  1186. 'rewrite_to_https' => 'n',
  1187. 'allow_override' => 'All',
  1188. 'http_port' => 80,
  1189. 'https_port' => 443,
  1190. 'apache_directives' => '',
  1191. 'nginx_directives' => '',
  1192. 'php_fpm_use_socket' => 'y',
  1193. 'pm' => 'ondemand',
  1194. 'pm_max_children' => 10,
  1195. 'pm_start_servers' => 1,
  1196. 'pm_min_spare_servers' => 1,
  1197. 'pm_max_spare_servers' => 5,
  1198. 'pm_process_idle_timeout' => 10,
  1199. 'pm_max_requests' => 0,
  1200. 'custom_php_ini' => '',
  1201. 'active' => 'y',
  1202. 'document_root' => '-',
  1203. 'system_user' => '-',
  1204. 'system_group' => '-',
  1205. 'log_retention' => 30,
  1206. 'client_group_id' => $this->cli_grupo_id,//$cliente_groupid, //$client_group_id,
  1207. );
  1208. //print 'Valores: ' . $dns_ip_servidor_ipv6 . " " . $formulario . " Parametros: " ;
  1209. //print "<pre>"; print_r($paramsite); print "</pre>\n";
  1210. /*print '<pre> cliente id ' . $fields['client_id'];
  1211. print "<pre>";print_r($fields);print "</pre>\n";*/
  1212. //print "<pre>Formulario ";print_r($formulario);print "</pre>\n";
  1213. //$this->crearBaseDatosFtp($remote);
  1214. //print 'DNS IPV6 ' . $dns_ip_servidor_ipv6['ip_address'];
  1215. //IMPORTANTE. El último parámetro es para lanzar un evento que llama a la función on_after_insert
  1216. //que prepara los campos document_root, system_user y system_group
  1217. //$site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php', $fields['client_group_id'], $paramsite, 'sites:web_vhost_domain:on_after_insert');
  1218. //IMPORTANTE. ESTE ES EL ÚNICO PLUGING QUE FUNCIONA.
  1219. $site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php',
  1220. $this->cli_id, /*$cliente_id_seleccionado,*/
  1221. $paramsite, 'sites:web_vhost_domain:on_after_insert');
  1222. //print 'Sitio id '. $site_id;
  1223. }
  1224. function onSubmit() {
  1225. global $app, $conf;
  1226. /*$sesionesLog = $_SESSION["s"]["user"]["typ"];
  1227. $sesionesLog2 = $_SESSION["s"]["user"];
  1228. $sesiones = $_SESSION;
  1229. $sesionId = $_SESSION["s"]["id"];*/
  1230. //print_r($sesiones);
  1231. //print('la ssessison es ' .$ssionId);
  1232. //print_r($sesionesLog2);
  1233. if($this->plantillaWebDNS()){
  1234. return;
  1235. }
  1236. //Carga de campos del formulario.
  1237. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  1238. //Creo la clase remote para usar las librerias
  1239. $remote = new remote_actions;
  1240. if($this->tieneServidorIPs()){
  1241. return;
  1242. }
  1243. if($this->servidoresActivados()){
  1244. return;
  1245. }
  1246. //------INICIO LIMITES--------------------------------------------------------------------------------------------------
  1247. $limitado = new limites($this->cli_grupo_id);
  1248. $tieneLimitesDNS = $limitado->limClienteDns();
  1249. $tieneLimitesWeb = $limitado->limClienteWebDominio();
  1250. $tieneLimitesDB = $limitado->limClienteDB();
  1251. if($tieneLimitesDNS || $tieneLimitesWeb || $tieneLimitesDB){
  1252. return;
  1253. }
  1254. //------FIN LIMITES-----------------------------------------------------------------------------------------------------
  1255. if($this->existeDominio($fields)){
  1256. return;
  1257. }
  1258. //Esta variable nos llega por jQuery desde el htm para el control de errores en la vista.
  1259. if($_POST['create'] != 1)
  1260. {
  1261. $app->tform->errorMessage = 'DUMMY';
  1262. $app->tpl->setVar($this->dataRecord);
  1263. $this->onShow();
  1264. return;
  1265. }
  1266. if($this->comprobarSubDominios($fields['domain'])){
  1267. $this->crearSubDominio($remote, $fields['domain']);
  1268. if(!$this->subdom_error){
  1269. $this->crearSitioWebSubdominio($remote);
  1270. $this->crearBaseDatosFtp($remote);
  1271. }
  1272. } else {
  1273. if(!$this->dominio_error){
  1274. $this->crearDnsSitioWeb($remote);
  1275. //Si todo va bien, el resultado de la web y dns
  1276. echo '<br><div class="alert alert-success"><br>
  1277. Altas Web y DNS del dominio <b>'.$fields['domain'].'</b>, ¡Creadas correctamente!
  1278. <br><br></div></br>';
  1279. //IMPORTANTE, es necesario cargar nuestro formulario para poder ejecutar la función que crea
  1280. //la base de datos y el ftp ya que hay datos que tomamos de el antes de ejecutarla.
  1281. $app->tform->loadFormDef('form/new_service_webdns.tform.php');
  1282. $this->crearBaseDatosFtp($remote);
  1283. }else{
  1284. $this->onError();
  1285. return;
  1286. }
  1287. }
  1288. }
  1289. }
  1290. class remote_actions extends remoting {
  1291. public function insert_query($formdef_file, $client_id, $params, $event_identifier = '') {
  1292. global $app;
  1293. /*$sql = $this->insertQueryPrepare($formdef_file, $client_id, $params);
  1294. echo(' Query ' . $sql);
  1295. $app->uses('remoting_lib');
  1296. $app->remoting_lib->loadUserProfile();*/
  1297. //return $app->db->query($sql);//$this->insertQueryExecute($sql, $params, $event_identifier);
  1298. //echo(' insertQueryPrepare ' . $this->insertQueryExecute($sql, $params, $event_identifier));
  1299. return $this->insertQueryWebDNS($formdef_file, $client_id, $params, $event_identifier);
  1300. }
  1301. //------------------------------------------------------------------------------------------------------------
  1302. //IMPORTANTE. FUNCIONES EXTRAIDAS Y MODIFICADAS DE ISPCONFIG PARA SOLUCIONAR EL PROBLEMA DE AUTOLOGEO A ADMIN.
  1303. //------------------------------------------------------------------------------------------------------------
  1304. function insertQueryWebDNS($formdef_file, $client_id, $params, $event_identifier = '') {
  1305. //$sql = $app->remoting->insertQueryPrepare($formdef_file, $client_id, $params);
  1306. $sql = $this->insertQueryPrepareWebDNS($formdef_file, $client_id, $params);
  1307. if($sql !== false) return $this->insertQueryExecuteWebDNS($sql, $params, $event_identifier);
  1308. else return false;
  1309. }
  1310. function insertQueryPrepareWebDNS($formdef_file, $client_id, $params) {
  1311. global $app;
  1312. $app->uses('remoting_lib');
  1313. //* load the user profile of the client
  1314. //$app->remoting_lib->loadUserProfile($client_id);
  1315. //* Load the form definition
  1316. $app->remoting_lib->loadFormDef($formdef_file);
  1317. //echo(' Base de datos ' . $app->remoting_lib->loadFormDef($formdef_file));
  1318. //* Get the SQL query
  1319. $sql = $app->remoting_lib->getSQL($params, 'INSERT', 0);
  1320. /*if($app->remoting_lib->errorMessage != '') {
  1321. throw new SoapFault('data_processing_error', $app->remoting_lib->errorMessage);
  1322. return false;
  1323. }*/
  1324. $app->log('Executed insertQueryPrepareWebDNS', LOGLEVEL_DEBUG);
  1325. return $sql;
  1326. }
  1327. function insertQueryExecuteWebDNS($sql, $params, $event_identifier = '') {
  1328. global $app;
  1329. $app->uses('remoting_lib');
  1330. $app->db->query($sql);
  1331. /*if($app->db->errorMessage != '') {
  1332. throw new SoapFault('database_error', $app->db->errorMessage . ' '.$sql);
  1333. return false;
  1334. }*/
  1335. if ( isset($params['_primary_id'] ))
  1336. $insert_id = $params['_primary_id'];
  1337. else
  1338. $insert_id = $app->db->insertID();
  1339. // set a few values for compatibility with tform actions, mostly used by plugins
  1340. $this->id = $insert_id;
  1341. $this->dataRecord = $params;
  1342. $app->log('Executed insertQueryExecute, raising events now if any: ' . $event_identifier, LOGLEVEL_DEBUG);
  1343. if($event_identifier != '') $app->plugin->raiseEvent($event_identifier, $this);
  1344. //$app->uses('tform');
  1345. //* Save changes to Datalog
  1346. if($app->remoting_lib->formDef["db_history"] == 'yes') {
  1347. //$new_rec = $app->remoting_lib->getDataRecord($insert_id);
  1348. $new_rec = $this->getDataRecordWebDNS($insert_id);
  1349. $app->remoting_lib->datalogSave('INSERT', $primary_id, array(), $new_rec);
  1350. }
  1351. return $insert_id;
  1352. }
  1353. function sites_ftp_user_after_insert() {
  1354. global $app, $conf;
  1355. $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
  1356. //echo(' Valor FTP ' . $this->dataRecord["parent_domain_id"]);
  1357. $server_id = $app->functions->intval($web["server_id"]);
  1358. $dir = $web["document_root"];
  1359. $uid = $web["system_user"];
  1360. $gid = $web["system_group"];
  1361. // Check system user and group
  1362. if($app->functions->is_allowed_user($uid) == false || $app->functions->is_allowed_group($gid) == false) {
  1363. $app->error('Invalid system user or group');
  1364. }
  1365. // The FTP user shall be owned by the same group then the website
  1366. $sys_groupid = $app->functions->intval($web['sys_groupid']);
  1367. $sql = "UPDATE ftp_user SET server_id = ?, dir = ?, uid = ?, gid = ?, sys_groupid = ? WHERE ftp_user_id = ?";
  1368. $app->db->query($sql, $server_id, $dir, $uid, $gid, $sys_groupid, $this->id);
  1369. }
  1370. function dns_rr_after_insert($dns_rr_id, $cliente_grupo_id) {
  1371. global $app, $conf;
  1372. //echo(' el cliente grupo id ' . $cliente_grupo_id . ' el id tupla en dns_rr ' . $dns_rr_id);
  1373. if($_SESSION["s"]["user"]["typ"] == 'user') {
  1374. $app->db->datalogUpdate('dns_rr', array("sys_userid" => $cliente_grupo_id,
  1375. "sys_groupid" => $cliente_grupo_id), 'id', $dns_rr_id);
  1376. }
  1377. if($_SESSION["s"]["user"]["typ"] == 'admin') {
  1378. $app->db->datalogUpdate('dns_rr', array("sys_userid" => 1, //$cliente_grupo_id,
  1379. "sys_groupid" => $cliente_grupo_id), 'id', $dns_rr_id);
  1380. }
  1381. }
  1382. function dns_soa_after_insert($dns_soa_id, $cliente_grupo_id) {
  1383. global $app, $conf;
  1384. //echo(' el cliente grupo id ' . $cliente_grupo_id . ' el id tupla en dns_rr ' . $dns_soa_id . ' sys usuario ' . $sys_usuario_id);
  1385. if($_SESSION["s"]["user"]["typ"] == 'user') {
  1386. $app->db->datalogUpdate('dns_soa', array("sys_userid" => $cliente_grupo_id,
  1387. "sys_groupid" => $cliente_grupo_id), 'id', $dns_soa_id);
  1388. }
  1389. if($_SESSION["s"]["user"]["typ"] == 'admin') {
  1390. $app->db->datalogUpdate('dns_soa', array("sys_userid" => 1, //$cliente_grupo_id,
  1391. "sys_groupid" => $cliente_grupo_id), 'id', $dns_soa_id);
  1392. }
  1393. }
  1394. function dns_registro_tipo_a_after_insert($cli_grupo_id) {
  1395. global $app, $conf;
  1396. //echo(' el valor zone ' . $this->dataRecord["zone"]);
  1397. //* Set the sys_groupid of the rr record to be the same then the sys_groupid of the soa record
  1398. if($_SESSION["s"]["user"]["typ"] == 'user') {
  1399. $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
  1400. $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $soa['sys_groupid']), 'id', $this->id);
  1401. }
  1402. /*if($_SESSION["s"]["user"]["typ"] == 'admin') {
  1403. $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
  1404. $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $soa['sys_groupid']), 'id', $this->id);
  1405. }*/
  1406. if($app->auth->has_clients($_SESSION['s']['user']['userid'])) {
  1407. $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
  1408. $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $cli_grupo_id), 'id', $this->id);
  1409. }
  1410. //* Update the serial number of the SOA record
  1411. /*$soa_id = $app->functions->intval($_POST["zone"]);
  1412. $serial = $app->validate_dns->increase_serial($soa["serial"]);
  1413. $app->db->datalogUpdate('dns_soa', array("serial" => $serial), 'id', $soa_id);*/
  1414. }
  1415. public function sites_database_user_after_add($client_id, $params){
  1416. global $app, $conf;
  1417. //echo('Plugeando');
  1418. // if($_SESSION["s"]["user"]["typ"] == 'user' /*&& isset($this->dataRecord["client_group_id"])*/) {
  1419. //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
  1420. $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
  1421. /* }
  1422. if($_SESSION["s"]["user"]["typ"] == 'admin'/* && isset($this->dataRecord["client_group_id"])*///) {
  1423. //echo('Plugeando ' .$app->functions->intval($this->dataRecord["client_group_id"]) . ' y ' . $client_id . ' id ' . $this->id);
  1424. //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
  1425. /* $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
  1426. }
  1427. if($app->auth->has_clients($_SESSION['s']['user']['userid'])/* && isset($this->dataRecord["client_group_id"])*///) {
  1428. //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
  1429. /* $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
  1430. }
  1431. $app->uses('sites_web_database_user_plugin');
  1432. global $app;
  1433. //Register for the events
  1434. $app->plugin->registerEvent('sites:web_database_user:on_after_update', 'sites_web_database_user_plugin', 'sites_web_database_user_edit');
  1435. $app->plugin->registerEvent('sites:web_database_user:on_after_insert', 'sites_web_database_user_plugin', 'sites_web_database_user_edit');
  1436. */
  1437. }
  1438. public function sites_database_user_add($session_id, $client_id, $params, $event_identifier = '') {
  1439. global $app;
  1440. /*if(!$this->checkPerm($session_id, 'sites_database_user_add')) {
  1441. throw new SoapFault('permission_denied', 'You do not have the permissions to access this function.');
  1442. return false;
  1443. }*/
  1444. //echo(' la tablita ' . $this->formDef['db_table']);
  1445. return $this->insertQueryWebDNS('../sites/form/database_user.tform.php', $client_id, $params, $event_identifier);
  1446. }
  1447. function getDataRecordWebDNS($primary_id) {
  1448. global $app;
  1449. $escape = '`';
  1450. //$this->loadUserProfile();
  1451. if(@is_numeric($primary_id)) {
  1452. if($primary_id > 0) {
  1453. // Return a single record
  1454. //return $this->getDataRecordPadreWebDNS($primary_id);
  1455. return $app->tform->getDataRecord($primary_id);
  1456. //return parent::getDataRecord($primary_id);
  1457. } elseif($primary_id == -1) {
  1458. // Return a array with all records
  1459. $sql = "SELECT * FROM ??";
  1460. return $app->db->queryAllRecords($sql, $this->formDef['db_table']);
  1461. } else {
  1462. throw new SoapFault('invalid_id', 'The ID has to be > 0 or -1.');
  1463. return array();
  1464. }
  1465. } elseif (@is_array($primary_id) || @is_object($primary_id)) {
  1466. 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!
  1467. $sql_offset = 0;
  1468. $sql_limit = 0;
  1469. $sql_where = '';
  1470. $params = array($this->formDef['db_table']);
  1471. foreach($primary_id as $key => $val) {
  1472. if($key == '#OFFSET#') $sql_offset = $app->functions->intval($val);
  1473. elseif($key == '#LIMIT#') $sql_limit = $app->functions->intval($val);
  1474. elseif(stristr($val, '%')) {
  1475. $sql_where .= "?? like ? AND ";
  1476. } else {
  1477. $sql_where .= "?? = ? AND ";
  1478. }
  1479. $params[] = $key;
  1480. $params[] = $val;
  1481. }
  1482. $sql_where = substr($sql_where, 0, -5);
  1483. if($sql_where == '') $sql_where = '1';
  1484. //$sql = "SELECT * FROM ?? WHERE ".$sql_where. " AND " . $this->getAuthSQLWebDNS('r', $this->formDef['db_table']);
  1485. $sql = "SELECT * FROM ?? WHERE ".$sql_where. " AND " . $this->getAuthSQL('r', $this->formDef['db_table']);
  1486. if($sql_offset >= 0 && $sql_limit > 0) $sql .= ' LIMIT ' . $sql_offset . ',' . $sql_limit;
  1487. return $app->db->queryAllRecords($sql, true, $params);
  1488. } else {
  1489. $this->errorMessage = 'The ID must be either an integer or an array.';
  1490. return array();
  1491. }
  1492. }
  1493. /*function getDataRecordPadreWebDNS($primary_id) {
  1494. global $app;
  1495. $escape = '`';
  1496. $sql = "SELECT * FROM ?? WHERE ?? = ? AND ".$this->getAuthSQLWebDNS('r', $this->formDef['db_table']);
  1497. return $app->db->queryOneRecord($sql, $this->formDef['db_table'], $this->formDef['db_table_idx'], $primary_id);
  1498. }*/
  1499. function getAuthSQLWebDNS($perm, $table = '') {
  1500. if($_SESSION["s"]["user"]["typ"] == 'admin' || $_SESSION['s']['user']['mailuser_id'] > 0) {
  1501. return '1';
  1502. } else {
  1503. if ($table != ''){
  1504. $table = ' ' . $table . '.';
  1505. }
  1506. $groups = ( $_SESSION["s"]["user"]["groups"] ) ? $_SESSION["s"]["user"]["groups"] : 0;
  1507. $sql = '(';
  1508. $sql .= "(" . $table . "sys_userid = ".$_SESSION["s"]["user"]["userid"]." AND " . $table . "sys_perm_user like '%$perm%') OR ";
  1509. $sql .= "(" . $table . "sys_groupid IN (".$groups.") AND " . $table ."sys_perm_group like '%$perm%') OR ";
  1510. $sql .= $table . "sys_perm_other like '%$perm%'";
  1511. $sql .= ')';
  1512. return $sql;
  1513. }
  1514. }
  1515. //----------------------------------------------------------------------------------
  1516. //IMPORTANTE. ESTA FUNCION ES COMO LO HACE ISPCONFIG NO EXTRAIDA PERO SI MODIFICADA.
  1517. //----------------------------------------------------------------------------------
  1518. public function sites_database_add($client_id, $params){
  1519. global $app, $conf;
  1520. //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO
  1521. //DE LO QUE SE QUIERE CREAR EN ESTE CASO SITIO WEB
  1522. $tform_def_file = "../sites/form/database.tform.php";
  1523. $app->tform->loadFormDef($tform_def_file);
  1524. $app->remoting_lib->loadFormDef('../sites/form/database.tform.php');
  1525. //$app->tform->formDef('../sites/form/database.tform.php');
  1526. //$sql = $app->remoting->insertQueryPrepare('../sites/form/database.tform.php', $client_id, $params);
  1527. $sql = $this->insertQueryPrepareWebDNS('../sites/form/database.tform.php', $client_id, $params);
  1528. if($sql !== false) {
  1529. $app->uses('sites_database_plugin');
  1530. //print_r($sql);
  1531. $this->id = 0;
  1532. $this->dataRecord = $params;
  1533. //$app->uses('sites_database_plugin');
  1534. //$app->sites_database_plugin->processDatabaseInsert($this);
  1535. //$retval = $this->insertQueryExecute($sql, $params);
  1536. $retval = $this->insertQueryExecuteWebDNS($sql, $params);
  1537. $app->sites_database_plugin->processDatabaseInsert($this);
  1538. //$app->plugin->raiseEvent('sites:web_database:on_after_insert', $this);
  1539. // set correct values for backup_interval and backup_copies
  1540. /*if(isset($params['backup_interval']) || isset($params['backup_copies'])){
  1541. $sql_set = array();
  1542. if(isset($params['backup_interval'])) $sql_set[] = "backup_interval = '".$app->db->quote($params['backup_interval'])."'";
  1543. if(isset($params['backup_copies'])) $sql_set[] = "backup_copies = ".$app->functions->intval($params['backup_copies']);
  1544. //$app->db->query("UPDATE web_database SET ".implode(', ', $sql_set)." WHERE database_id = ".$retval);
  1545. $this->updateQueryExecute("UPDATE web_database SET ".implode(', ', $sql_set)." WHERE database_id = ".$retval, $retval, $params);
  1546. }*/
  1547. return $retval;
  1548. }
  1549. return false;
  1550. }
  1551. }
  1552. $page = new page_action;
  1553. $page->onLoad();
  1554. //IMPORTENTE, es necesario estas lí­neas para que el botón del pdf funcione. Activa el javascript
  1555. //echo '<script type="text/javascript">';
  1556. //echo '</script>';
  1557. ?>
  1558. <!--IMPORTENTE, es necesario estas lí­neas para que el botón del pdf funcione. Activa el javascript -->
  1559. <script type="text/javascript">
  1560. </script>