sql_db_conversion.php 15 KB

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