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