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