ISPConfig module for simplify the creation of websites and DNS zones in a only step
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

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