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