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

1836 строки
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. //El cliente 1 es admin
  711. //Captura de las ips del servidor dns
  712. if($this->cli_id == 0){
  713. //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
  714. //Alguno de los dos tiene que existir por configuración de ispconfig.
  715. $this->ip4_servidor_dns = $app->db->queryOneRecord(
  716. 'SELECT ip_type, ip_address FROM server_ip
  717. WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  718. $this->ip6_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="IPv6"');
  721. if(!$this->ip4_servidor_dns){
  722. $this->ip4_servidor_dns = $app->db->queryOneRecord(
  723. 'SELECT ip_type, ip_address FROM server_ip
  724. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  725. }
  726. if(!$this->ip6_servidor_dns){
  727. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  728. 'SELECT ip_type, ip_address FROM server_ip
  729. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
  730. }
  731. }else{//Comprobamos si el cliente tiene servidor asignado, si no lo tiene asignamos el que admin a seleccionado
  732. //para este servidor.
  733. $this->ip4_servidor_dns = $app->db->queryOneRecord(
  734. 'SELECT ip_type, ip_address
  735. FROM server_ip
  736. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  737. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  738. 'SELECT ip_type, ip_address
  739. FROM server_ip
  740. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->dns_serv.'"AND ip_type="IPv6"');
  741. //si no tiene asignado le damos el de admin.
  742. if(!$this->ip4_servidor_dns){
  743. //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
  744. //Tomamos las de admin.
  745. //Alguno de los dos tiene que existir por configuración de ispconfig.
  746. $this->ip4_servidor_dns = $app->db->queryOneRecord(
  747. 'SELECT ip_type, ip_address FROM server_ip
  748. WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  749. if(!$this->ip4_servidor_dns){
  750. $this->ip4_servidor_dns = $app->db->queryOneRecord(
  751. 'SELECT ip_type, ip_address FROM server_ip
  752. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv4"');
  753. }
  754. }
  755. if(!$this->ip6_servidor_dns){
  756. //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
  757. //Tomamos las de admin.
  758. //Alguno de los dos tiene que existir por configuración de ispconfig.
  759. //$this->ip4_servidor_dns = $app->db->queryOneRecord('SELECT ip_type, ip_address FROM server_ip WHERE client_id = "0" AND ip_type="IPv4"');
  760. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  761. 'SELECT ip_type, ip_address FROM server_ip
  762. WHERE client_id = "0" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
  763. if(!$this->ip6_servidor_dns){
  764. $this->ip6_servidor_dns = $app->db->queryOneRecord(
  765. 'SELECT ip_type, ip_address FROM server_ip
  766. WHERE client_id = "1" AND server_id = "'.$this->dns_serv.'" AND ip_type="IPv6"');
  767. }
  768. }
  769. }
  770. //Captura de las ips del servidor web
  771. if($this->cli_id == 0){
  772. //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
  773. //Alguno de los dos tiene que existir por configuración de ispconfig.
  774. $this->ip4_servidor_web = $app->db->queryOneRecord(
  775. 'SELECT ip_type, ip_address FROM server_ip
  776. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  777. $this->ip6_servidor_web = $app->db->queryOneRecord(
  778. 'SELECT ip_type, ip_address FROM server_ip
  779. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  780. /*if(!$this->ip4_servidor_web){
  781. $this->ip4_servidor_web = $app->db->queryOneRecord(
  782. 'SELECT ip_type, ip_address FROM server_ip
  783. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  784. }
  785. if(!$this->ip6_servidor_web){
  786. $this->ip6_servidor_web = $app->db->queryOneRecord(
  787. 'SELECT ip_type, ip_address FROM server_ip
  788. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  789. }*/
  790. }else{//Comprobamos si el cliente tiene servidor asignado
  791. $this->ip4_servidor_web = $app->db->queryOneRecord(
  792. 'SELECT ip_type, ip_address
  793. FROM server_ip
  794. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  795. $this->ip6_servidor_web = $app->db->queryOneRecord(
  796. 'SELECT ip_type, ip_address
  797. FROM server_ip
  798. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->web_serv.'"AND ip_type="IPv6"');
  799. //si no tiene asignado le damos el de admin.
  800. if(!$this->ip4_servidor_web){
  801. $this->ip4_servidor_web = $app->db->queryOneRecord(
  802. 'SELECT ip_type, ip_address FROM server_ip
  803. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  804. /*if(!$this->ip4_servidor_web){
  805. $this->ip4_servidor_web = $app->db->queryOneRecord(
  806. 'SELECT ip_type, ip_address FROM server_ip
  807. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv4"');
  808. }*/
  809. }
  810. if(!$this->ip6_servidor_web){
  811. $this->ip6_servidor_web = $app->db->queryOneRecord(
  812. 'SELECT ip_type, ip_address FROM server_ip
  813. WHERE client_id = "0" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  814. /*if(!$this->ip6_servidor_web){
  815. $this->ip6_servidor_web = $app->db->queryOneRecord(
  816. 'SELECT ip_type, ip_address FROM server_ip
  817. WHERE client_id = "1" AND server_id = "'.$this->web_serv.'" AND ip_type="IPv6"');
  818. }*/
  819. }
  820. }
  821. //Captura de las ips del servidor bbdd
  822. if($this->cli_id == 0){
  823. //Compruebo si hay datos para el client_id 0 y si no existe pruebo con el 1.
  824. //Alguno de los dos tiene que existir por configuración de ispconfig.
  825. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  826. 'SELECT ip_type, ip_address FROM server_ip
  827. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  828. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  829. 'SELECT ip_type, ip_address FROM server_ip
  830. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  831. /*if(!$this->ip4_servidor_bbdd){
  832. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  833. 'SELECT ip_type, ip_address FROM server_ip
  834. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  835. }
  836. if(!$this->ip6_servidor_bbdd){
  837. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  838. 'SELECT ip_type, ip_address FROM server_ip
  839. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  840. }*/
  841. }else{//Comprobamos si el cliente tiene servidor asignado
  842. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  843. 'SELECT ip_type, ip_address
  844. FROM server_ip
  845. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  846. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  847. 'SELECT ip_type, ip_address
  848. FROM server_ip
  849. WHERE client_id = "'.$this->cli_id.'" AND server_id = "'.$this->bbdd_serv.'"AND ip_type="IPv6"');
  850. //si no tiene asignado le damos el de admin.
  851. if(!$this->ip4_servidor_bbdd){
  852. //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
  853. //Tomamos las de admin.
  854. //Alguno de los dos tiene que existir por configuración de ispconfig.
  855. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  856. 'SELECT ip_type, ip_address FROM server_ip
  857. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  858. /*if(!$this->ip4_servidor_bbdd){
  859. $this->ip4_servidor_bbdd = $app->db->queryOneRecord(
  860. 'SELECT ip_type, ip_address FROM server_ip
  861. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv4"');
  862. }*/
  863. }
  864. if(!$this->ip6_servidor_bbdd){
  865. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  866. 'SELECT ip_type, ip_address FROM server_ip
  867. WHERE client_id = "0" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  868. /*if(!$this->ip6_servidor_bbdd){
  869. $this->ip6_servidor_bbdd = $app->db->queryOneRecord(
  870. 'SELECT ip_type, ip_address FROM server_ip
  871. WHERE client_id = "1" AND server_id = "'.$this->bbdd_serv.'" AND ip_type="IPv6"');
  872. }*/
  873. }
  874. }
  875. //para el servidor ftp no se hacen comprobaciones
  876. //ya que las ips son las mismas que para el servidor web.
  877. //$la_ip4 = $app->db->queryOneRecord("SELECT ip_type, ip_address FROM server_ip WHERE ip_type='IPv4'");
  878. $this->ip4_pdf = $this->ip4_servidor_dns['ip_address'];//$dns_ip_servidor['ip_address'];//$la_ip4['ip_address'];
  879. /*print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
  880. print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
  881. print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
  882. print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";
  883. print "<pre>IP4 BBDD ";print_r($this->ip4_servidor_bbdd);print "</pre>\n";
  884. print "<pre>IP6 BBDD ";print_r($this->ip6_servidor_bbdd);print "</pre>\n";
  885. echo('El cliente ' . $this->cli_id . '<br>');*/
  886. if(!$this->ip4_servidor_dns['ip_address']){
  887. $servicio_dns = $app->db->queryOneRecord(
  888. 'SELECT server_id, dns_server, server_name FROM server
  889. WHERE server_id = "'.$this->dns_serv.'"');
  890. $nom_serv_dns = $servicio_dns['server_name'];
  891. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_dns;
  892. $this->onError();
  893. return true;
  894. }
  895. if(!$this->ip6_servidor_dns['ip_address']){
  896. $servicio_dns = $app->db->queryOneRecord(
  897. 'SELECT server_id, dns_server, server_name FROM server
  898. WHERE server_id = "'.$this->dns_serv.'"');
  899. $nom_serv_dns = $servicio_dns['server_name'];
  900. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor '. $nom_serv_dns;
  901. $this->onError();
  902. return true;
  903. }
  904. if(!$this->ip4_servidor_web['ip_address']){
  905. $servidor_web = $app->db->queryOneRecord(
  906. 'SELECT server_id, web_server, server_name FROM server
  907. WHERE server_id = "'.$this->web_serv.'"');
  908. $nom_serv_web = $servidor_web['server_name'];
  909. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_web;
  910. $this->onError();
  911. return true;
  912. }
  913. if(!$this->ip6_servidor_web['ip_address']){
  914. $servidor_web = $app->db->queryOneRecord(
  915. 'SELECT server_id, web_server, server_name FROM server
  916. WHERE server_id = "'.$this->web_serv.'"');
  917. $nom_serv_web = $servidor_web['server_name'];
  918. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor ' . $nom_serv_web;
  919. $this->onError();
  920. return true;
  921. }
  922. if(!$this->ip4_servidor_bbdd['ip_address']){
  923. $servicio_db = $app->db->queryOneRecord(
  924. 'SELECT server_id, db_server, server_name FROM server
  925. WHERE server_id = "'.$this->bbdd_serv.'"');
  926. $nom_serv_db = $servicio_db['server_name'];
  927. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP4 para el servidor ' . $nom_serv_db;
  928. $this->onError();
  929. return true;
  930. }
  931. if(!$this->ip6_servidor_bbdd['ip_address']){
  932. $servicio_db = $app->db->queryOneRecord(
  933. 'SELECT server_id, db_server, server_name FROM server
  934. WHERE server_id = "'.$this->bbdd_serv.'"');
  935. $nom_serv_db = $servicio_db['server_name'];
  936. $app->tform->errorMessage = $app->tform->wordbook['error_no_ip']. 'la IP6 para el servidor ' . $nom_serv_db;
  937. $this->onError();
  938. return true;
  939. }
  940. return false;
  941. }
  942. //Comprueba si los servidores asignados al usuario seleccionado tiene los servicios activos para cada caso.
  943. function servidoresActivados(){
  944. global $app, $conf;
  945. $servicio_web = $app->db->queryOneRecord(
  946. 'SELECT server_id, web_server, server_name FROM server
  947. WHERE server_id = "'.$this->web_serv.'"');
  948. $nom_serv_web = $servicio_web['server_name'];
  949. $servicio_dns = $app->db->queryOneRecord(
  950. 'SELECT server_id, dns_server, server_name FROM server
  951. WHERE server_id = "'.$this->dns_serv.'"');
  952. $nom_serv_dns = $servicio_dns['server_name'];
  953. $servicio_ftp = $app->db->queryOneRecord(
  954. 'SELECT server_id, file_server, server_name FROM server
  955. WHERE server_id = "'.$this->ftp_serv.'"');
  956. $nom_serv_ftp = $servicio_ftp['server_name'];
  957. $servicio_db = $app->db->queryOneRecord(
  958. 'SELECT server_id, db_server, server_name FROM server
  959. WHERE server_id = "'.$this->bbdd_serv.'"');
  960. $nom_serv_db = $servicio_db['server_name'];
  961. //print "<pre>Servidor WEB ";print_r($servicio_web);print "</pre>\n";
  962. if($servicio_web['web_server'] == 0){
  963. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_web . ' el servicio WEB.';
  964. $this->onError();
  965. return true;
  966. }
  967. //print "<pre>Servidor DNS ";print_r($servicio_dns);print "</pre>\n";
  968. if($servicio_dns['dns_server'] == 0){
  969. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_dns . ' el servicio DNS.';
  970. $this->onError();
  971. return true;
  972. }
  973. //print "<pre>Servidor FTP ";print_r($servicio_ftp);print "</pre>\n";
  974. if($servicio_ftp['file_server'] == 0){
  975. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_ftp . ' el servicio FTP.';
  976. $this->onError();
  977. return true;
  978. }
  979. //print "<pre>Servidor DB ";print_r($servicio_db);print "</pre>\n";
  980. if($servicio_db['db_server'] == 0){
  981. $app->tform->errorMessage = $app->tform->wordbook['error_activado_servidor'] . $nom_serv_db . ' el servicio DB.';
  982. $this->onError();
  983. return true;
  984. }
  985. return false;
  986. }
  987. //Comprobación de que tenemos instalada nuestra plantilla
  988. function plantillaWebDNS(){
  989. global $app;
  990. if(!$app->db->queryOneRecord("SELECT name FROM dns_template WHERE name = 'webdns'")) {
  991. $app->tform->errorMessage = $app->tform->wordbook['error_plantilla_webdns'];
  992. $this->onError();
  993. return true;
  994. }
  995. }
  996. //Comprueba que no exista el dominio y que no tenga sitio web, puede tener sitio web y no tener dns.
  997. function existeDominio($campos){
  998. global $app, $conf;
  999. if($app->db->queryOneRecord('SELECT * FROM dns_soa WHERE origin LIKE "'.$campos['domain'].'."')) {
  1000. $app->tform->errorMessage = $app->tform->wordbook['domain_error_unique'];
  1001. }
  1002. if($app->db->queryOneRecord('SELECT domain_id, domain FROM web_domain WHERE domain = "'.$campos['domain'].'"')) {
  1003. $app->tform->errorMessage = $app->tform->wordbook['error_sitio_web_existe'];
  1004. }
  1005. //IMPORTANTE. AQUI CONTROLAMOS LOS ERRORES QUE SE VALIDAN EN EL FORMULARIO, EN ESTE CASO EL CAMPO DEL DOMINIO.
  1006. if($app->tform->errorMessage)
  1007. {
  1008. $this->onError();
  1009. return true;
  1010. }
  1011. }
  1012. public $ip4_ultima;
  1013. public $ip6_ultima;
  1014. //Creación del las dns y sitio web para un dominio.
  1015. function crearDnsSitioWeb($remoto){
  1016. global $app, $conf;
  1017. $remote = new remote_actions;
  1018. //Carga de los campos del formulario.
  1019. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  1020. //Carga del formulario dns_soa para guardar en base de datos.
  1021. $tform_def_file = "../dns/form/dns_soa.tform.php";
  1022. $app->tform->loadFormDef($tform_def_file);
  1023. //Carga y seleccion de dns_template, si no esta creado se informa de que tiene que crearse.
  1024. $template_record = $app->db->queryOneRecord(
  1025. "SELECT * FROM dns_template WHERE visible = 'Y' AND name = 'webdns'"); /*'open6hosting'");*/
  1026. /*print "<pre>DNS SERVER ";print_r($this->dns_serv);print "</pre>\n";
  1027. print "<pre>WEB SERVER ";print_r($this->web_serv);print "</pre>\n";
  1028. print "<pre>IP4 DNS ";print_r($this->ip4_servidor_dns);print "</pre>\n";
  1029. print "<pre>IP6 DNS ";print_r($this->ip6_servidor_dns);print "</pre>\n";
  1030. print "<pre>IP4 WEB ";print_r($this->ip4_servidor_web);print "</pre>\n";
  1031. print "<pre>IP6 WEB ";print_r($this->ip6_servidor_web);print "</pre>\n";*/
  1032. //Si el servidor es el que tiene asignado el cliente o el de admin por defecto, le damos esta ip4
  1033. if($this->dns_serv && $this->ip4_servidor_dns){
  1034. $this->ip4_ultima = $this->ip4_servidor_dns;
  1035. }
  1036. if($this->dns_serv && $this->ip6_servidor_dns){
  1037. $this->ip6_ultima = $this->ip6_servidor_dns;
  1038. }
  1039. if($this->web_serv && $this->ip4_servidor_web){
  1040. $this->ip4_ultima = $this->ip4_servidor_web;
  1041. }
  1042. if($this->web_serv && $this->ip6_servidor_web){
  1043. $this->ip6_ultima = $this->ip6_servidor_web;
  1044. }
  1045. $tpl_content = $template_record['template'];
  1046. // Reemplazo la variable que nos encontramos en base de datos por el valor que se ha introducido en el formulario
  1047. $tpl_content = str_replace('{DOMAIN}', $fields['domain'], $tpl_content);
  1048. //Carga de los datos en las variables de las ips.
  1049. $tpl_content = str_replace('{IP}', $this->ip4_ultima['ip_address'],/*$dns_ip_servidor['ip_address'],*/ $tpl_content);
  1050. $tpl_content = str_replace('{IPV6}', $this->ip6_ultima['ip_address'], /*$dns_ip_servidor_ipv6['ip_address'],*/ $tpl_content);
  1051. $enable_dnssec = 'N';
  1052. // Parse the template
  1053. $tpl_rows = explode("\n", $tpl_content);
  1054. $section = '';
  1055. $vars = array();
  1056. $vars['xfer']='';
  1057. $dns_rr = array();
  1058. foreach($tpl_rows as $row) {
  1059. $row = trim($row);
  1060. if(substr($row, 0, 1) == '[') {
  1061. if($row == '[ZONE]') {
  1062. $section = 'zone';
  1063. } elseif($row == '[DNS_RECORDS]') {
  1064. $section = 'dns_records';
  1065. } else {
  1066. die('Unknown section type');
  1067. }
  1068. } else {
  1069. if($row != '') {
  1070. // Handle zone section
  1071. if($section == 'zone') {
  1072. $parts = explode('=', $row);
  1073. $key = trim($parts[0]);
  1074. $val = trim($parts[1]);
  1075. if($key != '') $vars[$key] = $val;
  1076. }
  1077. // Handle DNS Record rows
  1078. if($section == 'dns_records') {
  1079. $parts = explode('|', $row);
  1080. $dns_rr[] = array(
  1081. 'name' => $parts[1],
  1082. 'type' => $parts[0],
  1083. 'data' => $parts[2],
  1084. 'aux' => $parts[3],
  1085. 'ttl' => $parts[4]
  1086. );
  1087. }
  1088. }
  1089. }
  1090. } // end foreach
  1091. // Insert the soa record
  1092. $sys_userid = $this->cli_id;//$cliente_id_seleccionado;//$fields['client_group_id'];
  1093. $origin = $vars['origin'];
  1094. $ns = $vars['ns'];
  1095. $mbox = str_replace('@', '.', $vars['mbox']);
  1096. $refresh = $vars['refresh'];
  1097. $retry = $vars['retry'];
  1098. $expire = $vars['expire'];
  1099. $minimum = $vars['minimum'];
  1100. $ttl = $vars['ttl'];
  1101. $xfer = $vars['xfer'];
  1102. $also_notify = $vars['also_notify'];
  1103. $update_acl = $vars['update_acl'];
  1104. $serial = $app->validate_dns->increase_serial(0);
  1105. $insert_data = array(
  1106. "sys_userid" => $this->sys_usuario_id,//$sysUsuarioId,//$fields['client_group_id'],
  1107. "sys_groupid" => $this->cli_grupo_id,//$cliente_groupid,//$client_group_id,
  1108. "sys_perm_user" => 'riud',
  1109. "sys_perm_group" => 'riud',
  1110. "sys_perm_other" => '',
  1111. "server_id" => $this->dns_serv,
  1112. "origin" => $origin,
  1113. "ns" => $ns,
  1114. "mbox" => $mbox,
  1115. "serial" => $serial,
  1116. "refresh" => $refresh,
  1117. "retry" => $retry,
  1118. "expire" => $expire,
  1119. "minimum" => $minimum,
  1120. "ttl" => $ttl,
  1121. "active" => 'Y',
  1122. "xfer" => $xfer,
  1123. "also_notify" => $also_notify,
  1124. "update_acl" => $update_acl,
  1125. "dnssec_wanted" => $enable_dnssec
  1126. );
  1127. $dns_soa_id = $app->db->datalogInsert('dns_soa', $insert_data, 'id');
  1128. $remote->dns_soa_after_insert($dns_soa_id, $this->cli_grupo_id);
  1129. // Insert the dns_rr records
  1130. if(is_array($dns_rr) && $dns_soa_id > 0) {
  1131. foreach($dns_rr as $rr) {
  1132. $insert_data = array(
  1133. "sys_userid" => $this->sys_usuario_id,//$sysUsuarioId, //$fields['client_group_id'],
  1134. "sys_groupid" => $this->cli_grupo_id,//$cliente_groupid, //$client_group_id,
  1135. "sys_perm_user" => 'riud',
  1136. "sys_perm_group" => 'riud',
  1137. "sys_perm_other" => '',
  1138. "server_id" => $this->dns_serv,
  1139. "zone" => $dns_soa_id,
  1140. "name" => $rr['name'],
  1141. "type" => $rr['type'],
  1142. "data" => $rr['data'],
  1143. "aux" => $rr['aux'],
  1144. "ttl" => $rr['ttl'],
  1145. "active" => 'Y'
  1146. );
  1147. $dns_rr_id = $app->db->datalogInsert('dns_rr', $insert_data, 'id');
  1148. $remote->dns_rr_after_insert($dns_rr_id, $this->cli_grupo_id);
  1149. }
  1150. }
  1151. //sites_web_domain_add
  1152. $tform_def_file = "../sites/form/web_vhost_domain.tform.php";
  1153. $app->tform->loadFormDef($tform_def_file);
  1154. //print_r($fields);
  1155. //echo('La sesión user id ' . $_SESSION['s']['user']['userid']);
  1156. // add site
  1157. $paramsite = array(
  1158. 'type' => 'vhost',
  1159. 'domain' => $fields['domain'],
  1160. 'server_id' => $this->web_serv,// $web_servidor, //$server_id,//$dns_servidor['default_webserver'],
  1161. //IMPORTANTE. Aquí­ no se ponen los campos sys_userid ni sys_groupid, el evento on_after_insert
  1162. //'sys_userid' => $sysUsuarioId, //$fields['client_group_id'],//$sys_userid,
  1163. //'sys_groupid' => $cliente_groupid,
  1164. 'ip_address' => '*', //$dns_ip_servidor['ip_address'],
  1165. 'ipv6_address' => $this->ip6_servidor_web['ip_address'], //$this->ip6_ultima['ip_address'], //$dns_ip_servidor_ipv6['ip_address'],
  1166. 'traffic_quota' => '-1',
  1167. 'hd_quota' => '0',
  1168. 'cgi' => 'y',
  1169. 'ssi' => 'y',
  1170. 'suexec' => 'y',
  1171. 'ruby' => 'n',
  1172. 'python' => 'n',
  1173. 'perl' => 'n',
  1174. 'errordocs' => '1',
  1175. 'subdomain' => 'www',
  1176. 'php' => 'php-fpm',
  1177. 'fastcgi_php_version' => '',
  1178. 'seo_redirect' => '',
  1179. 'rewrite_to_https' => 'n',
  1180. 'allow_override' => 'All',
  1181. 'http_port' => 80,
  1182. 'https_port' => 443,
  1183. 'apache_directives' => '',
  1184. 'nginx_directives' => '',
  1185. 'php_fpm_use_socket' => 'y',
  1186. 'pm' => 'ondemand',
  1187. 'pm_max_children' => 10,
  1188. 'pm_start_servers' => 1,
  1189. 'pm_min_spare_servers' => 1,
  1190. 'pm_max_spare_servers' => 5,
  1191. 'pm_process_idle_timeout' => 10,
  1192. 'pm_max_requests' => 0,
  1193. 'custom_php_ini' => '',
  1194. 'active' => 'y',
  1195. 'document_root' => '-',
  1196. 'system_user' => '-',
  1197. 'system_group' => '-',
  1198. 'log_retention' => 30,
  1199. 'client_group_id' => $this->cli_grupo_id,//$cliente_groupid, //$client_group_id,
  1200. );
  1201. //print 'Valores: ' . $dns_ip_servidor_ipv6 . " " . $formulario . " Parametros: " ;
  1202. //print "<pre>"; print_r($paramsite); print "</pre>\n";
  1203. /*print '<pre> cliente id ' . $fields['client_id'];
  1204. print "<pre>";print_r($fields);print "</pre>\n";*/
  1205. //print "<pre>Formulario ";print_r($formulario);print "</pre>\n";
  1206. //$this->crearBaseDatosFtp($remote);
  1207. //print 'DNS IPV6 ' . $dns_ip_servidor_ipv6['ip_address'];
  1208. //IMPORTANTE. El último parámetro es para lanzar un evento que llama a la función on_after_insert
  1209. //que prepara los campos document_root, system_user y system_group
  1210. //$site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php', $fields['client_group_id'], $paramsite, 'sites:web_vhost_domain:on_after_insert');
  1211. //IMPORTANTE. ESTE ES EL ÚNICO PLUGING QUE FUNCIONA.
  1212. $site_id = $remoto->insert_query('../sites/form/web_vhost_domain.tform.php',
  1213. $this->cli_id, /*$cliente_id_seleccionado,*/
  1214. $paramsite, 'sites:web_vhost_domain:on_after_insert');
  1215. //print 'Sitio id '. $site_id;
  1216. }
  1217. function onSubmit() {
  1218. global $app, $conf;
  1219. /*$sesionesLog = $_SESSION["s"]["user"]["typ"];
  1220. $sesionesLog2 = $_SESSION["s"]["user"];
  1221. $sesiones = $_SESSION;
  1222. $sesionId = $_SESSION["s"]["id"];*/
  1223. //print_r($sesiones);
  1224. //print('la ssessison es ' .$ssionId);
  1225. //print_r($sesionesLog2);
  1226. if($this->plantillaWebDNS()){
  1227. return;
  1228. }
  1229. //Carga de campos del formulario.
  1230. $fields = $app->tform->encode($this->dataRecord, $app->tform->getCurrentTab(), true);
  1231. //Creo la clase remote para usar las librerias
  1232. $remote = new remote_actions;
  1233. if($this->tieneServidorIPs()){
  1234. return;
  1235. }
  1236. if($this->servidoresActivados()){
  1237. return;
  1238. }
  1239. //------INICIO LIMITES--------------------------------------------------------------------------------------------------
  1240. $limitado = new limites($this->cli_grupo_id);
  1241. $tieneLimitesDNS = $limitado->limClienteDns();
  1242. $tieneLimitesWeb = $limitado->limClienteWebDominio();
  1243. $tieneLimitesDB = $limitado->limClienteDB();
  1244. if($tieneLimitesDNS || $tieneLimitesWeb || $tieneLimitesDB){
  1245. return;
  1246. }
  1247. //------FIN LIMITES-----------------------------------------------------------------------------------------------------
  1248. if($this->existeDominio($fields)){
  1249. return;
  1250. }
  1251. //Esta variable nos llega por jQuery desde el htm para el control de errores en la vista.
  1252. if($_POST['create'] != 1)
  1253. {
  1254. $app->tform->errorMessage = 'DUMMY';
  1255. $app->tpl->setVar($this->dataRecord);
  1256. $this->onShow();
  1257. return;
  1258. }
  1259. if($this->comprobarSubDominios($fields['domain'])){
  1260. $this->crearSubDominio($remote, $fields['domain']);
  1261. if(!$this->subdom_error){
  1262. $this->crearSitioWebSubdominio($remote);
  1263. $this->crearBaseDatosFtp($remote);
  1264. }
  1265. } else {
  1266. if(!$this->dominio_error){
  1267. $this->crearDnsSitioWeb($remote);
  1268. //Si todo va bien, el resultado de la web y dns
  1269. echo '<br><div class="alert alert-success"><br>
  1270. Altas Web y DNS del dominio <b>'.$fields['domain'].'</b>, ¡Creadas correctamente!
  1271. <br><br></div></br>';
  1272. //IMPORTANTE, es necesario cargar nuestro formulario para poder ejecutar la función que crea
  1273. //la base de datos y el ftp ya que hay datos que tomamos de el antes de ejecutarla.
  1274. $app->tform->loadFormDef('form/new_service_webdns.tform.php');
  1275. $this->crearBaseDatosFtp($remote);
  1276. }else{
  1277. $this->onError();
  1278. return;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. class remote_actions extends remoting {
  1284. public function insert_query($formdef_file, $client_id, $params, $event_identifier = '') {
  1285. global $app;
  1286. /*$sql = $this->insertQueryPrepare($formdef_file, $client_id, $params);
  1287. echo(' Query ' . $sql);
  1288. $app->uses('remoting_lib');
  1289. $app->remoting_lib->loadUserProfile();*/
  1290. //return $app->db->query($sql);//$this->insertQueryExecute($sql, $params, $event_identifier);
  1291. //echo(' insertQueryPrepare ' . $this->insertQueryExecute($sql, $params, $event_identifier));
  1292. return $this->insertQueryWebDNS($formdef_file, $client_id, $params, $event_identifier);
  1293. }
  1294. //------------------------------------------------------------------------------------------------------------
  1295. //IMPORTANTE. FUNCIONES EXTRAIDAS Y MODIFICADAS DE ISPCONFIG PARA SOLUCIONAR EL PROBLEMA DE AUTOLOGEO A ADMIN.
  1296. //------------------------------------------------------------------------------------------------------------
  1297. function insertQueryWebDNS($formdef_file, $client_id, $params, $event_identifier = '') {
  1298. //$sql = $app->remoting->insertQueryPrepare($formdef_file, $client_id, $params);
  1299. $sql = $this->insertQueryPrepareWebDNS($formdef_file, $client_id, $params);
  1300. if($sql !== false) return $this->insertQueryExecuteWebDNS($sql, $params, $event_identifier);
  1301. else return false;
  1302. }
  1303. function insertQueryPrepareWebDNS($formdef_file, $client_id, $params) {
  1304. global $app;
  1305. $app->uses('remoting_lib');
  1306. //* load the user profile of the client
  1307. //$app->remoting_lib->loadUserProfile($client_id);
  1308. //* Load the form definition
  1309. $app->remoting_lib->loadFormDef($formdef_file);
  1310. //echo(' Base de datos ' . $app->remoting_lib->loadFormDef($formdef_file));
  1311. //* Get the SQL query
  1312. $sql = $app->remoting_lib->getSQL($params, 'INSERT', 0);
  1313. /*if($app->remoting_lib->errorMessage != '') {
  1314. throw new SoapFault('data_processing_error', $app->remoting_lib->errorMessage);
  1315. return false;
  1316. }*/
  1317. $app->log('Executed insertQueryPrepareWebDNS', LOGLEVEL_DEBUG);
  1318. return $sql;
  1319. }
  1320. function insertQueryExecuteWebDNS($sql, $params, $event_identifier = '') {
  1321. global $app;
  1322. $app->uses('remoting_lib');
  1323. $app->db->query($sql);
  1324. /*if($app->db->errorMessage != '') {
  1325. throw new SoapFault('database_error', $app->db->errorMessage . ' '.$sql);
  1326. return false;
  1327. }*/
  1328. if ( isset($params['_primary_id'] ))
  1329. $insert_id = $params['_primary_id'];
  1330. else
  1331. $insert_id = $app->db->insertID();
  1332. // set a few values for compatibility with tform actions, mostly used by plugins
  1333. $this->id = $insert_id;
  1334. $this->dataRecord = $params;
  1335. $app->log('Executed insertQueryExecute, raising events now if any: ' . $event_identifier, LOGLEVEL_DEBUG);
  1336. if($event_identifier != '') $app->plugin->raiseEvent($event_identifier, $this);
  1337. //$app->uses('tform');
  1338. //* Save changes to Datalog
  1339. if($app->remoting_lib->formDef["db_history"] == 'yes') {
  1340. //$new_rec = $app->remoting_lib->getDataRecord($insert_id);
  1341. $new_rec = $this->getDataRecordWebDNS($insert_id);
  1342. $app->remoting_lib->datalogSave('INSERT', $primary_id, array(), $new_rec);
  1343. }
  1344. return $insert_id;
  1345. }
  1346. function sites_ftp_user_after_insert() {
  1347. global $app, $conf;
  1348. $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
  1349. //echo(' Valor FTP ' . $this->dataRecord["parent_domain_id"]);
  1350. $server_id = $app->functions->intval($web["server_id"]);
  1351. $dir = $web["document_root"];
  1352. $uid = $web["system_user"];
  1353. $gid = $web["system_group"];
  1354. // Check system user and group
  1355. if($app->functions->is_allowed_user($uid) == false || $app->functions->is_allowed_group($gid) == false) {
  1356. $app->error('Invalid system user or group');
  1357. }
  1358. // The FTP user shall be owned by the same group then the website
  1359. $sys_groupid = $app->functions->intval($web['sys_groupid']);
  1360. $sql = "UPDATE ftp_user SET server_id = ?, dir = ?, uid = ?, gid = ?, sys_groupid = ? WHERE ftp_user_id = ?";
  1361. $app->db->query($sql, $server_id, $dir, $uid, $gid, $sys_groupid, $this->id);
  1362. }
  1363. function dns_rr_after_insert($dns_rr_id, $cliente_grupo_id) {
  1364. global $app, $conf;
  1365. //echo(' el cliente grupo id ' . $cliente_grupo_id . ' el id tupla en dns_rr ' . $dns_rr_id);
  1366. if($_SESSION["s"]["user"]["typ"] == 'user') {
  1367. $app->db->datalogUpdate('dns_rr', array("sys_userid" => $cliente_grupo_id,
  1368. "sys_groupid" => $cliente_grupo_id), 'id', $dns_rr_id);
  1369. }
  1370. if($_SESSION["s"]["user"]["typ"] == 'admin') {
  1371. $app->db->datalogUpdate('dns_rr', array("sys_userid" => 1, //$cliente_grupo_id,
  1372. "sys_groupid" => $cliente_grupo_id), 'id', $dns_rr_id);
  1373. }
  1374. }
  1375. function dns_soa_after_insert($dns_soa_id, $cliente_grupo_id) {
  1376. global $app, $conf;
  1377. //echo(' el cliente grupo id ' . $cliente_grupo_id . ' el id tupla en dns_rr ' . $dns_soa_id . ' sys usuario ' . $sys_usuario_id);
  1378. if($_SESSION["s"]["user"]["typ"] == 'user') {
  1379. $app->db->datalogUpdate('dns_soa', array("sys_userid" => $cliente_grupo_id,
  1380. "sys_groupid" => $cliente_grupo_id), 'id', $dns_soa_id);
  1381. }
  1382. if($_SESSION["s"]["user"]["typ"] == 'admin') {
  1383. $app->db->datalogUpdate('dns_soa', array("sys_userid" => 1, //$cliente_grupo_id,
  1384. "sys_groupid" => $cliente_grupo_id), 'id', $dns_soa_id);
  1385. }
  1386. }
  1387. function dns_registro_tipo_a_after_insert($cli_grupo_id) {
  1388. global $app, $conf;
  1389. //echo(' el valor zone ' . $this->dataRecord["zone"]);
  1390. //* Set the sys_groupid of the rr record to be the same then the sys_groupid of the soa record
  1391. if($_SESSION["s"]["user"]["typ"] == 'user') {
  1392. $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
  1393. $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $soa['sys_groupid']), 'id', $this->id);
  1394. }
  1395. /*if($_SESSION["s"]["user"]["typ"] == 'admin') {
  1396. $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
  1397. $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $soa['sys_groupid']), 'id', $this->id);
  1398. }*/
  1399. if($app->auth->has_clients($_SESSION['s']['user']['userid'])) {
  1400. $soa = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ? AND " . $this->getAuthSQLWebDNS('r'), $this->dataRecord["zone"]);
  1401. $app->db->datalogUpdate('dns_rr', array("sys_groupid" => $cli_grupo_id), 'id', $this->id);
  1402. }
  1403. //* Update the serial number of the SOA record
  1404. /*$soa_id = $app->functions->intval($_POST["zone"]);
  1405. $serial = $app->validate_dns->increase_serial($soa["serial"]);
  1406. $app->db->datalogUpdate('dns_soa', array("serial" => $serial), 'id', $soa_id);*/
  1407. }
  1408. public function sites_database_user_after_add($client_id, $params){
  1409. global $app, $conf;
  1410. //echo('Plugeando');
  1411. // if($_SESSION["s"]["user"]["typ"] == 'user' /*&& isset($this->dataRecord["client_group_id"])*/) {
  1412. //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
  1413. $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
  1414. /* }
  1415. if($_SESSION["s"]["user"]["typ"] == 'admin'/* && isset($this->dataRecord["client_group_id"])*///) {
  1416. //echo('Plugeando ' .$app->functions->intval($this->dataRecord["client_group_id"]) . ' y ' . $client_id . ' id ' . $this->id);
  1417. //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
  1418. /* $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
  1419. }
  1420. if($app->auth->has_clients($_SESSION['s']['user']['userid'])/* && isset($this->dataRecord["client_group_id"])*///) {
  1421. //$client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
  1422. /* $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_id, $this->id);
  1423. }
  1424. $app->uses('sites_web_database_user_plugin');
  1425. global $app;
  1426. //Register for the events
  1427. $app->plugin->registerEvent('sites:web_database_user:on_after_update', 'sites_web_database_user_plugin', 'sites_web_database_user_edit');
  1428. $app->plugin->registerEvent('sites:web_database_user:on_after_insert', 'sites_web_database_user_plugin', 'sites_web_database_user_edit');
  1429. */
  1430. }
  1431. public function sites_database_user_add($session_id, $client_id, $params, $event_identifier = '') {
  1432. global $app;
  1433. /*if(!$this->checkPerm($session_id, 'sites_database_user_add')) {
  1434. throw new SoapFault('permission_denied', 'You do not have the permissions to access this function.');
  1435. return false;
  1436. }*/
  1437. //echo(' la tablita ' . $this->formDef['db_table']);
  1438. return $this->insertQueryWebDNS('../sites/form/database_user.tform.php', $client_id, $params, $event_identifier);
  1439. }
  1440. function getDataRecordWebDNS($primary_id) {
  1441. global $app;
  1442. $escape = '`';
  1443. //$this->loadUserProfile();
  1444. if(@is_numeric($primary_id)) {
  1445. if($primary_id > 0) {
  1446. // Return a single record
  1447. //return $this->getDataRecordPadreWebDNS($primary_id);
  1448. return $app->tform->getDataRecord($primary_id);
  1449. //return parent::getDataRecord($primary_id);
  1450. } elseif($primary_id == -1) {
  1451. // Return a array with all records
  1452. $sql = "SELECT * FROM ??";
  1453. return $app->db->queryAllRecords($sql, $this->formDef['db_table']);
  1454. } else {
  1455. throw new SoapFault('invalid_id', 'The ID has to be > 0 or -1.');
  1456. return array();
  1457. }
  1458. } elseif (@is_array($primary_id) || @is_object($primary_id)) {
  1459. 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!
  1460. $sql_offset = 0;
  1461. $sql_limit = 0;
  1462. $sql_where = '';
  1463. $params = array($this->formDef['db_table']);
  1464. foreach($primary_id as $key => $val) {
  1465. if($key == '#OFFSET#') $sql_offset = $app->functions->intval($val);
  1466. elseif($key == '#LIMIT#') $sql_limit = $app->functions->intval($val);
  1467. elseif(stristr($val, '%')) {
  1468. $sql_where .= "?? like ? AND ";
  1469. } else {
  1470. $sql_where .= "?? = ? AND ";
  1471. }
  1472. $params[] = $key;
  1473. $params[] = $val;
  1474. }
  1475. $sql_where = substr($sql_where, 0, -5);
  1476. if($sql_where == '') $sql_where = '1';
  1477. //$sql = "SELECT * FROM ?? WHERE ".$sql_where. " AND " . $this->getAuthSQLWebDNS('r', $this->formDef['db_table']);
  1478. $sql = "SELECT * FROM ?? WHERE ".$sql_where. " AND " . $this->getAuthSQL('r', $this->formDef['db_table']);
  1479. if($sql_offset >= 0 && $sql_limit > 0) $sql .= ' LIMIT ' . $sql_offset . ',' . $sql_limit;
  1480. return $app->db->queryAllRecords($sql, true, $params);
  1481. } else {
  1482. $this->errorMessage = 'The ID must be either an integer or an array.';
  1483. return array();
  1484. }
  1485. }
  1486. /*function getDataRecordPadreWebDNS($primary_id) {
  1487. global $app;
  1488. $escape = '`';
  1489. $sql = "SELECT * FROM ?? WHERE ?? = ? AND ".$this->getAuthSQLWebDNS('r', $this->formDef['db_table']);
  1490. return $app->db->queryOneRecord($sql, $this->formDef['db_table'], $this->formDef['db_table_idx'], $primary_id);
  1491. }*/
  1492. function getAuthSQLWebDNS($perm, $table = '') {
  1493. if($_SESSION["s"]["user"]["typ"] == 'admin' || $_SESSION['s']['user']['mailuser_id'] > 0) {
  1494. return '1';
  1495. } else {
  1496. if ($table != ''){
  1497. $table = ' ' . $table . '.';
  1498. }
  1499. $groups = ( $_SESSION["s"]["user"]["groups"] ) ? $_SESSION["s"]["user"]["groups"] : 0;
  1500. $sql = '(';
  1501. $sql .= "(" . $table . "sys_userid = ".$_SESSION["s"]["user"]["userid"]." AND " . $table . "sys_perm_user like '%$perm%') OR ";
  1502. $sql .= "(" . $table . "sys_groupid IN (".$groups.") AND " . $table ."sys_perm_group like '%$perm%') OR ";
  1503. $sql .= $table . "sys_perm_other like '%$perm%'";
  1504. $sql .= ')';
  1505. return $sql;
  1506. }
  1507. }
  1508. //----------------------------------------------------------------------------------
  1509. //IMPORTANTE. ESTA FUNCION ES COMO LO HACE ISPCONFIG NO EXTRAIDA PERO SI MODIFICADA.
  1510. //----------------------------------------------------------------------------------
  1511. public function sites_database_add($client_id, $params){
  1512. global $app, $conf;
  1513. //IMPORTANTE. PARA QUE EL PLUGING FUNCIONE HAY QUE CARGAR ANTES EL FORMULARIO
  1514. //DE LO QUE SE QUIERE CREAR EN ESTE CASO SITIO WEB
  1515. $tform_def_file = "../sites/form/database.tform.php";
  1516. $app->tform->loadFormDef($tform_def_file);
  1517. $app->remoting_lib->loadFormDef('../sites/form/database.tform.php');
  1518. //$app->tform->formDef('../sites/form/database.tform.php');
  1519. //$sql = $app->remoting->insertQueryPrepare('../sites/form/database.tform.php', $client_id, $params);
  1520. $sql = $this->insertQueryPrepareWebDNS('../sites/form/database.tform.php', $client_id, $params);
  1521. if($sql !== false) {
  1522. $app->uses('sites_database_plugin');
  1523. //print_r($sql);
  1524. $this->id = 0;
  1525. $this->dataRecord = $params;
  1526. //$app->uses('sites_database_plugin');
  1527. //$app->sites_database_plugin->processDatabaseInsert($this);
  1528. //$retval = $this->insertQueryExecute($sql, $params);
  1529. $retval = $this->insertQueryExecuteWebDNS($sql, $params);
  1530. $app->sites_database_plugin->processDatabaseInsert($this);
  1531. //$app->plugin->raiseEvent('sites:web_database:on_after_insert', $this);
  1532. // set correct values for backup_interval and backup_copies
  1533. /*if(isset($params['backup_interval']) || isset($params['backup_copies'])){
  1534. $sql_set = array();
  1535. if(isset($params['backup_interval'])) $sql_set[] = "backup_interval = '".$app->db->quote($params['backup_interval'])."'";
  1536. if(isset($params['backup_copies'])) $sql_set[] = "backup_copies = ".$app->functions->intval($params['backup_copies']);
  1537. //$app->db->query("UPDATE web_database SET ".implode(', ', $sql_set)." WHERE database_id = ".$retval);
  1538. $this->updateQueryExecute("UPDATE web_database SET ".implode(', ', $sql_set)." WHERE database_id = ".$retval, $retval, $params);
  1539. }*/
  1540. return $retval;
  1541. }
  1542. return false;
  1543. }
  1544. }
  1545. $page = new page_action;
  1546. $page->onLoad();
  1547. //IMPORTENTE, es necesario estas lí­neas para que el botón del pdf funcione. Activa el javascript
  1548. //echo '<script type="text/javascript">';
  1549. //echo '</script>';
  1550. ?>
  1551. <!--IMPORTENTE, es necesario estas lí­neas para que el botón del pdf funcione. Activa el javascript -->
  1552. <script type="text/javascript">
  1553. </script>