2 /**********************************************************************
3 Copyright (C) FrontAccounting, LLC.
4 Released under the terms of the GNU General Public License,
5 GPL, as published by the Free Software Foundation, either version
6 3 of the License, or (at your option) any later version.
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
13 function write_config_db($new = false)
15 global $path_to_root, $def_coy, $db_connections, $tb_pref_counter;
16 include_once($path_to_root . "/config_db.php");
20 $n = count($db_connections);
22 $msg .= "/*Connection Information for the database\n";
23 $msg .= "- \$def_coy is the default company that is pre-selected on login\n\n";
24 $msg .= "- host is the computer ip address or name where the database is the default is localhost assuming that the web server is also the sql server\n\n";
25 $msg .= "- user is the user name under which the database should be accessed - need to change to the mysql (or other DB) user set up for purpose\n";
26 $msg .= " NB it is not secure to use root as the user with no password - a user with appropriate privileges must be set up\n\n";
27 $msg .= "- password is the password the user of the database requires to be sent to authorise the above database user\n\n";
28 $msg .= "- DatabaseName is the name of the database as defined in the RDMS being used. Typically RDMS allow many databases to be maintained under the same server.\n";
29 $msg .= " The scripts for MySQL provided use the name logicworks */\n\n\n";
31 $msg .= "\$def_coy = " . $def_coy . ";\n\n";
32 $msg .= "\$tb_pref_counter = " . $tb_pref_counter . ";\n\n";
33 $msg .= "\$db_connections = array (\n";
35 for ($i = 0; $i < $n; $i++)
41 $msg .= "('name' => '" . $db_connections[$i]['name'] . "',\n";
42 $msg .= "\t\t'host' => '" . $db_connections[$i]['host'] . "',\n";
43 $msg .= "\t\t'dbuser' => '" . $db_connections[$i]['dbuser'] . "',\n";
44 $msg .= "\t\t'dbpassword' => '" . $db_connections[$i]['dbpassword'] . "',\n";
45 $msg .= "\t\t'dbname' => '" . $db_connections[$i]['dbname'] . "',\n";
46 $msg .= "\t\t'tbpref' => '" . $db_connections[$i]['tbpref'] . "')";
53 $filename = $path_to_root . "/config_db.php";
54 // Check if the file exists and is writable first.
55 if (file_exists($filename) && is_writable($filename))
57 if (!$zp = fopen($filename, 'w'))
63 if (!fwrite($zp, $msg))
79 function db_create_db($connection)
81 $db = mysql_connect($connection["host"] ,
82 $connection["dbuser"], $connection["dbpassword"]);
83 if (!mysql_select_db($connection["dbname"], $db))
85 $sql = "CREATE DATABASE " . $connection["dbname"] . "";
86 if (!mysql_query($sql))
88 mysql_select_db($connection["dbname"], $db);
93 function db_drop_db($connection)
96 if ($connection["tbpref"] == "")
98 $sql = "DROP DATABASE " . $connection["dbname"] . "";
99 return mysql_query($sql);
103 $res = db_query("show table status");
104 $all_tables = array();
105 while($row = db_fetch($res))
106 $all_tables[] = $row;
107 // get table structures
108 foreach ($all_tables as $table)
110 if (strpos($table['Name'], $connection["tbpref"]) === 0)
111 db_query("DROP TABLE `".$table['Name'] . "`");
113 //deleting the tables, how??
118 function db_import($filename, $connection, $force=true)
120 global $db, $go_debug;
122 $allowed_commands = array(
123 "create" => 'table_queries',
124 "alter table" => 'table_queries',
125 "insert" => 'data_queries',
126 "update" => 'data_queries',
127 "drop table if exists" => 'drop_queries');
128 $ignored_mysql_errors = array( //errors ignored in normal (non forced) mode
129 '1022', // duplicate key
130 '1050', // Table %s already exists
131 '1060', // duplicate column name
132 '1061', // duplicate key name
133 '1062', // duplicate key entry
134 '1091' // can't drop key/column check if exists
136 $data_queries = array();
137 $drop_queries = array();
138 $table_queries = array();
139 $sql_errors = array();
141 ini_set("max_execution_time", "180");
142 db_query("SET foreign_key_checks=0");
144 // uncrompress gziped backup files
145 if (strpos($filename, ".gz") || strpos($filename, ".GZ"))
146 $lines = db_ungzip("lines", $filename);
147 elseif (strpos($filename, ".zip") || strpos($filename, ".ZIP"))
148 $lines = db_unzip("lines", $filename);
150 $lines = file("". $filename);
154 foreach($lines as $line_no => $line)
158 $line = str_replace("0_", $connection["tbpref"], $line);
160 if ($query_table == '')
161 { // check if line begins with one of allowed queries
162 foreach($allowed_commands as $cmd => $table)
164 if (strtolower(substr($line, 0, strlen($cmd))) == $cmd)
166 $query_table = $table;
167 ${$query_table}[] = array('', $line_no+1);
172 if($query_table != '') // inside allowed query
174 $table = $query_table;
175 if (substr($line, -1) == ';') // end of query found
177 $line = substr($line, 0, strlen($line) - 1); // strip ';'
180 ${$table}[count(${$table}) - 1][0] .= $line . "\n";
185 { // for debugging purposes
186 global $path_to_root;
187 $f = fopen($path_to_root.'/tmp/dbimport.txt', 'w+');
188 fwrite($f, print_r($drop_queries,true) ."\n");
189 fwrite($f, print_r($table_queries,true) ."\n");
190 fwrite($f, print_r($data_queries,true));
194 // execute drop tables if exists queries
195 if (is_array($drop_queries))
197 foreach($drop_queries as $drop_query)
199 if (!db_query($drop_query[0]))
201 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force)
202 $sql_errors[] = array(db_error_msg($db), $drop_query[1]);
207 // execute create tables queries
208 if (is_array($table_queries))
210 foreach($table_queries as $table_query)
212 if (!db_query($table_query[0]))
214 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force) {
215 $sql_errors[] = array(db_error_msg($db), $table_query[1]);
221 // execute insert data queries
222 if (is_array($data_queries))
224 foreach($data_queries as $data_query)
226 if (!db_query($data_query[0]))
228 if (!in_array(db_error_no(),$ignored_mysql_errors) || !$force)
229 $sql_errors[] = array(db_error_msg($db), $data_query[1]);
234 db_query("SET foreign_key_checks=1");
236 if (count($sql_errors)) {
237 // display first failure message; the rest are probably derivative
238 $err = $sql_errors[0];
239 display_error(sprintf(_("SQL script execution failed in line %d: %s"),
244 //$shell_command = C_MYSQL_PATH . " -h $host -u $user -p{$password} $dbname < $filename";
245 //shell_exec($shell_command);
248 // returns the content of the gziped $path backup file. use of $mode see below
249 function db_ungzip($mode, $path)
251 $file_data = gzfile($path);
252 // returns one string or an array of lines
253 if ($mode != "lines")
254 return implode("",$file_data);
259 // returns the content of the ziped $path backup file. use of $mode see below
260 function db_unzip($mode, $path)
263 $all = implode("", file($path));
265 // convert path to name of ziped file
266 $filename = ereg_replace(".*/", "", $path);
267 $filename = substr($filename, 0, strlen($filename) - 4);
269 // compare filname in zip and filename from $_GET
270 if (substr($all, 30, strlen($filename)-4) . substr($all, 30+strlen($filename)+9, 4)
272 return ''; // exit if names differ
276 // get the suffix of the filename in hex
277 $crc_bugfix = substr($all, 30, strlen($filename)+13);
278 $crc_bugfix = substr(substr($crc_bugfix, 0, strlen($crc_bugfix) - 4),
279 strlen($crc_bugfix) - 12 - 4);
281 // convert hex to ascii
282 for ($i=0; $i < 12; )
283 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
285 // remove central directory information (we have always just one ziped file)
286 $comp = substr($all, -(strlen($all) - 30 - strlen($filename)-13));
287 $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)-13));
289 // fix the crc bugfix (see function save_to_file)
290 $comp = "x
\9c" . $comp . $suffix;
291 $file_data = gzuncompress($comp);
294 // returns one string or an array of lines
295 if ($mode != "lines")
298 return explode("\n", $file_data);
301 function db_backup($conn, $ext='no', $comm='', $tbpref = TB_PREF)
303 if ($conn['tbpref'] != "")
304 $filename = $conn['dbname'] . "_" . $conn['tbpref'] . date("Ymd_Hi") . ".sql";
306 $filename = $conn['dbname'] . "_" . date("Ymd_Hi") . ".sql";
308 return db_export($conn, $filename, $ext, $comm, $tbpref);
311 // generates a dump of $db database
312 // $drop and $zip tell if to include the drop table statement or dry to pack
313 function db_export($conn, $filename, $zip='no', $comment='', $tbpref = TB_PREF)
316 global $app_title, $version, $power_url, $path_to_root;
319 // set max string size before writing to file
320 $max_size = 1048576 * 2; // 2 MB
321 // changes max size if value can be retrieved
322 if (ini_get("memory_limit"))
323 $max_size = 900000 * ini_get("memory_limit");
325 // set backupfile name
327 $backupfile = $filename . ".gz";
328 elseif ($zip == "zip")
329 $backupfile = $filename . ".zip";
331 $backupfile = $filename;
332 $company = get_company_pref('coy_name', $tbpref);
335 $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
336 $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
337 $out.="# Built by " . $app_title . " " . $version ."\n";
338 $out.="# ".$power_url."\n";
339 $out.="# Company: ". @html_entity_decode($company, ENT_COMPAT, $_SESSION['language']->encoding)."\n";
340 $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
342 // write users comment
345 $out .= "# Comment:\n";
346 $comment=preg_replace("'\n'","\n# ","# ".$comment);
347 //$comment=str_replace("\n", "\n# ", $comment);
348 foreach(explode("\n",$comment) as $line)
353 //$out.="use ".$db.";\n"; we don't use this option.
355 // get auto_increment values and names of all tables
356 $res = db_query("show table status");
357 $all_tables = array();
358 while($row = db_fetch($res))
360 //if ($conn["tbpref"] == "" || strpos($row['Name'], $conn["tbpref"]) !== false) replaced
361 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
362 ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) !== false))
363 $all_tables[] = $row;
365 // get table structures
366 foreach ($all_tables as $table)
368 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
369 $tmp = db_fetch($res1);
370 $table_sql[$table['Name']] = $tmp["Create Table"];
375 if (isset($table_sql))
377 foreach($table_sql as $tablenme=>$table)
380 // save all tables, needed for creating this table in $fks
381 while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
383 $tmp_table = substr($tmp_table, $ref_pos + 12);
384 $ref_pos = strpos($tmp_table, "(");
385 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
390 $all_tables = order_sql_tables($all_tables, $fks);
392 // as long as no error occurred
395 //while($row=@mysql_fetch_array($res))
396 foreach ($all_tables as $row)
398 $tablename = $row['Name'];
399 $auto_incr[$tablename] = $row['Auto_increment'];
403 $out.="### Structure of table `".$tablename."` ###\n\n";
405 $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
406 $out.=$table_sql[$tablename];
408 // add auto_increment value
409 if ($auto_incr[$tablename])
410 $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
417 $out.="### Data of table `".$tablename."` ###\n\n";
419 // check if field types are NULL or NOT NULL
420 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
422 $field_type = array();
423 for ($j = 0; $j < db_num_rows($res3); $j++)
425 $row3 = db_fetch($res3);
426 $field_type[] = $row3[2];
429 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
430 for ($j = 0; $j < db_num_rows($res2); $j++)
432 $out .= "INSERT INTO `" . $tablename . "` VALUES (";
433 $row2 = db_fetch_row($res2);
434 // run through each field
435 for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
437 $out .= db_escape(@html_entity_decode($row2[$k], ENT_COMPAT, $_SESSION['language']->encoding));
443 // if saving is successful, then empty $out, else set error flag
444 if (strlen($out) > $max_size && $zip != "zip")
446 if (save_to_file($backupfile, $zip, $out))
453 // an error occurred! Try to delete file and return error status
457 @unlink(BACKUP_PATH . $backupfile);
461 // if saving is successful, then empty $out, else set error flag
462 if (strlen($out) > $max_size && $zip != "zip")
464 if (save_to_file($backupfile, $zip, $out))
471 // an error occurred! Try to delete file and return error status
475 @unlink(BACKUP_PATH . $backupfile);
479 // if (mysql_error()) return "DB_ERROR";
480 //@mysql_close($con);
484 if (save_to_file($backupfile, $zip, $out))
490 @unlink(BACKUP_PATH . $backupfile);
496 // orders the tables in $tables according to the constraints in $fks
497 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
498 function order_sql_tables($tables, $fks)
500 // do not order if no contraints exist
505 $new_tables = array();
508 while (count($tables) && $modified == true)
511 foreach ($tables as $key=>$row)
513 // delete from $tables and add to $new_tables
514 if (isset($fks[$row['Name']]))
516 foreach($fks[$row['Name']] as $needed)
518 // go to next table if not all needed tables exist in $existing
519 if (!in_array($needed,$existing))
523 // delete from $tables and add to $new_tables
524 $existing[] = $row['Name'];
525 $new_tables[] = $row;
527 unset($tables[$key]);
535 // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
536 // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
537 // until now, just add the lasting tables to $new_tables, return them and print a warning
538 foreach($tables as $row)
539 $new_tables[] = $row;
540 echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
545 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
546 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
547 function save_to_file($backupfile, $zip, $fileData)
549 global $path_to_root;
553 if ($zp = @gzopen(BACKUP_PATH . $backupfile, "a9"))
555 @gzwrite($zp, $fileData);
564 // $zip contains the timestamp
566 elseif ($zip == "zip")
568 // based on zip.lib.php 2.2 from phpMyBackupAdmin
569 // offical zip format: http://www.pkware.com/appnote.txt
571 // End of central directory record
572 $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
574 // "local file header" segment
575 $unc_len = strlen($fileData);
576 $crc = crc32($fileData);
577 $zdata = gzcompress($fileData);
579 // extend stored file name with suffix
580 // needed for decoding (because of crc bug)
581 $name_suffix = substr($zdata, -4, 4);
583 for ($i = 0; $i < 4; $i++)
584 $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
586 $name = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql";
589 $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
590 $c_len = strlen($zdata);
593 $timearray = getdate($zip);
594 $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
595 ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
596 $dtime = dechex($dostime);
597 $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
598 eval('$hexdtime="' . $hexdtime . '";');
600 // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
601 $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
603 // crc32, compressed filesize, uncompressed filesize
604 $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
606 $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
608 // length of filename, extra field length
609 $fr .= pack('v', strlen($name)) . pack('v', 0);
612 // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
613 $fr .= $zdata . $sub2;
615 // now add to central directory record
616 $cdrec = "\x50\x4b\x01\x02";
617 $cdrec .= "\x00\x00"; // version made by
618 $cdrec .= $sub1 . $sub2;
620 // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
621 $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
625 $fileData = $fr . $cdrec . $eof_ctrl_dir;
627 // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
628 $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
630 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
632 @fwrite($zp, $fileData);
645 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
647 @fwrite($zp, $fileData);
658 function create_comp_dirs($comp_path, $comp_subdirs)
660 $index = "<?php\nheader(\"Location: ../index.php\");\n?>";
663 $f = @fopen("$cdir/index.php", "wb");
667 foreach($comp_subdirs as $dir)
669 @mkdir($cdir.'/'.$dir);
670 $f = @fopen("$cdir/$dir/index.php", "wb");