Added an extra parameter to db_export in maintenance_db.inc for new COAs
[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 /**
14  * @return Returns the array sorted as required
15  * @param $aryData Array containing data to sort
16  * @param $strIndex name of column to use as an index
17  * @param $strSortBy Column to sort the array by
18  * @param $strSortType String containing either asc or desc [default to asc]
19  * @desc Naturally sorts an array using by the column $strSortBy
20  */
21 function array_natsort($aryData, $strIndex, $strSortBy, $strSortType=false)
22 {
23    //    if the parameters are invalid
24    if (!is_array($aryData) || !$strSortBy)
25        //    return the array
26        return $aryData;
27
28    //    create our temporary arrays
29    $arySort = $aryResult = array();
30
31    //    loop through the array
32    foreach ($aryData as $key => $aryRow)
33        //    set up the value in the array
34        $arySort[$strIndex ? $aryRow[$strIndex] : $key] = $aryRow[$strSortBy];
35
36    //    apply the natural sort
37    natsort($arySort);
38
39    //    if the sort type is descending
40    if ($strSortType=="desc")
41        //    reverse the array
42        arsort($arySort);
43
44    //    loop through the sorted and original data
45                 foreach ($arySort as $arySortKey => $arySorted)
46                         if($strIndex) 
47                         {
48                                 foreach ($aryData as $aryOriginal)
49                                 // if the key matches
50                                         if ($aryOriginal[$strIndex]==$arySortKey)
51                                                 // add it to the output array
52                                                 array_push($aryResult, $aryOriginal);
53                         } else
54                                 $aryResult[$arySortKey] = $aryData[$arySortKey];
55    //    return the return
56    return $aryResult;
57 }
58
59 function update_admin_password($conn, $password)
60 {
61         $sql = "UPDATE ".$conn['tbpref']."users SET password=".db_escape($password) . "
62                 WHERE user_id='admin'";
63         db_query($sql, "could not update user password for 'admin'");
64 }
65
66 function write_config_db($new = false)
67 {
68         global $path_to_root, $def_coy, $db_connections, $tb_pref_counter;
69
70         if ($new)
71                 $tb_pref_counter++;
72         $n = count($db_connections);
73         $msg = "<?php\n\n";
74         $msg .= "/*Connection Information for the database\n";
75         $msg .= "\$def_coy - the default company that is pre-selected on login\n\n";
76         $msg .= "'host' - 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";
77         $msg .= "'dbuser' - the user name under which the company database should be accessed.\n";
78         $msg .= "  NB it is not secure to use root as the dbuser with no password - a user with appropriate privileges must be set up.\n\n";
79         $msg .= "'dbpassword' - the password required for the dbuser to authorise the above database user.\n\n";
80         $msg .= "'dbname' - 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";
81         $msg .= "'tbpref' - prefix on table names, or '' if not used. Always use non-empty prefixes if multiply company use the same database.\n";
82         $msg .= "*/\n\n\n";
83
84         $msg .= "\$def_coy = " . $def_coy . ";\n\n";
85         $msg .= "\$tb_pref_counter = " . $tb_pref_counter . ";\n\n";
86         $msg .= "\$db_connections = " .var_export($db_connections, true);
87         $msg .= ";\n?>";
88
89         $filename = $path_to_root . "/config_db.php";
90         // Check if the file exists and is writable first.
91         if ((!file_exists($filename) && is_writable($path_to_root)) || is_writable($filename))
92         {
93                 if (!$zp = fopen($filename, 'w'))
94                 {
95                         return -1;
96                 }
97                 else
98                 {
99                         if (!fwrite($zp, $msg))
100                         {
101                                 fclose($zp);
102                                 return -2;
103                         }
104                         // Close file
105                         fclose($zp);
106                 }
107         }
108         else
109         {
110                 return -3;
111         }
112         return 0;
113 }
114
115 function write_extensions($extensions=null, $company = -1)
116 {
117         global $path_to_root, $installed_extensions, $next_extension_id;
118
119         if (!isset($extensions)) {
120                 $extensions = $installed_extensions;
121         }
122         if (!isset($next_extension_id)) {
123                 $next_extension_id = 1;
124         }
125
126         $msg = "<?php\n\n";
127         if ($company == -1)
128                 $msg .=
129 "/* List of installed additional extensions. If extensions are added to the list manually
130         make sure they have unique and so far never used extension_ids as a keys,
131         and \$next_extension_id is also updated. More about format of this file yo will find in 
132         FA extension system documentation.
133 */
134 \n\$next_extension_id = $next_extension_id; // unique id for next installed extension\n\n";
135         else 
136                 $msg .=
137 "/*
138         Do not edit this file manually. This copy of global file is overwritten
139         by extensions editor.
140 */\n\n";
141
142         $msg .= "\$installed_extensions = ". var_export($extensions, true);
143         $msg .= ";\n?>";
144         $filename = $path_to_root . ($company==-1 ? '' : '/company/'.$company)
145                 .'/installed_extensions.php';
146
147         // Check if the file is writable first.
148         if (!$zp = @fopen($filename, 'w'))
149         {
150                 display_error(sprintf(_("Cannot open the extension setup file '%s' for writing."),
151                          $filename));
152                 return false;
153         }
154         else
155         {
156                 if (!fwrite($zp, $msg))
157                 {
158                         display_error(sprintf(_("Cannot write to the extensions setup file '%s'."),
159                                 $filename));
160                         fclose($zp);
161                         return false;
162                 }
163                 // Close file
164                 fclose($zp);
165         }
166         return true;
167 }
168 //---------------------------------------------------------------------------------------------
169 //
170 // Update per-company list of installed extensions
171 //
172 function update_extensions($extensions) {
173         global $db_connections;
174         
175         if (!write_extensions($extensions)) {
176                 display_notification(_("Cannot update system extensions list."));
177                 return false;
178         }
179
180         // update per company files
181         $cnt = count($db_connections);
182         for($i = 0; $i < $cnt; $i++) 
183         {
184                 $newexts = $extensions;
185                 // update 'active' status 
186                 $exts = get_company_extensions($i);
187                 foreach ($exts as $key => $ext) 
188                 {
189                         if (isset($newexts[$key]))
190                                 $newexts[$key]['active'] = $exts[$key]['active'];
191                 }
192                 if(!write_extensions($newexts, $i)) 
193                 {
194                         display_notification(sprintf(_("Cannot update extensions list for company '%s'."),
195                                 $db_connections[$i]['name']));
196                  return false;
197                 }
198         }
199         return true;
200 }
201
202
203 function write_lang()
204 {
205         global $path_to_root, $installed_languages, $dflt_lang;
206
207         $installed_languages = array_natsort($installed_languages, 'code', 'code');
208         $n = count($installed_languages);
209         $msg = "<?php\n\n";
210
211         $msg .= "/* How to make new entries here for non-packaged languages:\n\n";
212         $msg .= "-- 'code' should match the name of the directory for the language under \\lang\n.";
213         $msg .= "-- 'name' is the name that will be displayed in the language selection list (in Users and Display Setup)\n";
214         $msg .= "-- 'rtl' only needs to be set for right-to-left languages like Arabic and Hebrew\n";
215         $msg .= "-- 'encoding' used in translation file\n";
216         $msg .= "-- 'version' always set to '' for manually installed languages.\n";
217         $msg .= "-- 'path' installation path related to FA root (e.g. 'lang/en_US').\n";
218         $msg .= "*/\n\n\n";
219
220         $msg .= "\$installed_languages = " . var_export($installed_languages, true);
221         $msg .= ";\n";
222         $msg .= "\n\$dflt_lang = '$dflt_lang';\n?>\n";
223
224         $path = $path_to_root . "/lang";
225         $filename = $path.'/installed_languages.inc';
226         // Check if directory exists and is writable first.
227         if (file_exists($path) && is_writable($path))
228         {
229                 if (!$zp = fopen($filename, 'w'))
230                 {
231                         display_error(_("Cannot open the languages file - ") . $filename);
232                         return false;
233                 }
234                 else
235                 {
236                         if (!fwrite($zp, $msg))
237                         {
238                                 display_error(_("Cannot write to the language file - ") . $filename);
239                                 fclose($zp);
240                                 return false;
241                         }
242                         // Close file
243                         fclose($zp);
244                 }
245         }
246         else
247         {
248                 display_error(_("The language files folder ") . $path . _(" is not writable. Change its permissions so it is, then re-run the operation."));
249                 return false;
250         }
251         return true;
252 }
253
254 function db_create_db($connection)
255 {
256         $db = mysql_connect($connection["host"] ,
257                 $connection["dbuser"], $connection["dbpassword"]);
258         if (!mysql_select_db($connection["dbname"], $db))
259         {
260                 $sql = "CREATE DATABASE " . $connection["dbname"] . "";
261                 if (!mysql_query($sql))
262                         return 0;
263                 mysql_select_db($connection["dbname"], $db);
264         }
265         return $db;
266 }
267
268 function db_drop_db($connection)
269 {
270
271         if ($connection["tbpref"] == "")
272         {
273                 $sql = "DROP DATABASE " . $connection["dbname"] . "";
274                 return mysql_query($sql);
275         }
276         else
277         {
278         $res = db_query("show table status");
279         $all_tables = array();
280         while($row = db_fetch($res))
281                 $all_tables[] = $row;
282         // get table structures
283                 foreach ($all_tables as $table)
284                 {
285                         if (strpos($table['Name'], $connection["tbpref"]) === 0)
286                                 db_query("DROP TABLE `".$table['Name'] . "`");
287                 }
288                 //deleting the tables, how??
289                 return true;
290         }
291 }
292
293 function db_import($filename, $connection, $force=true)
294 {
295         global $db, $go_debug;
296
297         $allowed_commands = array(
298                 "create"  => 'table_queries', 
299                 "alter table" => 'table_queries', 
300                 "insert" => 'data_queries', 
301                 "update" => 'data_queries', 
302                 "drop table if exists" => 'drop_queries');
303         $ignored_mysql_errors = array( //errors ignored in normal (non forced) mode
304                 '1022', // duplicate key
305                 '1050', // Table %s already exists
306                 '1060', // duplicate column name
307                 '1061', // duplicate key name
308                 '1062', // duplicate key entry
309                 '1091'  // can't drop key/column check if exists
310         );
311         $data_queries = array();
312         $drop_queries = array();
313         $table_queries = array();
314         $sql_errors = array();
315
316         ini_set("max_execution_time", "180");
317         db_query("SET foreign_key_checks=0");
318         // uncrompress gziped backup files
319         if (strpos($filename, ".gz") || strpos($filename, ".GZ"))
320                 $lines = db_ungzip("lines", $filename);
321         elseif (strpos($filename, ".zip") || strpos($filename, ".ZIP"))
322                 $lines = db_unzip("lines", $filename);
323         else
324                 $lines = file("". $filename);
325
326         // parse input file
327         $query_table = '';
328         foreach($lines as $line_no => $line)
329         {
330                 $line = trim($line);
331                 
332                 $line = str_replace("0_", $connection["tbpref"], $line);
333
334                 if ($query_table == '') 
335                 {       // check if line begins with one of allowed queries
336                         foreach($allowed_commands as $cmd => $table) 
337                         {
338                                 if (strtolower(substr($line, 0, strlen($cmd))) == $cmd) 
339                                 {
340                                         $query_table = $table;
341                                         ${$query_table}[] = array('', $line_no+1);
342                                         break;
343                                 }
344                         }
345                  }
346                  if($query_table != '')  // inside allowed query
347                  {
348                         $table = $query_table;
349                         if (substr($line, -1) == ';') // end of query found
350                         {
351                                 $line = substr($line, 0, strlen($line) - 1); // strip ';'
352                                 $query_table = '';
353                         }
354                         ${$table}[count(${$table}) - 1][0] .= $line . "\n";
355                 }
356                 
357         }
358 /*
359         {       // for debugging purposes
360         global $path_to_root;
361         $f = fopen($path_to_root.'/tmp/dbimport.txt', 'w+');
362         fwrite($f, print_r($drop_queries,true) ."\n");
363         fwrite($f, print_r($table_queries,true) ."\n");
364         fwrite($f, print_r($data_queries,true));
365         fclose($f);
366         }
367 */
368         // execute drop tables if exists queries
369         if (is_array($drop_queries))
370         {
371                 foreach($drop_queries as $drop_query)
372                 {
373                         if (!db_query($drop_query[0]))
374                         {
375                                 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force)
376                                         $sql_errors[] = array(db_error_msg($db), $drop_query[1]);
377                         }
378                 }
379         }
380
381         // execute create tables queries
382         if (is_array($table_queries))
383         {
384                 foreach($table_queries as $table_query)
385                 {
386                         if (!db_query($table_query[0]))
387                         {       
388                                 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force) {
389                                         $sql_errors[] = array(db_error_msg($db), $table_query[1]);
390                                 }
391                         }
392                 }
393         }
394
395         // execute insert data queries
396         if (is_array($data_queries))
397         {
398                 foreach($data_queries as $data_query)
399                 {
400                         if (!db_query($data_query[0]))
401                         {
402                                 if (!in_array(db_error_no(),$ignored_mysql_errors) || !$force)
403                                         $sql_errors[] = array(db_error_msg($db), $data_query[1]);
404                         }
405                 }
406         }
407         
408         db_query("SET foreign_key_checks=1");
409
410         if (count($sql_errors)) {
411                 // display first failure message; the rest are probably derivative 
412                 $err = $sql_errors[0];
413                 display_error(sprintf(_("SQL script execution failed in line %d: %s"),
414                         $err[1], $err[0]));
415                 return false;
416         } else
417                 return true;
418 }
419
420 // returns the content of the gziped $path backup file. use of $mode see below
421 function db_ungzip($mode, $path)
422 {
423     $file_data = gzfile($path);
424     // returns one string or an array of lines
425     if ($mode != "lines")
426         return implode("",$file_data);
427     else
428         return $file_data;
429 }
430
431 // returns the content of the ziped $path backup file. use of $mode see below
432 function db_unzip($mode, $path)
433 {
434     $all = false;
435     $all = implode("", file($path));
436
437     // convert path to name of ziped file
438     $filename = preg_replace("/.*\//", "", $path);
439     $filename = substr($filename, 0, strlen($filename) - 4);
440
441     // compare filname in zip and filename from $_GET
442     if (substr($all, 30, strlen($filename)-4) . substr($all, 30+strlen($filename)+9, 4)
443           != $filename) {
444                 return '';     // exit if names differ
445     }
446     else
447     {
448         // get the suffix of the filename in hex
449                 $crc_bugfix = substr($all, 30, strlen($filename)+13);
450         $crc_bugfix = substr(substr($crc_bugfix, 0, strlen($crc_bugfix) - 4), 
451                                 strlen($crc_bugfix) - 12 - 4);
452         $suffix = false;
453         // convert hex to ascii
454         for ($i=0; $i < 12; )
455                 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
456
457         // remove central directory information (we have always just one ziped file)
458         $comp = substr($all, -(strlen($all) - 30 - strlen($filename)-13));
459         $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)-13));
460
461         // fix the crc bugfix (see function save_to_file)
462         $comp = "x\9c" . $comp . $suffix;
463         $file_data = gzuncompress($comp);
464     }
465
466     // returns one string or an array of lines
467     if ($mode != "lines")
468         return $file_data;
469     else
470         return explode("\n", $file_data);
471 }
472
473 function db_backup($conn, $ext='no', $comm='', $tbpref = TB_PREF)
474 {
475         if ($conn['tbpref'] != "")
476                 $filename = $conn['dbname'] . "_" . $conn['tbpref'] . date("Ymd_Hi") . ".sql";
477         else
478                 $filename = $conn['dbname'] . "_" . date("Ymd_Hi") . ".sql";
479
480         return db_export($conn, $filename, $ext, $comm, $tbpref);
481 }
482
483 // generates a dump of $db database
484 // $drop and $zip tell if to include the drop table statement or dry to pack
485 function db_export($conn, $filename, $zip='no', $comment='', $tbpref = TB_PREF, $no_default=false)
486 {
487
488         global $app_title, $version, $power_url, $path_to_root;
489
490     $error = false;
491     // set max string size before writing to file
492     $max_size = 1048576 * 2; // 2 MB
493     // changes max size if value can be retrieved
494     if (ini_get("memory_limit"))
495         $max_size = 900000 * ini_get("memory_limit");
496
497     // set backupfile name
498     if ($zip == "gzip")
499         $backupfile = $filename . ".gz";
500     elseif ($zip == "zip")
501         $backupfile = $filename . ".zip";
502     else
503         $backupfile = $filename;
504     $company = get_company_pref('coy_name', $tbpref);
505
506     //create comment
507     $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
508     $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
509     $out.="# Built by " . $app_title . " " . $version ."\n";
510     $out.="# ".$power_url."\n";
511     $out.="# Company: ". @html_entity_decode($company, ENT_QUOTES, $_SESSION['language']->encoding)."\n";
512     $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
513
514         // write users comment
515         if ($comment)
516         {
517                 $out .= "# Comment:\n";
518                 $comment=preg_replace("'\n'","\n# ","# ".$comment);
519                 //$comment=str_replace("\n", "\n# ", $comment);
520                 foreach(explode("\n",$comment) as $line)
521                         $out .= $line."\n";
522                 $out.="\n";
523         }
524
525     //$out.="use ".$db.";\n"; we don't use this option.
526
527     // get auto_increment values and names of all tables
528     $res = db_query("show table status");
529     $all_tables = array();
530     while($row = db_fetch($res))
531     {
532                 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
533                         ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) === 0))
534                 $all_tables[] = $row;
535     }
536         // get table structures
537         foreach ($all_tables as $table)
538         {
539                 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
540                 $tmp = db_fetch($res1);
541                 $table_sql[$table['Name']] = $tmp["Create Table"];
542         }
543
544         // find foreign keys
545         $fks = array();
546         if (isset($table_sql))
547         {
548                 foreach($table_sql as $tablenme=>$table)
549                 {
550                         $tmp_table=$table;
551                         // save all tables, needed for creating this table in $fks
552                         while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
553                         {
554                                 $tmp_table = substr($tmp_table, $ref_pos + 12);
555                                 $ref_pos = strpos($tmp_table, "(");
556                                 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
557                         }
558                 }
559         }
560         // order $all_tables
561         $all_tables = order_sql_tables($all_tables, $fks);
562
563         // as long as no error occurred
564         if (!$error)
565         {
566                 foreach ($all_tables as $row)
567                 {
568                         $tablename = $row['Name'];
569                         $auto_incr[$tablename] = $row['Auto_increment'];
570
571                         $out.="\n\n";
572                         // export tables
573                         $out.="### Structure of table `".$tablename."` ###\n\n";
574
575                         $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
576                         if ($no_default && ($def_pos = strpos($table_sql[$tablename], "DEFAULT CHARSET")) > 0)
577                                 $table_sql[$tablename] = substr($table_sql[$tablename], 0, $def_pos);
578                         $out.=$table_sql[$tablename];
579
580                         // add auto_increment value
581 //                      if ($auto_incr[$tablename])
582 //                              $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
583                         $out.=" ;";
584                         $out.="\n\n\n";
585
586                         // export data
587                         if (!$error)
588                         {
589                                 $out.="### Data of table `".$tablename."` ###\n\n";
590
591                                 // check if field types are NULL or NOT NULL
592                                 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
593
594                                 $field_null = array();
595                                 for ($j = 0; $j < db_num_rows($res3); $j++)
596                                 {
597                                         $row3 = db_fetch($res3);
598                                         $field_null[] = $row3[2]=='YES' && $row3[4]===null;
599                                 }
600
601                                 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
602                                 for ($j = 0; $j < db_num_rows($res2); $j++)
603                                 {
604                                         $out .= "INSERT INTO `" . $tablename . "` VALUES (";
605                                         $row2 = db_fetch_row($res2);
606                                         // run through each field
607                                         for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
608                                         {
609                                                 $out .= db_escape($row2[$k], $field_null[$k]);
610                                                 if ($k < ($nf - 1))
611                                                         $out .= ", ";
612                                         }
613                                         $out .= ");\n";
614
615                                         // if saving is successful, then empty $out, else set error flag
616                                         if (strlen($out) > $max_size && $zip != "zip")
617                                         {
618                                                 if (save_to_file($backupfile, $zip, $out))
619                                                         $out = "";
620                                                 else
621                                                         $error = true;
622                                         }
623                                 }
624
625                         // an error occurred! Try to delete file and return error status
626                         }
627                         elseif ($error)
628                         {
629                                 @unlink(BACKUP_PATH . $backupfile);
630                                 return false;
631                         }
632
633                         // if saving is successful, then empty $out, else set error flag
634                         if (strlen($out) > $max_size && $zip != "zip")
635                         {
636                                 if (save_to_file($backupfile, $zip, $out))
637                                         $out= "";
638                                 else
639                                         $error = true;
640                         }
641                 }
642
643         // an error occurred! Try to delete file and return error status
644         }
645         else
646         {
647                 @unlink(BACKUP_PATH . $backupfile);
648                 return false;
649         }
650
651         // if (mysql_error()) return "DB_ERROR";
652         //@mysql_close($con);
653
654         //if ($zip == "zip")
655         //      $zip = $time;
656         if (save_to_file($backupfile, $zip, $out))
657         {
658                 $out = "";
659         }
660         else
661         {
662                 @unlink(BACKUP_PATH . $backupfile);
663                 return false;
664         }
665     return $backupfile;
666 }
667
668 // orders the tables in $tables according to the constraints in $fks
669 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
670 function order_sql_tables($tables, $fks)
671 {
672         // do not order if no contraints exist
673         if (!count($fks))
674                 return $tables;
675
676         // order
677         $new_tables = array();
678         $existing = array();
679         $modified = true;
680         while (count($tables) && $modified == true)
681         {
682                 $modified = false;
683             foreach ($tables as $key=>$row)
684             {
685                 // delete from $tables and add to $new_tables
686                 if (isset($fks[$row['Name']]))
687                 {
688                         foreach($fks[$row['Name']] as $needed)
689                         {
690                         // go to next table if not all needed tables exist in $existing
691                         if (!in_array($needed,$existing))
692                                 continue 2;
693                     }
694                 }
695             // delete from $tables and add to $new_tables
696                 $existing[] = $row['Name'];
697                         $new_tables[] = $row;
698             prev($tables);
699             unset($tables[$key]);
700             $modified = true;
701
702             }
703         }
704
705         if (count($tables))
706         {
707             // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
708             // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
709             // until now, just add the lasting tables to $new_tables, return them and print a warning
710             foreach($tables as $row)
711                 $new_tables[] = $row;
712             echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
713         }
714         return $new_tables;
715 }
716
717 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
718 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
719 function save_to_file($backupfile, $zip, $fileData)
720 {
721         global $path_to_root;
722
723     if ($zip == "gzip")
724     {
725         if ($zp = @gzopen(BACKUP_PATH . $backupfile, "a9"))
726         {
727                         @gzwrite($zp, $fileData);
728                         @gzclose($zp);
729                         return true;
730         }
731         else
732         {
733                 return false;
734         }
735
736     // $zip contains the timestamp
737     }
738     elseif ($zip == "zip")
739     {
740         // based on zip.lib.php 2.2 from phpMyBackupAdmin
741         // offical zip format: http://www.pkware.com/appnote.txt
742
743         // End of central directory record
744         $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
745
746         // "local file header" segment
747         $unc_len = strlen($fileData);
748         $crc = crc32($fileData);
749         $zdata = gzcompress($fileData);
750
751                 // extend stored file name with suffix
752         // needed for decoding (because of crc bug)
753         $name_suffix = substr($zdata, -4, 4);
754         $name_suffix2 = "_";
755         for ($i = 0; $i < 4; $i++)
756                 $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
757
758         $name = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql";
759
760         // fix crc bug
761         $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
762         $c_len = strlen($zdata);
763
764         // dos time
765         $timearray = getdate($zip);
766         $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
767             ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
768         $dtime = dechex($dostime);
769         $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
770         eval('$hexdtime="' . $hexdtime . '";');
771
772         // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
773         $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
774
775         // crc32, compressed filesize, uncompressed filesize
776         $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
777
778         $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
779
780         // length of filename, extra field length
781         $fr .= pack('v', strlen($name)) . pack('v', 0);
782         $fr .= $name;
783
784         // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
785         $fr .= $zdata . $sub2;
786
787         // now add to central directory record
788         $cdrec = "\x50\x4b\x01\x02";
789         $cdrec .= "\x00\x00";                // version made by
790         $cdrec .= $sub1 . $sub2;
791
792          // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
793         $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
794         $cdrec .= $name;
795
796         // combine data
797         $fileData = $fr . $cdrec . $eof_ctrl_dir;
798
799         // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
800         $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
801
802         if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
803         {
804                         @fwrite($zp, $fileData);
805                         @fclose($zp);
806                         return true;
807         }
808         else
809         {
810                 return false;
811         }
812
813         // uncompressed
814     }
815     else
816     {
817         if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
818         {
819                         @fwrite($zp, $fileData);
820                         @fclose($zp);
821                         return true;
822         }
823         else
824         {
825                 return false;
826         }
827     }
828 }
829
830 function create_comp_dirs($comp_path, $comp_subdirs)
831 {
832                 $index = "<?php\nheader(\"Location: ../index.php\");\n?>";
833             $cdir = $comp_path;
834             @mkdir($cdir);
835                 $f = @fopen("$cdir/index.php", "wb");
836                 @fwrite($f, $index);
837                 @fclose($f);
838
839             foreach($comp_subdirs as $dir)
840             {
841                         @mkdir($cdir.'/'.$dir);
842                         $f = @fopen("$cdir/$dir/index.php", "wb");
843                         @fwrite($f, $index);
844                         @fclose($f);
845             }
846 }
847 ?>