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