PageRenderTime 27ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/stable/web/install.php

http://facturascripts.googlecode.com/
PHP | 483 lines | 361 code | 69 blank | 53 comment | 56 complexity | 009b6688e3506553789e36013c9d0b7f MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /*
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program; if not, write to the Free Software
  15. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  16. *
  17. * Autor: Carlos Garcia Gomez
  18. */
  19. /// obtiene todos los datos del xml de la tabla
  20. function get_xml_tabla($tabla, &$columnas, &$restricciones, &$indices)
  21. {
  22. $retorno = true;
  23. $xml = simplexml_load_file('admin/tablas/' . $tabla . '.xml');
  24. if($xml)
  25. {
  26. if($xml->columna)
  27. {
  28. $i = 0;
  29. foreach($xml->columna as $col)
  30. {
  31. $columnas[$i]['nombre'] = $col->nombre;
  32. $columnas[$i]['tipo'] = $col->tipo;
  33. $columnas[$i]['nulo'] = $col->nulo;
  34. $columnas[$i]['defecto'] = $col->defecto;
  35. $i++;
  36. }
  37. }
  38. else /// debe de haber columnas, sino es un fallo
  39. {
  40. $retorno = false;
  41. }
  42. if($xml->restriccion)
  43. {
  44. $i = 0;
  45. foreach($xml->restriccion as $col)
  46. {
  47. $restricciones[$i]['nombre'] = $col->nombre;
  48. $restricciones[$i]['consulta'] = $col->consulta;
  49. $i++;
  50. }
  51. }
  52. }
  53. else
  54. {
  55. $retorno = false;
  56. }
  57. return($retorno);
  58. }
  59. /*
  60. * Compara las columnas de una tabla data, devuelve una sentencia sql
  61. * en caso de encontrar diferencias.
  62. */
  63. function compara_columna($tabla, $col, $columnas)
  64. {
  65. $consulta = "";
  66. $encontrada = false;
  67. if($columnas)
  68. {
  69. foreach($columnas as $col2)
  70. {
  71. if($col2['column_name'] == $col['nombre'])
  72. {
  73. $encontrada = true;
  74. if($col['defecto'] == "")
  75. {
  76. $col['defecto'] = NULL;
  77. }
  78. if($col2['column_default'] != $col['defecto'])
  79. {
  80. if($col['defecto'] != NULL)
  81. {
  82. $consulta .= "ALTER TABLE " . $tabla . " ALTER COLUMN " . $col['nombre'] . " SET DEFAULT " . $col['defecto'] . ";\n";
  83. }
  84. }
  85. if(($col2['is_nullable'] == "YES" AND $col['nulo'] == "NO") OR $col2['is_nullable'] == "NO" AND $col['nulo'] == "SI")
  86. {
  87. if($col['nulo'] == "SI")
  88. {
  89. $consulta .= "ALTER TABLE " . $tabla . " ALTER COLUMN " . $col['nombre'] . " DROP NOT NULL;\n";
  90. }
  91. else
  92. {
  93. $consulta .= "ALTER TABLE " . $tabla . " ALTER COLUMN " . $col['nombre'] . " SET NOT NULL;\n";
  94. }
  95. }
  96. }
  97. }
  98. }
  99. /// si no se ha encontrado
  100. if(!$encontrada)
  101. {
  102. $consulta .= "ALTER TABLE " . $tabla . " ADD COLUMN " . $col['nombre'] . " " . $col['tipo'];
  103. if($col['defecto'] != "")
  104. {
  105. $consulta .= " DEFAULT " . $col['defecto'];
  106. }
  107. if($col['nulo'] == "NO")
  108. {
  109. $consulta .= " NOT NULL";
  110. }
  111. $consulta .= ";\n";
  112. }
  113. return($consulta);
  114. }
  115. /*
  116. * Compara dos arrays de restricciones, devuelve una sentencia sql
  117. * en caso de encontrar diferencias.
  118. */
  119. function compara_constraints($tabla, $c_nuevas, $c_old)
  120. {
  121. $consulta = "";
  122. if($c_old)
  123. {
  124. if($c_nuevas)
  125. {
  126. /// comprobamos una a una las viejas
  127. foreach($c_old as $col)
  128. {
  129. $encontrado = false;
  130. foreach($c_nuevas as $col2)
  131. {
  132. if($col['restriccion'] == $col2['nombre'])
  133. {
  134. $encontrado = true;
  135. }
  136. }
  137. if(!$encontrado)
  138. {
  139. /// eliminamos la restriccion
  140. $consulta .= "ALTER TABLE " . $tabla . " DROP CONSTRAINT " . $col['restriccion'] . ";\n";
  141. }
  142. }
  143. /// comprobamos una a una las nuevas
  144. foreach($c_nuevas as $col)
  145. {
  146. $encontrado = false;
  147. foreach($c_old as $col2)
  148. {
  149. if($col['nombre'] == $col2['restriccion'])
  150. {
  151. $encontrado = true;
  152. }
  153. }
  154. if(!$encontrado)
  155. {
  156. /// ańadimos la restriccion
  157. $consulta .= "ALTER TABLE " . $tabla . " ADD CONSTRAINT " . $col['consulta'] . ";\n";
  158. }
  159. }
  160. }
  161. else
  162. {
  163. /// eliminamos todas las restricciones
  164. foreach($c_old as $col)
  165. {
  166. $consulta .= "ALTER TABLE " . $tabla . " DROP CONSTRAINT " . $col['restriccion'] . ";\n";
  167. }
  168. }
  169. }
  170. else
  171. {
  172. if($c_nuevas)
  173. {
  174. /// ańadimos todas las restricciones nuevas
  175. foreach($c_nuevas as $col)
  176. {
  177. $consulta .= "ALTER TABLE " . $tabla . " ADD CONSTRAINT " . $col['consulta'] . ";\n";
  178. }
  179. }
  180. }
  181. return($consulta);
  182. }
  183. /// devuelve la sentencia sql necesaria para crear una tabla con la estructura proporcionada
  184. function genera_tabla($tabla, $xml_columnas, $xml_restricciones, $xml_indices)
  185. {
  186. $consulta = "CREATE TABLE " . $tabla . " (\n";
  187. foreach($xml_columnas as $col)
  188. {
  189. /// ańade la coma al final
  190. if($i)
  191. {
  192. $consulta .= ",\n";
  193. }
  194. else
  195. {
  196. $i = true;
  197. }
  198. $consulta .= $col['nombre'] . " " . $col['tipo'];
  199. if($col['nulo'] == 'NO')
  200. {
  201. $consulta .= " NOT NULL";
  202. }
  203. if($col['defecto'] != "")
  204. {
  205. $consulta .= " DEFAULT " . $col['defecto'];
  206. }
  207. }
  208. $consulta .= " );\n";
  209. /// ańadimos las restricciones
  210. $consulta .= compara_constraints($tabla, $xml_restricciones, false);
  211. return($consulta);
  212. }
  213. /// comprueba y actualiza la estructura de la tabla si es necesario
  214. function check_tabla(&$bd, $tabla, &$error)
  215. {
  216. $retorno = true;
  217. $error = "";
  218. $consulta = "";
  219. $columnas = false;
  220. $restricciones = false;
  221. $indices = false;
  222. $xml_columnas = false;
  223. $xml_restricciones = false;
  224. $xml_indices = false;
  225. $i = false;
  226. if( get_xml_tabla($tabla, $xml_columnas, $xml_restricciones, $xml_indices) )
  227. {
  228. if( $bd->existe_tabla($tabla) )
  229. {
  230. $columnas = get_columnas($bd, $tabla);
  231. $restricciones = get_constraints($bd, $tabla);
  232. /// comparamos las columnas
  233. foreach($xml_columnas as $col)
  234. {
  235. $consulta .= compara_columna($tabla, $col, $columnas);
  236. }
  237. /// comparamos las restricciones
  238. $consulta .= compara_constraints($tabla, $xml_restricciones, $restricciones);
  239. /*
  240. * TODO comparar los indices
  241. */
  242. }
  243. else
  244. {
  245. /// generamos el sql para crear la tabla
  246. $consulta .= genera_tabla($tabla, $xml_columnas, $xml_restricciones, $xml_indices);
  247. }
  248. if($consulta != "")
  249. {
  250. if( !$bd->exec($consulta) )
  251. {
  252. $error = "Error";
  253. echo "<div class='error'>" . $consulta . "</div>";
  254. }
  255. }
  256. }
  257. else
  258. {
  259. $error = "Error con el xml";
  260. $retorno = false;
  261. }
  262. return($retorno);
  263. }
  264. /// devuelve un array con las columnas de una tabla dada
  265. function get_columnas(&$bd, $tabla)
  266. {
  267. $columnas = false;
  268. if($tabla)
  269. {
  270. $consulta = "SELECT column_name, column_default, is_nullable
  271. FROM information_schema.columns
  272. WHERE table_catalog = '" . FS_DB_NAME . "' AND table_name = '$tabla';";
  273. $columnas = $bd->select($consulta);
  274. }
  275. return($columnas);
  276. }
  277. /// devuelve una array con las restricciones de una tabla dada
  278. function get_constraints(&$bd, $tabla)
  279. {
  280. $constraints = false;
  281. if($tabla)
  282. {
  283. $consulta = "select c.conname as \"restriccion\"
  284. from pg_class r, pg_constraint c
  285. where r.oid = c.conrelid
  286. and relname = '$tabla';";
  287. $constraints = $bd->select($consulta);
  288. }
  289. return($constraints);
  290. }
  291. if( !(file_exists('config.php')) )
  292. {
  293. echo "<?xml version=\"1.0\"?>\n",
  294. "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n",
  295. "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"es\">\n",
  296. "<head>\n<title>facturaScripts</title>\n<meta name='robots' content='noindex,nofollow'/>\n",
  297. "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>\n",
  298. "<link rel='stylesheet' type='text/css' media='screen' href='css/google.css'/>\n",
  299. "<script type='text/javascript' src='js/funciones.js'> </script>\n",
  300. "</head>\n<body>\n",
  301. "<div class='pie'>Debes crear el archivo de configuraci&oacute;n '<b>config.php</b>' a partir del archivo de ejemplo '<b>config-sample.php</b>'.<br/>\n",
  302. "Una vez lo tengas, crea la base de datos y <a href='install.php'>comienza la instalaci&oacute;n</a> de facturaSCRIPTS.</div>";
  303. }
  304. else
  305. {
  306. require('config.php');
  307. require('clases/db/postgresql.php');
  308. echo "<?xml version=\"1.0\"?>\n",
  309. "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n",
  310. "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"es\">\n",
  311. "<head>\n<title>FacturaSCRIPTS</title>\n<meta name='robots' content='noindex,nofollow'/>\n",
  312. "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>\n",
  313. "<link rel='stylesheet' type='text/css' media='screen' href='css/google.css'/>\n",
  314. "<script type='text/javascript' src='js/funciones.js'> </script>\n",
  315. "</head>\n<body>\n";
  316. $bd = new db();
  317. /// conectamos a la base de datos
  318. if( $bd->conectar() )
  319. {
  320. $instalacion = false;
  321. $error = false;
  322. echo "<div class='cuerpo'>\n",
  323. "<div class='destacado'>Instalador de facturaScripts:</div>\n";
  324. /*
  325. * Comprobamos si existe la tabla usuarios de facturaScripts,
  326. * si no ya sabemos que hay que crear un nuevo usuario.
  327. */
  328. if( !$bd->existe_tabla('fs_usuarios') )
  329. {
  330. $instalacion = true;
  331. }
  332. /// comprobamos la tablas tablas necesarias de facturascripts
  333. check_tabla($bd, 'fs_modulos', $error);
  334. if(!$error)
  335. {
  336. check_tabla($bd, 'fs_menu', $error);
  337. if(!$error)
  338. {
  339. check_tabla($bd, 'fs_usuarios', $error);
  340. if(!$error)
  341. {
  342. check_tabla($bd, 'fs_ack', $error);
  343. if(!$error)
  344. {
  345. check_tabla($bd, 'fs_opciones', $error);
  346. }
  347. else
  348. {
  349. echo '<div class="error">' , $error , '</div>';
  350. }
  351. }
  352. else
  353. {
  354. echo '<div class="error">' , $error , '</div>';
  355. }
  356. }
  357. else
  358. {
  359. echo '<div class="error">' , $error , '</div>';
  360. }
  361. }
  362. else
  363. {
  364. echo '<div class="error">' , $error , '</div>';
  365. }
  366. unset($bd);
  367. if($instalacion)
  368. {
  369. /// actualizamos los modulos sys y admin
  370. require_once('admin/modulo.php');
  371. $nuevo_modulo = new modulo_();
  372. $nuevo_modulo->actualizar();
  373. $bd = new db();
  374. if($bd->conectar())
  375. {
  376. /// insertamon el usuario admin
  377. $password = sha1('admin');
  378. $consulta = "INSERT INTO fs_usuarios (usuario,pass) VALUES ('admin','$password');";
  379. $consulta .= "INSERT INTO fs_ack (usuario,modulo) VALUES ('admin','admin');";
  380. if( $bd->exec($consulta) )
  381. {
  382. echo "<div class='mensaje'>Usuario creado correctamente</div>";
  383. }
  384. else
  385. {
  386. echo "<div class='error'>Error al crear el usuario admin</div>";
  387. }
  388. echo "<br/><br/>
  389. <div class='centrado'>
  390. <h1>Ą facturaScripts instalado satisfactoriamente !</h1> Ya puedes comenzar a usarlo.<br/>
  391. No te olvides de instalar los m&oacute;dulos y actualizar la base de datos.<br/><br/>
  392. <b>Usuario:</b> admin<br/><b>Contraseńa:</b> admin<br/>
  393. <br/><a href='index.php'>Entrar</a>";
  394. }
  395. else
  396. {
  397. echo "<div class='error'>Error al conectar a la base de datos</div>";
  398. }
  399. echo "</div>";
  400. }
  401. else
  402. {
  403. echo "<br/><br/>";
  404. echo "<div class='centrado'><a href='index.php'>Entrar</a></div>";
  405. }
  406. echo "</div>\n";
  407. }
  408. else
  409. {
  410. echo "<div class='copyright'>Error al conectar a la base de datos</div>\n";
  411. }
  412. }
  413. echo "</body></html>";
  414. ?>