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

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