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