Minor bugfix in db_import()
[fa-stable.git] / admin / db / maintenance_db.inc
1 <?php
2
3 function write_config_db($new = false)
4 {
5         global $path_to_root, $def_coy, $db_connections, $tb_pref_counter;
6         include_once($path_to_root . "/config_db.php");
7
8         if ($new)
9                 $tb_pref_counter++;
10         $n = count($db_connections);
11         $msg = "<?php\n\n";
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";
20
21         $msg .= "\$def_coy = " . $def_coy . ";\n\n";
22         $msg .= "\$tb_pref_counter = " . $tb_pref_counter . ";\n\n";
23         $msg .= "\$db_connections = array (\n";
24         $msg .= "\t0 => ";
25         for ($i = 0; $i < $n; $i++)
26         {
27                 if ($i > 0)
28                         $msg .= "\tarray ";
29                 else
30                         $msg .= "array ";
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'] . "')";
37                 if ($i != $n - 1)
38                         $msg .= ",";
39                 $msg .= "\n\n";
40         }
41         $msg .= "\t);\n?>";
42
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))
46         {
47                 if (!$zp = fopen($filename, 'w'))
48                 {
49                         return -1;
50                 }
51                 else
52                 {
53                         if (!fwrite($zp, $msg))
54                         {
55                                 fclose($zp);
56                                 return -2;
57                         }
58                         // Close file
59                         fclose($zp);
60                 }
61         }
62         else
63         {
64                 return -3;
65         }
66         return 0;
67 }
68
69 function db_create_db($connection)
70 {
71         $db = mysql_connect($connection["host"] ,
72                 $connection["dbuser"], $connection["dbpassword"]);
73         if (!mysql_select_db($connection["dbname"], $db))
74         {
75                 $sql = "CREATE DATABASE " . $connection["dbname"] . "";
76                 if (!mysql_query($sql))
77                         return 0;
78                 mysql_select_db($connection["dbname"], $db);
79         }
80         return $db;
81 }
82
83 function db_drop_db($connection)
84 {
85         if ($connection["tbpref"] == "")
86         {
87                 $sql = "DROP DATABASE " . $connection["dbname"] . "";
88                 return mysql_query($sql);
89         }
90         else
91         {
92         $res = db_query("show table status");
93         $all_tables = array();
94         while($row = db_fetch($res))
95                 $all_tables[] = $row;
96         // get table structures
97                 foreach ($all_tables as $table)
98                 {
99                         if (strpos($table['Name'], $connection["tbpref"]) !== false)
100                                 db_query("DROP TABLE `".$table['Name'] . "`");
101                 }
102                 //deleting the tables, how??
103                 return true;
104         }
105 }
106
107 function db_import($filename, $connection)
108 {
109         $data_queries = array();
110         $drop_queries = array();
111         $table_queries = array();
112
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);
118         else
119                 $lines = file("". $filename);
120
121         // divide insert and create sql queries
122         // $table is set to TRUE if the next line belongs to a create sql query
123         $table = false;
124         foreach($lines as $line)
125         {
126                 $line = trim($line);
127
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
131                 if (!$table)
132                 {
133
134                         // this line does not, too
135                         if (strtolower(substr($line,0,6)) == "insert")
136                         {
137                                 $data_queries[] = substr($line, 0, strlen($line) - 1);
138
139                         // this line does not, too
140                         }
141                         elseif (strtolower(substr($line, 0, 20)) == "drop table if exists")
142                         {
143                                 $drop_queries[] = substr($line, 0, strlen($line) - 1);
144
145                         // this line does!
146                         }
147                         elseif (strtolower(substr($line, 0, 6)) == "create")
148                         {
149                                 $table = true;
150                                 $table_queries[] = $line . "\n";
151                         }
152                         elseif (strtolower(substr($line, 0, 11)) == "alter table")
153                         {
154                                 $data_queries[] = substr($line, 0, strlen($line) - 1);
155                         }
156
157                 // the current line belongs to a create sql query
158                 }
159                 else
160                 {
161
162                         // create sql query ending in this line
163                         if (strtolower(substr($line, 0, 1)) == ")") {
164                                 $table = false;
165                                 $line = substr($line,0,strlen($line)-1);
166                   }
167                         $table_queries[count($table_queries) - 1] .= $line . "\n";
168                 }
169         }
170
171         $sql_error = false;
172
173         // execute drop tables if exists queries
174         if (is_array($drop_queries))
175         {
176                 foreach($drop_queries as $drop_query)
177                 {
178                         $sql_error = false;
179                         if (!db_query($drop_query))
180                         {
181                                 $sql_error = true;
182                                 //if ($CONF['import_error']) echo nl2br($drop_query)."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
183                         }
184                 }
185         }
186
187         // execute create tables queries
188         if (is_array($table_queries))
189         {
190                 foreach($table_queries as $table_query)
191                 {
192                         $sql_error = false;
193                         if (!db_query($table_query))
194                         {
195                                 $sql_error = true;
196                                 //if ($CONF['import_error']) echo nl2br($table_query)."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
197                         }
198                 }
199         }
200
201         // execute insert data queries
202         if (is_array($data_queries))
203         {
204                 foreach($data_queries as $data_query)
205                 {
206                         $sql_error = false;
207                         if (!db_query($data_query))
208                         {
209                                 //if ($CONF['import_error']) echo $data_query."\n<div class=\"bold_left\">".mysql_error()."</div><br>\n";
210                                 $sql_error = true;
211                                 return false;
212                         }
213                 }
214         }
215
216         // show number successful executed querys or if an error did occur
217         if ($sql_error == 1)
218                 return false;
219                 //echo "<div class=\"red\">".IM_ERROR.".</div>\n";
220         else
221                 return true;
222                 //echo "<div class=\"green\">".IM_SUCCESS." ".count($table_queries)." ".IM_TABLES." ".count($data_queries)." ".IM_ROWS." (".$import_file.")</div>\n";
223         //$shell_command = C_MYSQL_PATH . " -h $host -u $user -p{$password} $dbname < $filename";
224         //shell_exec($shell_command);
225 }
226
227 // returns the content of the gziped $path backup file. use of $mode see below
228 function db_ungzip($mode, $path)
229 {
230     $file_data = gzfile($path);
231     // returns one string or an array of lines
232     if ($mode != "lines")
233         return implode("",$file_data);
234     else
235         return $file_data;
236 }
237
238 // returns the content of the ziped $path backup file. use of $mode see below
239 function db_unzip($mode, $path)
240 {
241     $all = false;
242     $all = implode("", file($path));
243
244     // convert path to name of ziped file
245     $filename = ereg_replace(".*/", "", $path);
246     $filename = substr($filename, 0, strlen($filename) - 4);
247
248     // compare filname in zip and filename from $_GET
249     if (substr($all, 30, strlen($filename)) != $filename)
250     {
251                 return '';
252         // exit if names differ
253         //echo F_WRONG_FILE.".";
254         //exit;
255     }
256     else
257     {
258         // get the suffix of the filename in hex
259         $crc_bugfix = substr(substr($filename, 0, strlen($filename) - 4), strlen($filename) - 12 - 4);
260         $suffix = false;
261
262         // convert hex to ascii
263         for ($i=0; $i < 12; )
264                 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
265
266         // remove central directory information (we have always just one ziped file)
267         $comp = substr($all, -(strlen($all) - 30 - strlen($filename)));
268         $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)));
269
270         // fix the crc bugfix (see function save_to_file)
271         $comp = "x\9c" . $comp . $suffix;
272         $file_data = gzuncompress($comp);
273     }
274
275     // returns one string or an array of lines
276     if ($mode != "lines")
277         return $file_data;
278     else
279         return explode("\n", $file_data);
280 }
281
282 // generates a dump of $db database
283 // $drop and $zip tell if to include the drop table statement or dry to pack
284 function db_export($conn, $filename, $zip='no', $comment='')
285 {
286
287         global $app_title, $version, $power_url, $path_to_root;
288
289     $error = false;
290
291     // set max string size before writing to file
292     $max_size = 1048576 * 2; // 2 MB
293     // changes max size if value can be retrieved
294     if (ini_get("memory_limit"))
295         $max_size = 900000 * ini_get("memory_limit");
296
297     // set backupfile name
298     if ($zip == "gzip")
299         $backupfile = $filename . ".gz";
300     elseif ($zip == "zip")
301         $backupfile = $filename . ".zip";
302     else
303         $backupfile = $filename;
304     $company = get_company_pref('coy_name');
305     //create comment
306     $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
307     $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
308     $out.="# Built by " . $app_title . " " . $version ."\n";
309     $out.="# ".$power_url."\n";
310     $out.="# Company: ".$company."\n";
311     $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
312
313         // write users comment
314         if ($comment)
315         {
316                 $out .= "# Comment:\n";
317                 $comment=preg_replace("'\n'","\n# ","# ".$comment);
318                 //$comment=str_replace("\n", "\n# ", $comment);
319                 foreach(explode("\n",$comment) as $line)
320                         $out .= $line."\n";
321                 $out.="\n";
322         }
323
324     //$out.="use ".$db.";\n"; we don't use this option.
325
326     // get auto_increment values and names of all tables
327     $res = db_query("show table status");
328     $all_tables = array();
329     while($row = db_fetch($res))
330     {
331                 //if ($conn["tbpref"] == "" || strpos($row['Name'], $conn["tbpref"]) !== false) replaced
332                 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
333                         ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) !== false))
334                 $all_tables[] = $row;
335     }
336         // get table structures
337         foreach ($all_tables as $table)
338         {
339                 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
340                 $tmp = db_fetch($res1);
341                 $table_sql[$table['Name']] = $tmp["Create Table"];
342         }
343
344         // find foreign keys
345         $fks = array();
346         if (isset($table_sql))
347         {
348                 foreach($table_sql as $tablenme=>$table)
349                 {
350                         $tmp_table=$table;
351                         // save all tables, needed for creating this table in $fks
352                         while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
353                         {
354                                 $tmp_table = substr($tmp_table, $ref_pos + 12);
355                                 $ref_pos = strpos($tmp_table, "(");
356                                 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
357                         }
358                 }
359         }
360         // order $all_tables
361         $all_tables = order_sql_tables($all_tables, $fks);
362
363         // as long as no error occurred
364         if (!$error)
365         {
366                 //while($row=@mysql_fetch_array($res))
367                 foreach ($all_tables as $row)
368                 {
369                         $tablename = $row['Name'];
370                         $auto_incr[$tablename] = $row['Auto_increment'];
371
372                         $out.="\n\n";
373                         // export tables
374                         $out.="### Structure of table `".$tablename."` ###\n\n";
375
376                         $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
377                         $out.=$table_sql[$tablename];
378
379                         // add auto_increment value
380                         if ($auto_incr[$tablename])
381                                 $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
382                         $out.=" ;";
383                         $out.="\n\n\n";
384
385                         // export data
386                         if (!$error)
387                         {
388                                 $out.="### Data of table `".$tablename."` ###\n\n";
389
390                                 // check if field types are NULL or NOT NULL
391                                 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
392
393                                 $field_type = array();
394                                 for ($j = 0; $j < db_num_rows($res3); $j++)
395                                 {
396                                         $row3 = db_fetch($res3);
397                                         $field_type[] = $row3[2];
398                                 }
399
400                                 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
401                                 for ($j = 0; $j < db_num_rows($res2); $j++)
402                                 {
403                                         $out .= "INSERT INTO `" . $tablename . "` VALUES (";
404                                         $row2 = db_fetch_row($res2);
405                                         // run through each field
406                                         for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
407                                         {
408                                                 // identify null values and save them as null instead of ''
409                                                 if ($field_type[$k] != "" && $field_type[$k] != "NO" && $row2[$k] == "")
410                                                         $out .= "NULL";
411                                                 else
412                                                         $out .= "'" . db_escape($row2[$k]) . "'";
413                                                 if ($k < ($nf - 1))
414                                                         $out .= ", ";
415                                         }
416                                         $out .= ");\n";
417
418                                         // if saving is successful, then empty $out, else set error flag
419                                         if (strlen($out) > $max_size && $zip != "zip")
420                                         {
421                                                 if (save_to_file($backupfile, $zip, $out))
422                                                         $out = "";
423                                                 else
424                                                         $error = true;
425                                         }
426                                 }
427
428                         // an error occurred! Try to delete file and return error status
429                         }
430                         elseif ($error)
431                         {
432                                 @unlink($path_to_root . BACKUP_PATH . $backupfile);
433                                 return false;
434                         }
435
436                         // if saving is successful, then empty $out, else set error flag
437                         if (strlen($out) > $max_size && $zip != "zip")
438                         {
439                                 if (save_to_file($backupfile, $zip, $out))
440                                         $out= "";
441                                 else
442                                         $error = true;
443                         }
444                 }
445
446         // an error occurred! Try to delete file and return error status
447         }
448         else
449         {
450                 @unlink($path_to_root . BACKUP_PATH . $backupfile);
451                 return false;
452         }
453
454         // if (mysql_error()) return "DB_ERROR";
455         //@mysql_close($con);
456
457         //if ($zip == "zip")
458         //      $zip = $time;
459         if (save_to_file($backupfile, $zip, $out))
460         {
461                 $out = "";
462         }
463         else
464         {
465                 @unlink($path_to_root . BACKUP_PATH . $backupfile);
466                 return false;
467         }
468     return $backupfile;
469 }
470
471 // orders the tables in $tables according to the constraints in $fks
472 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
473 function order_sql_tables($tables, $fks)
474 {
475         // do not order if no contraints exist
476         if (!count($fks))
477                 return $tables;
478
479         // order
480         $new_tables = array();
481         $existing = array();
482         $modified = true;
483         while (count($tables) && $modified == true)
484         {
485                 $modified = false;
486             foreach ($tables as $key=>$row)
487             {
488                 // delete from $tables and add to $new_tables
489                 if (isset($fks[$row['Name']]))
490                 {
491                         foreach($fks[$row['Name']] as $needed)
492                         {
493                         // go to next table if not all needed tables exist in $existing
494                         if (!in_array($needed,$existing))
495                                 continue 2;
496                     }
497                 }
498             // delete from $tables and add to $new_tables
499                 $existing[] = $row['Name'];
500                         $new_tables[] = $row;
501             prev($tables);
502             unset($tables[$key]);
503             $modified = true;
504
505             }
506         }
507
508         if (count($tables))
509         {
510             // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
511             // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
512             // until now, just add the lasting tables to $new_tables, return them and print a warning
513             foreach($tables as $row)
514                 $new_tables[] = $row;
515             echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
516         }
517         return $new_tables;
518 }
519
520 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
521 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
522 function save_to_file($backupfile, $zip, $fileData)
523 {
524         global $path_to_root;
525
526     if ($zip == "gzip")
527     {
528         if ($zp = @gzopen($path_to_root . BACKUP_PATH . $backupfile, "a9"))
529         {
530                         @gzwrite($zp, $fileData);
531                         @gzclose($zp);
532                         return true;
533         }
534         else
535         {
536                 return false;
537         }
538
539     // $zip contains the timestamp
540     }
541     elseif ($zip == "zip")
542     {
543         // based on zip.lib.php 2.2 from phpMyBackupAdmin
544         // offical zip format: http://www.pkware.com/appnote.txt
545
546         // End of central directory record
547         $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
548
549         // "local file header" segment
550         $unc_len = strlen($fileData);
551         $crc = crc32($fileData);
552         $zdata = gzcompress($fileData);
553
554         // string needed for decoding (because of crc bug)
555         //$name_suffix = substr($zdata, -4, 4);
556         //$name_suffix2 = "_";
557         //for ($i = 0; $i < 4; $i++)
558         //      $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
559         //$backupfile = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql.zip";
560         $name = substr($backupfile, 0, strlen($backupfile) -4);
561
562         // fix crc bug
563         $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
564         $c_len = strlen($zdata);
565
566         // dos time
567         $timearray = getdate($zip);
568         $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
569             ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
570         $dtime = dechex($dostime);
571         $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
572         eval('$hexdtime="' . $hexdtime . '";');
573
574         // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
575         $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
576
577         // crc32, compressed filesize, uncompressed filesize
578         $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
579
580         $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
581
582         // length of filename, extra field length
583         $fr .= pack('v', strlen($name)) . pack('v', 0);
584         $fr .= $name;
585
586         // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
587         $fr .= $zdata . $sub2;
588
589         // now add to central directory record
590         $cdrec = "\x50\x4b\x01\x02";
591         $cdrec .= "\x00\x00";                // version made by
592         $cdrec .= $sub1 . $sub2;
593
594          // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
595         $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
596         $cdrec .= $name;
597
598         // combine data
599         $fileData = $fr . $cdrec . $eof_ctrl_dir;
600
601         // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
602         $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
603
604         if ($zp = @fopen($path_to_root . BACKUP_PATH . $backupfile, "a"))
605         {
606                         @fwrite($zp, $fileData);
607                         @fclose($zp);
608                         return true;
609         }
610         else
611         {
612                 return false;
613         }
614
615         // uncompressed
616     }
617     else
618     {
619         if ($zp = @fopen($path_to_root . BACKUP_PATH . $backupfile, "a"))
620         {
621                         @fwrite($zp, $fileData);
622                         @fclose($zp);
623                         return true;
624         }
625         else
626         {
627                 return false;
628         }
629     }
630 }
631
632
633 ?>