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