ISPConfig module for simplify the creation of websites and DNS zones in a only step
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

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