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