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