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

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