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