sql_db_conversion.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. /*
  3. FusionPBX
  4. Version: MPL 1.1
  5. The contents of this file are subject to the Mozilla Public License Version
  6. 1.1 (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.mozilla.org/MPL/
  9. Software distributed under the License is distributed on an "AS IS" basis,
  10. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. for the specific language governing rights and limitations under the
  12. License.
  13. The Original Code is FusionPBX
  14. The Initial Developer of the Original Code is
  15. Mark J Crane <[email protected]>
  16. Portions created by the Initial Developer are Copyright (C) 2008-2012
  17. the Initial Developer. All Rights Reserved.
  18. Contributor(s):
  19. Mark J Crane <[email protected]>
  20. */
  21. //set the include path
  22. $conf = glob("{/usr/local/etc,/etc}/fusionpbx/config.conf", GLOB_BRACE);
  23. set_include_path(parse_ini_file($conf[0])['document.root']);
  24. //includes files
  25. require_once "resources/require.php";
  26. require_once "resources/check_auth.php";
  27. //check permissions
  28. if (permission_exists('sql_query_backup')) {
  29. //access granted
  30. }
  31. else {
  32. echo "access denied";
  33. exit;
  34. }
  35. //add multi-lingual support
  36. $language = new text;
  37. $text = $language->get();
  38. //show errors
  39. ini_set('display_errors', '1');
  40. //error_reporting (E_ALL); // Report everything
  41. error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ); //hide notices and warnings
  42. //define the db file exists function
  43. function db_field_exists ($tmp_array, $column) {
  44. $result = false;
  45. foreach ($tmp_array as &$row) {
  46. if ($row[0] == $column) {
  47. $result = true;
  48. }
  49. return $result;
  50. }
  51. }
  52. //db_field_exists ($result_dest, $column)
  53. //destination info
  54. //set the domain_uuid
  55. $dest_domain_uuid = '1';
  56. //set the database type
  57. $db_dest_type = 'mysql'; //sqlite, mysql, pgsql, others with a manually created PDO connection
  58. //sqlite: the dbfilename and db_file_path are automatically assigned however the values can be overidden by setting the values here.
  59. //$dbfilename = 'fusionpbx.db'; //host name/ip address + '.db' is the default database filename
  60. //$db_file_path = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/secure'; //the path is determined by a php variable
  61. //mysql: database connection information
  62. $db_host = '127.0.0.1'; //set the host only if the database is not local
  63. $db_port = '3306';
  64. $db_name = 'fusionpbx';
  65. $db_username = 'fusionpbx';
  66. $db_password = '';
  67. $db_create_username = 'root';
  68. $db_create_password = '';
  69. //pgsql: database connection information
  70. //$db_host = ''; //set the host only if the database is not local
  71. //$db_port = '';
  72. //$db_name = '';
  73. //$db_username = '';
  74. //$db_password = '';
  75. //$db_create_username = '';
  76. //$db_create_password = '';
  77. //load data into the database
  78. //create the sqlite database
  79. if ($db_dest_type == "sqlite") {
  80. //sqlite database will be created when the config.php is loaded and only if the database file does not exist
  81. $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/sqlite.sql';
  82. $file_contents = file_get_contents($filename);
  83. unset($filename);
  84. try {
  85. $db_dest = new PDO('sqlite:'.$db_filepath.'/'.$db_filename); //sqlite 3
  86. //$db_dest = new PDO('sqlite::memory:'); //sqlite 3
  87. $db_dest->beginTransaction();
  88. }
  89. catch (PDOException $error) {
  90. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  91. die();
  92. }
  93. //replace \r\n with \n then explode on \n
  94. $file_contents = str_replace("\r\n", "\n", $file_contents);
  95. //loop line by line through all the lines of sql code
  96. $stringarray = explode("\n", $file_contents);
  97. $x = 0;
  98. foreach($stringarray as $sql) {
  99. try {
  100. if(stristr($sql, 'CREATE TABLE') === FALSE) {
  101. //not found do not execute
  102. }
  103. else {
  104. //execute create table sql strings
  105. $db_dest->query($sql);
  106. }
  107. }
  108. catch (PDOException $error) {
  109. echo $text['label-error'].": " . $error->getMessage() . " sql: $sql<br/>";
  110. }
  111. $x++;
  112. }
  113. unset ($file_contents, $sql);
  114. $db_dest->commit();
  115. }
  116. //create the postgres database
  117. if ($db_dest_type == "pgsql") {
  118. $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/pgsql.sql';
  119. $file_contents = file_get_contents($filename);
  120. //if $db_create_username provided, attempt to create new PG role and database
  121. if (strlen($db_create_username) > 0) {
  122. //create the database connection
  123. try {
  124. if (strlen($db_port) == 0) { $db_port = "5432"; }
  125. if (strlen($db_host) > 0) {
  126. $db_dest = new PDO("pgsql:host={$db_host} port={$db_port} user={$db_create_username} password={$db_create_password} dbname=template1");
  127. } else {
  128. $db_dest = new PDO("pgsql:host=localhost port={$db_port} user={$db_create_username} password={$db_create_password} dbname=template1");
  129. }
  130. } catch (PDOException $error) {
  131. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  132. die();
  133. }
  134. //create the database, user, grant perms
  135. $db_dest->exec("CREATE DATABASE {$db_name}");
  136. $db_dest->exec("CREATE USER {$db_username} WITH PASSWORD '{$db_password}'");
  137. $db_dest->exec("GRANT ALL ON {$db_name} TO {$db_username}");
  138. //close database connection_aborted
  139. $db_dest = null;
  140. }
  141. //open database connection with $db_name
  142. try {
  143. if (strlen($db_port) == 0) { $db_port = "5432"; }
  144. if (strlen($db_host) > 0) {
  145. $db_dest = new PDO("pgsql:host={$db_host} port={$db_port} dbname={$db_name} user={$db_username} password={$db_password}");
  146. } else {
  147. $db_dest = new PDO("pgsql:host=localhost port={$db_port} user={$db_username} password={$db_password} dbname={$db_name}");
  148. }
  149. }
  150. catch (PDOException $error) {
  151. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  152. die();
  153. }
  154. //replace \r\n with \n then explode on \n
  155. $file_contents = str_replace("\r\n", "\n", $file_contents);
  156. //loop line by line through all the lines of sql code
  157. $stringarray = explode("\n", $file_contents);
  158. $x = 0;
  159. foreach($stringarray as $sql) {
  160. if (strlen($sql) > 3) {
  161. try {
  162. if(stristr($sql, 'CREATE TABLE') === FALSE) {
  163. //not found do not execute
  164. }
  165. else {
  166. //execute create table sql strings
  167. $db_dest->query($sql);
  168. }
  169. }
  170. catch (PDOException $error) {
  171. echo $text['label-error'].": " . $error->getMessage() . " sql: $sql<br/>";
  172. die();
  173. }
  174. }
  175. $x++;
  176. }
  177. unset ($file_contents, $sql);
  178. }
  179. //create the mysql database
  180. if ($db_dest_type == "mysql") {
  181. $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/mysql.sql';
  182. $file_contents = file_get_contents($filename);
  183. //database connection
  184. try {
  185. if (strlen($db_host) == 0 && strlen($db_port) == 0) {
  186. //if both host and port are empty use the unix socket
  187. if (strlen($db_create_username) == 0) {
  188. $db_dest = new PDO("mysql:host=$db_host;unix_socket=/var/run/mysqld/mysqld.sock;charset=utf8;", $db_username, $db_password);
  189. }
  190. else {
  191. $db_dest = new PDO("mysql:host=$db_host;unix_socket=/var/run/mysqld/mysqld.sock;charset=utf8;", $db_create_username, $db_create_password); }
  192. }
  193. else {
  194. if (strlen($db_port) == 0) {
  195. //leave out port if it is empty
  196. if (strlen($db_create_username) == 0) {
  197. $db_dest = new PDO("mysql:host=$db_host;charset=utf8;", $db_username, $db_password);
  198. }
  199. else {
  200. $db_dest = new PDO("mysql:host=$db_host;charset=utf8;", $db_create_username, $db_create_password);
  201. }
  202. }
  203. else {
  204. if (strlen($db_create_username) == 0) {
  205. $db_dest = new PDO("mysql:host=$db_host;port=$db_port;charset=utf8;", $db_username, $db_password);
  206. }
  207. else {
  208. $db_dest = new PDO("mysql:host=$db_host;port=$db_port;charset=utf8;", $db_create_username, $db_create_password);
  209. }
  210. }
  211. }
  212. $db_dest->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  213. $db_dest->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
  214. }
  215. catch (PDOException $error) {
  216. if ($v_debug) {
  217. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  218. }
  219. }
  220. //create the table, user and set the permissions only if the db_create_username was provided
  221. if (strlen($db_create_username) > 0) {
  222. //select the mysql database
  223. try {
  224. $db_dest->query("USE mysql;");
  225. }
  226. catch (PDOException $error) {
  227. if ($v_debug) {
  228. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  229. }
  230. }
  231. //create user and set the permissions
  232. try {
  233. $tmp_sql = "CREATE USER '".$db_username."'@'%' IDENTIFIED BY '".$db_password."'; ";
  234. $db_dest->query($tmp_sql);
  235. }
  236. catch (PDOException $error) {
  237. if ($v_debug) {
  238. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  239. }
  240. }
  241. //set account to unlimitted use
  242. try {
  243. $tmp_sql = "GRANT USAGE ON * . * TO '".$db_username."'@'localhost' ";
  244. $tmp_sql .= "IDENTIFIED BY '".$db_password."' ";
  245. $tmp_sql .= "WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; ";
  246. $db_dest->query($tmp_sql);
  247. }
  248. catch (PDOException $error) {
  249. if ($v_debug) {
  250. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  251. }
  252. }
  253. //create the database and set the create user with permissions
  254. try {
  255. $tmp_sql = "CREATE DATABASE IF NOT EXISTS ".$db_name."; ";
  256. $db_dest->query($tmp_sql);
  257. }
  258. catch (PDOException $error) {
  259. if ($v_debug) {
  260. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  261. }
  262. }
  263. //set user permissions
  264. try {
  265. $db_dest->query("GRANT ALL PRIVILEGES ON ".$db_name.".* TO '".$db_username."'@'%'; ");
  266. }
  267. catch (PDOException $error) {
  268. if ($v_debug) {
  269. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  270. }
  271. }
  272. //make the changes active
  273. try {
  274. $tmp_sql = "FLUSH PRIVILEGES; ";
  275. $db_dest->query($tmp_sql);
  276. }
  277. catch (PDOException $error) {
  278. if ($v_debug) {
  279. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  280. }
  281. }
  282. } //if (strlen($db_create_username) > 0)
  283. //select the database
  284. try {
  285. $db_dest->query("USE ".$db_name.";");
  286. }
  287. catch (PDOException $error) {
  288. if ($v_debug) {
  289. print $text['label-error'].": " . $error->getMessage() . "<br/>";
  290. }
  291. }
  292. //add the defaults data into the database
  293. //replace \r\n with \n then explode on \n
  294. $file_contents = str_replace("\r\n", "\n", $file_contents);
  295. //loop line by line through all the lines of sql code
  296. $stringarray = explode("\n", $file_contents);
  297. $x = 0;
  298. foreach($stringarray as $sql) {
  299. if (strlen($sql) > 3) {
  300. try {
  301. if(stristr($sql, 'CREATE TABLE') === FALSE) {
  302. //not found do not execute
  303. }
  304. else {
  305. //execute create table sql strings
  306. $db_dest->query($sql);
  307. }
  308. }
  309. catch (PDOException $error) {
  310. //echo "error on line $x: " . $error->getMessage() . " sql: $sql<br/>";
  311. //die();
  312. }
  313. }
  314. $x++;
  315. }
  316. unset ($file_contents, $sql);
  317. }
  318. //get the list of tables
  319. if ($db_dest_type == "sqlite") {
  320. $sql = "SELECT name FROM sqlite_master ";
  321. $sql .= "WHERE type='table' ";
  322. $sql .= "order by name;";
  323. }
  324. if ($db_dest_type == "pgsql") {
  325. $sql = "select table_name as name ";
  326. $sql .= "from information_schema.tables ";
  327. $sql .= "where table_schema='public' ";
  328. $sql .= "and table_type='BASE TABLE' ";
  329. $sql .= "order by table_name ";
  330. }
  331. if ($db_dest_type == "mysql") {
  332. $sql = "show tables";
  333. }
  334. //get the default schema structure
  335. $prep_statement = $db_dest->prepare(check_sql($sql));
  336. $prep_statement->execute();
  337. $result_dest = $prep_statement->fetchAll(PDO::FETCH_NAMED);
  338. //clean the content from the table
  339. foreach ($result_dest as &$row) {
  340. $table_name = $row[0];
  341. $sql = 'delete from '.$table_name;
  342. //$db_dest->query($sql);
  343. }
  344. //add data into each table
  345. foreach ($result_dest as &$row) {
  346. //get the table name
  347. $table_name = $row[0];
  348. //$table_name = 'v_extensions';
  349. //$db_dest_type = "sqlite";
  350. //get the table source data
  351. $destination_column_array='';
  352. unset($destination_column_array);
  353. if ($db_dest_type == "sqlite") {
  354. $tmp_sql = "PRAGMA table_info($table_name);";
  355. }
  356. if ($db_dest_type == "pgsql") {
  357. }
  358. if ($db_dest_type == "mysql") {
  359. $tmp_sql = "show columns from $table_name;";
  360. }
  361. if (strlen($tmp_sql) > 0) {
  362. $prep_statement_2 = $db_dest->prepare(check_sql($tmp_sql));
  363. //$prep_statement_2 = $db->prepare(check_sql($tmp_sql));
  364. if ($prep_statement_2) {
  365. $prep_statement_2->execute();
  366. $result2 = $prep_statement_2->fetchAll(PDO::FETCH_ASSOC);
  367. }
  368. else {
  369. echo "<b>".$text['label-error'].":</b>\n";
  370. echo "<pre>\n";
  371. print_r($db_dest->errorInfo());
  372. echo "</pre>\n";
  373. }
  374. $x = 0;
  375. foreach ($result2 as $row2) {
  376. if ($db_dest_type == "sqlite") {
  377. $destination_column_array[$x] = $row2['name'];
  378. }
  379. if ($db_dest_type == "mysql") {
  380. $destination_column_array[$x] = $row2['Field'];
  381. }
  382. if ($db_dest_type == "pgsql") {
  383. }
  384. $x++;
  385. }
  386. /*
  387. $x = 0;
  388. foreach ($result2[0] as $key => $value) {
  389. if ($db_dest_type == "sqlite" && $key == "name") {
  390. $destination_column_array[$x] = $key;
  391. }
  392. $x++;
  393. }
  394. */
  395. $destination_column_array_count = count($destination_column_array);
  396. }
  397. unset($prep_statement_2, $result2);
  398. //echo "<pre>\n";
  399. //print_r($destination_column_array);
  400. //echo "</pre>\n";
  401. //get the table source data
  402. $tmp_sql = "select * from $table_name";
  403. if (strlen($tmp_sql) > 0) {
  404. $prep_statement_2 = $db->prepare(check_sql($tmp_sql));
  405. if ($prep_statement_2) {
  406. $prep_statement_2->execute();
  407. $result2 = $prep_statement_2->fetchAll(PDO::FETCH_ASSOC);
  408. }
  409. else {
  410. echo "<b>".$text['label-error'].":</b>\n";
  411. echo "<pre>\n";
  412. print_r($db->errorInfo());
  413. echo "</pre>\n";
  414. }
  415. $x = 0;
  416. foreach ($result2[0] as $key => $value) {
  417. $column_array[$x] = $key;
  418. $x++;
  419. }
  420. foreach ($result2 as &$row) {
  421. //build the sql query string
  422. if (substr($table_name, 0, 2) == 'v_') {
  423. $sql = "INSERT INTO $table_name (";
  424. $x = 1;
  425. foreach ($destination_column_array as $column) {
  426. if ($x < $destination_column_array_count) {
  427. $sql .= "".$column.", ";
  428. }
  429. else {
  430. $sql .= "".$column."";
  431. }
  432. $x++;
  433. }
  434. $sql .= ") ";
  435. $sql .= "VALUES( ";
  436. $x = 1;
  437. foreach ($destination_column_array as $column) {
  438. if ($x < $destination_column_array_count) {
  439. //if ($column == "domain_uuid") {
  440. // $sql .= "'".$dest_domain_uuid."',";
  441. //}
  442. //else {
  443. $sql .= "'".check_str($row[$column])."', ";
  444. //}
  445. }
  446. else {
  447. //if ($column == "domain_uuid") {
  448. // $sql .= "'".$dest_domain_uuid."'";
  449. //}
  450. //else {
  451. $sql .= "'".check_str($row[$column])."'";
  452. //}
  453. }
  454. $x++;
  455. }
  456. $sql .= ");\n";
  457. }
  458. //add the sql into the destination database
  459. echo $sql."<br />\n";
  460. $db_dest->query($sql);
  461. }
  462. }
  463. }
  464. ?>