3 function write_config_db($new = false)
5 global $path_to_root, $def_coy, $db_connections, $tb_pref_counter;
6 include_once($path_to_root . "/config_db.php");
10 $n = count($db_connections);
12 $msg .= "/*Connection Information for the database\n";
13 $msg .= "- \$def_coy is the default company that is pre-selected on login\n\n";
14 $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";
15 $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";
16 $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";
17 $msg .= "- password is the password the user of the database requires to be sent to authorise the above database user\n\n";
18 $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";
19 $msg .= " The scripts for MySQL provided use the name logicworks */\n\n\n";
21 $msg .= "\$def_coy = " . $def_coy . ";\n\n";
22 $msg .= "\$tb_pref_counter = " . $tb_pref_counter . ";\n\n";
23 $msg .= "\$db_connections = array (\n";
25 for ($i = 0; $i < $n; $i++)
31 $msg .= "('name' => '" . $db_connections[$i]['name'] . "',\n";
32 $msg .= "\t\t'host' => '" . $db_connections[$i]['host'] . "',\n";
33 $msg .= "\t\t'dbuser' => '" . $db_connections[$i]['dbuser'] . "',\n";
34 $msg .= "\t\t'dbpassword' => '" . $db_connections[$i]['dbpassword'] . "',\n";
35 $msg .= "\t\t'dbname' => '" . $db_connections[$i]['dbname'] . "',\n";
36 $msg .= "\t\t'tbpref' => '" . $db_connections[$i]['tbpref'] . "')";
43 $filename = $path_to_root . "/config_db.php";
44 // Check if the file exists and is writable first.
45 if (file_exists($filename) && is_writable($filename))
47 if (!$zp = fopen($filename, 'w'))
53 if (!fwrite($zp, $msg))
69 function db_create_db($connection)
71 $db = mysql_connect($connection["host"] ,
72 $connection["dbuser"], $connection["dbpassword"]);
73 if (!mysql_select_db($connection["dbname"], $db))
75 $sql = "CREATE DATABASE " . $connection["dbname"] . "";
76 if (!mysql_query($sql))
78 mysql_select_db($connection["dbname"], $db);
83 function db_drop_db($connection)
85 if ($connection["tbpref"] == "")
87 $sql = "DROP DATABASE " . $connection["dbname"] . "";
88 return mysql_query($sql);
92 $res = db_query("show table status");
93 $all_tables = array();
94 while($row = db_fetch($res))
96 // get table structures
97 foreach ($all_tables as $table)
99 if (strpos($table['Name'], $connection["tbpref"]) === 0)
100 db_query("DROP TABLE `".$table['Name'] . "`");
102 //deleting the tables, how??
107 function db_import($filename, $connection)
109 $data_queries = array();
110 $drop_queries = array();
111 $table_queries = array();
113 // uncrompress gziped backup files
114 if (strpos($filename, ".gzip") || strpos($filename, ".GZIP"))
115 $lines = db_ungzip("lines", $filename);
116 elseif (strpos($filename, ".zip") || strpos($filename, ".ZIP"))
117 $lines = db_unzip("lines", $filename);
119 $lines = file("". $filename);
121 // divide insert and create sql queries
122 // $table is set to TRUE if the next line belongs to a create sql query
124 foreach($lines as $line)
128 $line = str_replace("0_", $connection["tbpref"], $line);
129 // $line = str_replace("Y_", "0_", $line);
130 // the last line did not belong to a 'create' sql query
134 // this line does not, too
135 if (strtolower(substr($line,0,6)) == "insert")
137 $data_queries[] = substr($line, 0, strlen($line) - 1);
139 // this line does not, too
141 elseif (strtolower(substr($line,0,6)) == "update")
143 $data_queries[] = substr($line, 0, strlen($line) - 1);
145 // this line does not, too
147 elseif (strtolower(substr($line, 0, 20)) == "drop table if exists")
149 $drop_queries[] = substr($line, 0, strlen($line) - 1);
153 elseif (strtolower(substr($line, 0, 6)) == "create")
156 $table_queries[] = $line . "\n";
158 elseif (strtolower(substr($line, 0, 11)) == "alter table")
160 $data_queries[] = substr($line, 0, strlen($line) - 1);
163 // the current line belongs to a create sql query
168 // create sql query ending in this line
169 if (strtolower(substr($line, 0, 1)) == ")") {
171 $line = substr($line,0,strlen($line)-1);
173 $table_queries[count($table_queries) - 1] .= $line . "\n";
179 // execute drop tables if exists queries
180 if (is_array($drop_queries))
182 foreach($drop_queries as $drop_query)
185 if (!db_query($drop_query))
188 //if ($CONF['import_error']) echo nl2br($drop_query)."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
193 // execute create tables queries
194 if (is_array($table_queries))
196 foreach($table_queries as $table_query)
199 if (!db_query($table_query))
202 //if ($CONF['import_error']) echo nl2br($table_query)."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
207 // execute insert data queries
208 if (is_array($data_queries))
210 foreach($data_queries as $data_query)
213 if (!db_query($data_query))
215 //if ($CONF['import_error']) echo $data_query."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
222 // show number successful executed querys or if an error did occur
225 //echo "<div class=\"red\">".IM_ERROR.".</div>\n";
228 //echo "<div class=\"green\">".IM_SUCCESS." ".count($table_queries)." ".IM_TABLES." ".count($data_queries)." ".IM_ROWS." (".$import_file.")</div>\n";
229 //$shell_command = C_MYSQL_PATH . " -h $host -u $user -p{$password} $dbname < $filename";
230 //shell_exec($shell_command);
233 // returns the content of the gziped $path backup file. use of $mode see below
234 function db_ungzip($mode, $path)
236 $file_data = gzfile($path);
237 // returns one string or an array of lines
238 if ($mode != "lines")
239 return implode("",$file_data);
244 // returns the content of the ziped $path backup file. use of $mode see below
245 function db_unzip($mode, $path)
248 $all = implode("", file($path));
250 // convert path to name of ziped file
251 $filename = ereg_replace(".*/", "", $path);
252 $filename = substr($filename, 0, strlen($filename) - 4);
254 // compare filname in zip and filename from $_GET
255 if (substr($all, 30, strlen($filename)) != $filename)
258 // exit if names differ
259 //echo F_WRONG_FILE.".";
264 // get the suffix of the filename in hex
265 $crc_bugfix = substr(substr($filename, 0, strlen($filename) - 4), strlen($filename) - 12 - 4);
268 // convert hex to ascii
269 for ($i=0; $i < 12; )
270 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
272 // remove central directory information (we have always just one ziped file)
273 $comp = substr($all, -(strlen($all) - 30 - strlen($filename)));
274 $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)));
276 // fix the crc bugfix (see function save_to_file)
277 $comp = "x
\9c" . $comp . $suffix;
278 $file_data = gzuncompress($comp);
281 // returns one string or an array of lines
282 if ($mode != "lines")
285 return explode("\n", $file_data);
288 // generates a dump of $db database
289 // $drop and $zip tell if to include the drop table statement or dry to pack
290 function db_export($conn, $filename, $zip='no', $comment='')
293 global $app_title, $version, $power_url, $path_to_root;
297 // set max string size before writing to file
298 $max_size = 1048576 * 2; // 2 MB
299 // changes max size if value can be retrieved
300 if (ini_get("memory_limit"))
301 $max_size = 900000 * ini_get("memory_limit");
303 // set backupfile name
305 $backupfile = $filename . ".gz";
306 elseif ($zip == "zip")
307 $backupfile = $filename . ".zip";
309 $backupfile = $filename;
310 $company = get_company_pref('coy_name');
312 $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
313 $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
314 $out.="# Built by " . $app_title . " " . $version ."\n";
315 $out.="# ".$power_url."\n";
316 $out.="# Company: ".$company."\n";
317 $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
319 // write users comment
322 $out .= "# Comment:\n";
323 $comment=preg_replace("'\n'","\n# ","# ".$comment);
324 //$comment=str_replace("\n", "\n# ", $comment);
325 foreach(explode("\n",$comment) as $line)
330 //$out.="use ".$db.";\n"; we don't use this option.
332 // get auto_increment values and names of all tables
333 $res = db_query("show table status");
334 $all_tables = array();
335 while($row = db_fetch($res))
337 //if ($conn["tbpref"] == "" || strpos($row['Name'], $conn["tbpref"]) !== false) replaced
338 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
339 ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) !== false))
340 $all_tables[] = $row;
342 // get table structures
343 foreach ($all_tables as $table)
345 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
346 $tmp = db_fetch($res1);
347 $table_sql[$table['Name']] = $tmp["Create Table"];
352 if (isset($table_sql))
354 foreach($table_sql as $tablenme=>$table)
357 // save all tables, needed for creating this table in $fks
358 while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
360 $tmp_table = substr($tmp_table, $ref_pos + 12);
361 $ref_pos = strpos($tmp_table, "(");
362 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
367 $all_tables = order_sql_tables($all_tables, $fks);
369 // as long as no error occurred
372 //while($row=@mysql_fetch_array($res))
373 foreach ($all_tables as $row)
375 $tablename = $row['Name'];
376 $auto_incr[$tablename] = $row['Auto_increment'];
380 $out.="### Structure of table `".$tablename."` ###\n\n";
382 $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
383 $out.=$table_sql[$tablename];
385 // add auto_increment value
386 if ($auto_incr[$tablename])
387 $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
394 $out.="### Data of table `".$tablename."` ###\n\n";
396 // check if field types are NULL or NOT NULL
397 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
399 $field_type = array();
400 for ($j = 0; $j < db_num_rows($res3); $j++)
402 $row3 = db_fetch($res3);
403 $field_type[] = $row3[2];
406 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
407 for ($j = 0; $j < db_num_rows($res2); $j++)
409 $out .= "INSERT INTO `" . $tablename . "` VALUES (";
410 $row2 = db_fetch_row($res2);
411 // run through each field
412 for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
414 // identify null values and save them as null instead of ''
415 if ($field_type[$k] != "" && $field_type[$k] != "NO" && $row2[$k] == "")
418 $out .= "'" . db_escape($row2[$k]) . "'";
424 // if saving is successful, then empty $out, else set error flag
425 if (strlen($out) > $max_size && $zip != "zip")
427 if (save_to_file($backupfile, $zip, $out))
434 // an error occurred! Try to delete file and return error status
438 @unlink(BACKUP_PATH . $backupfile);
442 // if saving is successful, then empty $out, else set error flag
443 if (strlen($out) > $max_size && $zip != "zip")
445 if (save_to_file($backupfile, $zip, $out))
452 // an error occurred! Try to delete file and return error status
456 @unlink(BACKUP_PATH . $backupfile);
460 // if (mysql_error()) return "DB_ERROR";
461 //@mysql_close($con);
465 if (save_to_file($backupfile, $zip, $out))
471 @unlink(BACKUP_PATH . $backupfile);
477 // orders the tables in $tables according to the constraints in $fks
478 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
479 function order_sql_tables($tables, $fks)
481 // do not order if no contraints exist
486 $new_tables = array();
489 while (count($tables) && $modified == true)
492 foreach ($tables as $key=>$row)
494 // delete from $tables and add to $new_tables
495 if (isset($fks[$row['Name']]))
497 foreach($fks[$row['Name']] as $needed)
499 // go to next table if not all needed tables exist in $existing
500 if (!in_array($needed,$existing))
504 // delete from $tables and add to $new_tables
505 $existing[] = $row['Name'];
506 $new_tables[] = $row;
508 unset($tables[$key]);
516 // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
517 // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
518 // until now, just add the lasting tables to $new_tables, return them and print a warning
519 foreach($tables as $row)
520 $new_tables[] = $row;
521 echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
526 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
527 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
528 function save_to_file($backupfile, $zip, $fileData)
530 global $path_to_root;
534 if ($zp = @gzopen(BACKUP_PATH . $backupfile, "a9"))
536 @gzwrite($zp, $fileData);
545 // $zip contains the timestamp
547 elseif ($zip == "zip")
549 // based on zip.lib.php 2.2 from phpMyBackupAdmin
550 // offical zip format: http://www.pkware.com/appnote.txt
552 // End of central directory record
553 $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
555 // "local file header" segment
556 $unc_len = strlen($fileData);
557 $crc = crc32($fileData);
558 $zdata = gzcompress($fileData);
560 // string needed for decoding (because of crc bug)
561 //$name_suffix = substr($zdata, -4, 4);
562 //$name_suffix2 = "_";
563 //for ($i = 0; $i < 4; $i++)
564 // $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
565 //$backupfile = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql.zip";
566 $name = substr($backupfile, 0, strlen($backupfile) -4);
569 $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
570 $c_len = strlen($zdata);
573 $timearray = getdate($zip);
574 $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
575 ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
576 $dtime = dechex($dostime);
577 $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
578 eval('$hexdtime="' . $hexdtime . '";');
580 // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
581 $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
583 // crc32, compressed filesize, uncompressed filesize
584 $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
586 $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
588 // length of filename, extra field length
589 $fr .= pack('v', strlen($name)) . pack('v', 0);
592 // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
593 $fr .= $zdata . $sub2;
595 // now add to central directory record
596 $cdrec = "\x50\x4b\x01\x02";
597 $cdrec .= "\x00\x00"; // version made by
598 $cdrec .= $sub1 . $sub2;
600 // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
601 $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
605 $fileData = $fr . $cdrec . $eof_ctrl_dir;
607 // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
608 $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
610 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
612 @fwrite($zp, $fileData);
625 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
627 @fwrite($zp, $fileData);