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