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