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"]) !== false)
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, 20)) == "drop table if exists")
143 $drop_queries[] = substr($line, 0, strlen($line) - 1);
147 elseif (strtolower(substr($line, 0, 6)) == "create")
150 $table_queries[] = $line . "\n";
153 // the current line belongs to a create sql query
158 // create sql query ending in this line
159 if (strtolower(substr($line, 0, 1)) == ")")
161 $table_queries[count($table_queries) - 1] .= $line . "\n";
167 // execute drop tables if exists queries
168 if (is_array($drop_queries))
170 foreach($drop_queries as $drop_query)
173 if (!db_query($drop_query))
176 //if ($CONF['import_error']) echo nl2br($drop_query)."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
181 // execute create tables queries
182 if (is_array($table_queries))
184 foreach($table_queries as $table_query)
187 if (!db_query($table_query))
190 //if ($CONF['import_error']) echo nl2br($table_query)."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
195 // execute insert data queries
196 if (is_array($data_queries))
198 foreach($data_queries as $data_query)
201 if (!db_query($data_query))
203 //if ($CONF['import_error']) echo $data_query."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
209 // show number successful executed querys or if an error did occur
212 //echo "<div class=\"red\">".IM_ERROR.".</div>\n";
215 //echo "<div class=\"green\">".IM_SUCCESS." ".count($table_queries)." ".IM_TABLES." ".count($data_queries)." ".IM_ROWS." (".$import_file.")</div>\n";
216 //$shell_command = C_MYSQL_PATH . " -h $host -u $user -p{$password} $dbname < $filename";
217 //shell_exec($shell_command);
220 // returns the content of the gziped $path backup file. use of $mode see below
221 function db_ungzip($mode, $path)
223 $file_data = gzfile($path);
224 // returns one string or an array of lines
225 if ($mode != "lines")
226 return implode("",$file_data);
231 // returns the content of the ziped $path backup file. use of $mode see below
232 function db_unzip($mode, $path)
235 $all = implode("", file($path));
237 // convert path to name of ziped file
238 $filename = ereg_replace(".*/", "", $path);
239 $filename = substr($filename, 0, strlen($filename) - 4);
241 // compare filname in zip and filename from $_GET
242 if (substr($all, 30, strlen($filename)) != $filename)
245 // exit if names differ
246 //echo F_WRONG_FILE.".";
251 // get the suffix of the filename in hex
252 $crc_bugfix = substr(substr($filename, 0, strlen($filename) - 4), strlen($filename) - 12 - 4);
255 // convert hex to ascii
256 for ($i=0; $i < 12; )
257 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
259 // remove central directory information (we have always just one ziped file)
260 $comp = substr($all, -(strlen($all) - 30 - strlen($filename)));
261 $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)));
263 // fix the crc bugfix (see function save_to_file)
264 $comp = "x
\9c" . $comp . $suffix;
265 $file_data = gzuncompress($comp);
268 // returns one string or an array of lines
269 if ($mode != "lines")
272 return explode("\n", $file_data);
275 // generates a dump of $db database
276 // $drop and $zip tell if to include the drop table statement or dry to pack
277 function db_export($conn, $filename, $zip='no', $comment='')
280 global $app_title, $version, $power_url, $path_to_root;
284 // set max string size before writing to file
285 $max_size = 1048576 * 2; // 2 MB
286 // changes max size if value can be retrieved
287 if (ini_get("memory_limit"))
288 $max_size = 900000 * ini_get("memory_limit");
290 // set backupfile name
292 $backupfile = $filename . ".gz";
293 elseif ($zip == "zip")
294 $backupfile = $filename . ".zip";
296 $backupfile = $filename;
297 $company = get_company_pref('coy_name');
299 $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
300 $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
301 $out.="# Built by " . $app_title . " " . $version ."\n";
302 $out.="# ".$power_url."\n";
303 $out.="# Company: ".$company."\n";
304 $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
306 // write users comment
309 $out .= "# Comment:\n";
310 $comment=preg_replace("'\n'","\n# ","# ".$comment);
311 //$comment=str_replace("\n", "\n# ", $comment);
312 foreach(explode("\n",$comment) as $line)
317 //$out.="use ".$db.";\n"; we don't use this option.
319 // get auto_increment values and names of all tables
320 $res = db_query("show table status");
321 $all_tables = array();
322 while($row = db_fetch($res))
324 //if ($conn["tbpref"] == "" || strpos($row['Name'], $conn["tbpref"]) !== false) replaced
325 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
326 ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) !== false))
327 $all_tables[] = $row;
329 // get table structures
330 foreach ($all_tables as $table)
332 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
333 $tmp = db_fetch($res1);
334 $table_sql[$table['Name']] = $tmp["Create Table"];
339 if (isset($table_sql))
341 foreach($table_sql as $tablenme=>$table)
344 // save all tables, needed for creating this table in $fks
345 while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
347 $tmp_table = substr($tmp_table, $ref_pos + 12);
348 $ref_pos = strpos($tmp_table, "(");
349 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
354 $all_tables = order_sql_tables($all_tables, $fks);
356 // as long as no error occurred
359 //while($row=@mysql_fetch_array($res))
360 foreach ($all_tables as $row)
362 $tablename = $row['Name'];
363 $auto_incr[$tablename] = $row['Auto_increment'];
367 $out.="### Structure of table `".$tablename."` ###\n\n";
369 $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
370 $out.=$table_sql[$tablename];
372 // add auto_increment value
373 if ($auto_incr[$tablename])
374 $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
381 $out.="### Data of table `".$tablename."` ###\n\n";
383 // check if field types are NULL or NOT NULL
384 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
386 $field_type = array();
387 for ($j = 0; $j < db_num_rows($res3); $j++)
389 $row3 = db_fetch($res3);
390 $field_type[] = $row3[2];
393 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
394 for ($j = 0; $j < db_num_rows($res2); $j++)
396 $out .= "INSERT INTO `" . $tablename . "` VALUES (";
397 $row2 = db_fetch_row($res2);
398 // run through each field
399 for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
401 // identify null values and save them as null instead of ''
402 if ($field_type[$k] != "" && $field_type[$k] != "NO" && $row2[$k] == "")
405 $out .= "'" . db_escape($row2[$k]) . "'";
411 // if saving is successful, then empty $out, else set error flag
412 if (strlen($out) > $max_size && $zip != "zip")
414 if (save_to_file($backupfile, $zip, $out))
421 // an error occurred! Try to delete file and return error status
425 @unlink($path_to_root . BACKUP_PATH . $backupfile);
429 // if saving is successful, then empty $out, else set error flag
430 if (strlen($out) > $max_size && $zip != "zip")
432 if (save_to_file($backupfile, $zip, $out))
439 // an error occurred! Try to delete file and return error status
443 @unlink($path_to_root . BACKUP_PATH . $backupfile);
447 // if (mysql_error()) return "DB_ERROR";
448 //@mysql_close($con);
452 if (save_to_file($backupfile, $zip, $out))
458 @unlink($path_to_root . BACKUP_PATH . $backupfile);
464 // orders the tables in $tables according to the constraints in $fks
465 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
466 function order_sql_tables($tables, $fks)
468 // do not order if no contraints exist
473 $new_tables = array();
476 while (count($tables) && $modified == true)
479 foreach ($tables as $key=>$row)
481 // delete from $tables and add to $new_tables
482 if (isset($fks[$row['Name']]))
484 foreach($fks[$row['Name']] as $needed)
486 // go to next table if not all needed tables exist in $existing
487 if (!in_array($needed,$existing))
491 // delete from $tables and add to $new_tables
492 $existing[] = $row['Name'];
493 $new_tables[] = $row;
495 unset($tables[$key]);
503 // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
504 // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
505 // until now, just add the lasting tables to $new_tables, return them and print a warning
506 foreach($tables as $row)
507 $new_tables[] = $row;
508 echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
513 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
514 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
515 function save_to_file($backupfile, $zip, $fileData)
517 global $path_to_root;
521 if ($zp = @gzopen($path_to_root . BACKUP_PATH . $backupfile, "a9"))
523 @gzwrite($zp, $fileData);
532 // $zip contains the timestamp
534 elseif ($zip == "zip")
536 // based on zip.lib.php 2.2 from phpMyBackupAdmin
537 // offical zip format: http://www.pkware.com/appnote.txt
539 // End of central directory record
540 $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
542 // "local file header" segment
543 $unc_len = strlen($fileData);
544 $crc = crc32($fileData);
545 $zdata = gzcompress($fileData);
547 // string needed for decoding (because of crc bug)
548 //$name_suffix = substr($zdata, -4, 4);
549 //$name_suffix2 = "_";
550 //for ($i = 0; $i < 4; $i++)
551 // $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
552 //$backupfile = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql.zip";
553 $name = substr($backupfile, 0, strlen($backupfile) -4);
556 $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
557 $c_len = strlen($zdata);
560 $timearray = getdate($zip);
561 $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
562 ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
563 $dtime = dechex($dostime);
564 $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
565 eval('$hexdtime="' . $hexdtime . '";');
567 // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
568 $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
570 // crc32, compressed filesize, uncompressed filesize
571 $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
573 $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
575 // length of filename, extra field length
576 $fr .= pack('v', strlen($name)) . pack('v', 0);
579 // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
580 $fr .= $zdata . $sub2;
582 // now add to central directory record
583 $cdrec = "\x50\x4b\x01\x02";
584 $cdrec .= "\x00\x00"; // version made by
585 $cdrec .= $sub1 . $sub2;
587 // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
588 $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
592 $fileData = $fr . $cdrec . $eof_ctrl_dir;
594 // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
595 $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
597 if ($zp = @fopen($path_to_root . BACKUP_PATH . $backupfile, "a"))
599 @fwrite($zp, $fileData);
612 if ($zp = @fopen($path_to_root . BACKUP_PATH . $backupfile, "a"))
614 @fwrite($zp, $fileData);