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

1853 строки
75 KiB

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