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