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