Merged changes form stabel branch up to the current state (2.3.22+).
[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 define('EXPORT_MAX_INSERT', 50000);
22
23 function array_natsort($aryData, $strIndex, $strSortBy, $strSortType=false)
24 {
25    //    if the parameters are invalid
26    if (!is_array($aryData) || !$strSortBy)
27        //    return the array
28        return $aryData;
29
30    //    create our temporary arrays
31    $arySort = $aryResult = array();
32
33    //    loop through the array
34    foreach ($aryData as $key => $aryRow)
35        //    set up the value in the array
36        $arySort[$strIndex ? $aryRow[$strIndex] : $key] = $aryRow[$strSortBy];
37
38    //    apply the natural sort
39    natsort($arySort);
40
41    //    if the sort type is descending
42    if ($strSortType=="desc")
43        //    reverse the array
44        arsort($arySort);
45
46    //    loop through the sorted and original data
47                 foreach ($arySort as $arySortKey => $arySorted)
48                         if($strIndex) 
49                         {
50                                 foreach ($aryData as $aryOriginal)
51                                 // if the key matches
52                                         if ($aryOriginal[$strIndex]==$arySortKey)
53                                                 // add it to the output array
54                                                 array_push($aryResult, $aryOriginal);
55                         } else
56                                 $aryResult[$arySortKey] = $aryData[$arySortKey];
57    //    return the return
58    return $aryResult;
59 }
60
61 function update_admin_password($conn, $password)
62 {
63         $sql = "UPDATE ".$conn['tbpref']."users SET password=".db_escape($password) . "
64                 WHERE user_id='admin'";
65         db_query($sql, "could not update user password for 'admin'");
66 }
67
68 function write_config_db($new = false)
69 {
70         global $path_to_root, $def_coy, $db_connections, $tb_pref_counter;
71
72         if ($new)
73                 $tb_pref_counter++;
74         $n = count($db_connections);
75         $msg = "<?php\n\n";
76         $msg .= "/*Connection Information for the database\n";
77         $msg .= "\$def_coy - the default company that is pre-selected on login\n\n";
78         $msg .= "'host' - 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";
79         $msg .= "'dbuser' - the user name under which the company database should be accessed.\n";
80         $msg .= "  NB it is not secure to use root as the dbuser with no password - a user with appropriate privileges must be set up.\n\n";
81         $msg .= "'dbpassword' - the password required for the dbuser to authorise the above database user.\n\n";
82         $msg .= "'dbname' - 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";
83         $msg .= "'tbpref' - prefix on table names, or '' if not used. Always use non-empty prefixes if multiply company use the same database.\n";
84         $msg .= "*/\n\n\n";
85
86         $msg .= "\$def_coy = " . $def_coy . ";\n\n";
87         $msg .= "\$tb_pref_counter = " . $tb_pref_counter . ";\n\n";
88         $msg .= "\$db_connections = " .var_export($db_connections, true);
89         $msg .= ";\n?>";
90
91         $filename = $path_to_root . "/config_db.php";
92         // Check if the file exists and is writable first.
93         if ((!file_exists($filename) && is_writable($path_to_root)) || is_writable($filename))
94         {
95                 if (!$zp = fopen($filename, 'w'))
96                 {
97                         return -1;
98                 }
99                 else
100                 {
101                         if (!fwrite($zp, $msg))
102                         {
103                                 fclose($zp);
104                                 return -2;
105                         }
106                         // Close file
107                         fclose($zp);
108                 }
109         }
110         else
111         {
112                 return -3;
113         }
114         return 0;
115 }
116
117 function write_extensions($extensions=null, $company = -1)
118 {
119         global $path_to_root, $installed_extensions, $next_extension_id;
120
121         if (!isset($extensions)) {
122                 $extensions = $installed_extensions;
123         }
124         if (!isset($next_extension_id)) {
125                 $next_extension_id = 1;
126         }
127
128         $msg = "<?php\n\n";
129         if ($company == -1)
130                 $msg .=
131 "/* List of installed additional extensions. If extensions are added to the list manually
132         make sure they have unique and so far never used extension_ids as a keys,
133         and \$next_extension_id is also updated. More about format of this file yo will find in 
134         FA extension system documentation.
135 */
136 \n\$next_extension_id = $next_extension_id; // unique id for next installed extension\n\n";
137         else 
138                 $msg .=
139 "/*
140         Do not edit this file manually. This copy of global file is overwritten
141         by extensions editor.
142 */\n\n";
143
144         $msg .= "\$installed_extensions = ". var_export($extensions, true);
145         $msg .= ";\n?>";
146         $filename = $path_to_root . ($company==-1 ? '' : '/company/'.$company)
147                 .'/installed_extensions.php';
148
149         // Check if the file is writable first.
150         if (!$zp = @fopen($filename, 'w'))
151         {
152                 display_error(sprintf(_("Cannot open the extension setup file '%s' for writing."),
153                          $filename));
154                 return false;
155         }
156         else
157         {
158                 if (!fwrite($zp, $msg))
159                 {
160                         display_error(sprintf(_("Cannot write to the extensions setup file '%s'."),
161                                 $filename));
162                         fclose($zp);
163                         return false;
164                 }
165                 // Close file
166                 fclose($zp);
167         }
168         return true;
169 }
170 //---------------------------------------------------------------------------------------------
171 //
172 // Update per-company list of installed extensions
173 //
174 function update_extensions($extensions) {
175         global $db_connections;
176         
177         if (!write_extensions($extensions)) {
178                 display_notification(_("Cannot update system extensions list."));
179                 return false;
180         }
181
182         // update per company files
183         $cnt = max(1, count($db_connections));
184         for($i = 0; $i < $cnt; $i++) 
185         {
186                 $newexts = $extensions;
187                 // update 'active' status 
188                 $exts = get_company_extensions($i);
189                 foreach ($exts as $key => $ext) 
190                 {
191                         if (isset($newexts[$key]))
192                                 $newexts[$key]['active'] = $exts[$key]['active'];
193                 }
194                 if(!write_extensions($newexts, $i)) 
195                 {
196                         display_notification(sprintf(_("Cannot update extensions list for company '%s'."),
197                                 $db_connections[$i]['name']));
198                  return false;
199                 }
200         }
201         return true;
202 }
203
204
205 function write_lang()
206 {
207         global $path_to_root, $installed_languages, $dflt_lang;
208
209         $installed_languages = array_natsort($installed_languages, 'code', 'code');
210         $n = count($installed_languages);
211         $msg = "<?php\n\n";
212
213         $msg .= "/* How to make new entries here for non-packaged languages:\n\n";
214         $msg .= "-- 'code' should match the name of the directory for the language under \\lang\n.";
215         $msg .= "-- 'name' is the name that will be displayed in the language selection list (in Users and Display Setup)\n";
216         $msg .= "-- 'rtl' only needs to be set for right-to-left languages like Arabic and Hebrew\n";
217         $msg .= "-- 'encoding' used in translation file\n";
218         $msg .= "-- 'version' always set to '' for manually installed languages.\n";
219         $msg .= "-- 'path' installation path related to FA root (e.g. 'lang/en_US').\n";
220         $msg .= "*/\n\n\n";
221
222         $msg .= "\$installed_languages = " . var_export($installed_languages, true);
223         $msg .= ";\n";
224         $msg .= "\n\$dflt_lang = '$dflt_lang';\n?>\n";
225
226         $path = $path_to_root . "/lang";
227         $filename = $path.'/installed_languages.inc';
228         // Check if directory exists and is writable first.
229         if (file_exists($path) && is_writable($path))
230         {
231                 if (!$zp = fopen($filename, 'w'))
232                 {
233                         display_error(_("Cannot open the languages file - ") . $filename);
234                         return false;
235                 }
236                 else
237                 {
238                         if (!fwrite($zp, $msg))
239                         {
240                                 display_error(_("Cannot write to the language file - ") . $filename);
241                                 fclose($zp);
242                                 return false;
243                         }
244                         // Close file
245                         fclose($zp);
246                 }
247         }
248         else
249         {
250                 display_error(_("The language files folder ") . $path . _(" is not writable. Change its permissions so it is, then re-run the operation."));
251                 return false;
252         }
253         return true;
254 }
255 /*
256         Database import:
257                 $filename - sql file name
258                 $connection - database connection
259                 $force - ignore duplicate errors
260                 $init - presume $filename is initialization file with '0_' prefix
261                 $protect - protect users/roles 
262                 $return_errors - return errors instead of display them
263 */
264 function db_import($filename, $connection, $force=true, $init=true, $protect=false, $return_errors=false)
265 {
266         global $db, $go_debug, $sql_trail;
267
268         $sql_trail = false;
269
270         $allowed_commands = array(
271                 "create"  => 'table_queries', 
272                 "delimiter" => 'table_queries',
273                 "alter table" => 'table_queries', 
274                 "insert" => 'data_queries', 
275                 "update" => 'data_queries', 
276                 "set names" => 'set_names',
277                 "drop table if exists" => 'drop_queries',
278                 "drop function if exists" => 'drop_queries',
279                 "drop trigger if exists" => 'drop_queries',
280                 );
281
282         $protected = array(
283                 'security_roles',
284                 'users'
285         );
286
287         $ignored_mysql_errors = array( //errors ignored in normal (non forced) mode
288                 '1022', // duplicate key
289                 '1050', // Table %s already exists
290                 '1060', // duplicate column name
291                 '1061', // duplicate key name
292                 '1062', // duplicate key entry
293                 '1091'  // can't drop key/column check if exists
294         );
295
296         $set_names = array();
297         $data_queries = array();
298         $drop_queries = array();
299         $table_queries = array();
300         $sql_errors = array();
301
302         $old_encoding = db_get_charset($db);
303
304         ini_set("max_execution_time", "180");
305         db_query("SET foreign_key_checks=0");
306         $check_line_len = false;
307         // uncrompress gziped backup files
308         if (strpos($filename, ".gz") || strpos($filename, ".GZ"))
309         {       $lines = db_ungzip("lines", $filename);
310                 $check_line_len = true;
311         } elseif (strpos($filename, ".zip") || strpos($filename, ".ZIP"))
312                 $lines = db_unzip("lines", $filename);
313         else
314                 $lines = file("". $filename);
315
316         // parse input file
317         $query_table = '';
318         $delimiter = ';';
319
320         foreach($lines as $line_no => $line)
321         {
322                 $gzfile_bug = $check_line_len && (strlen($line) == 8190); // there is a bug in php (at least 4.1.1-5.5.9) gzfile which limits line length to 8190 bytes!
323
324                 $line = trim($line);
325                 if ($init)
326                         $line = str_replace("0_", $connection["tbpref"], $line);
327
328                 if ($query_table == '') 
329                 {       // check if line begins with one of allowed queries
330                         foreach($allowed_commands as $cmd => $table) 
331                         {
332                                 if (strtolower(substr($line, 0, strlen($cmd))) == $cmd) 
333                                 {
334                                         if ($cmd == 'delimiter') {
335                                                 $delimiter = trim(substr($line, 10));
336                                                 continue 2;
337                                         }
338                                         $query_table = $table;
339                                         $skip = false;
340                                         if ($protect)
341                                         {
342                                                 foreach($protected as $protbl)
343                                                         if (strpos($line, $connection["tbpref"].$protbl) !== false)
344                                                         {
345                                                                 $skip = true; break;
346                                                         }
347                                         }
348                                         if (!$skip)
349                                                 ${$query_table}[] = array('', $line_no+1);
350                                         break;
351                                 }
352                         }
353                  }
354                  if($query_table != '')  // inside allowed query
355                  {
356                         $table = $query_table;
357                         if (!$gzfile_bug && substr($line, -strlen($delimiter)) == $delimiter) // end of query found 
358                         {
359                                 $line = substr($line, 0, strlen($line) - strlen($delimiter)); // strip delimiter
360                                 $query_table = '';
361                         }
362                         if (!$skip)
363                                 ${$table}[count(${$table}) - 1][0] .= $line . "\n";
364                 }
365
366         }
367
368         //
369         // 'set names' or equivalents should be used only on post 2.3 FA versions
370         // otherwise text encoding can be broken during import
371         //
372         $encoding = null; // UI encoding for default site language is the default
373         $new_db = $init || db_fixed();
374         $new_file = count($set_names);
375         if ($new_db)
376         {
377                 if ($new_file)
378                 {
379                         if (count($set_names)) // standard db restore
380                         {
381                                 if (preg_match('/set\s*names\s*[\']?(\w*)[\']?/i', $set_names[0][0], $match))
382                                         $encoding = $match[1];
383                         }
384                         // otherwise use default site ui encoding
385                 }
386         }
387         else
388         {
389                 if ($new_file) // import on old db is forbidden: this would destroy db content unless latin1 was used before in UI
390                 {
391                         $msg = _("This is new format backup file which cannot be restored on database not migrated to utf8.");
392                         if ($return_errors)
393                                 return $msg;
394                         else
395                                 display_error($msg);
396                         return false;
397                 }
398                  else   // backup restore during upgrade failure
399                         $encoding = 'latin1'; // standard encoding on mysql client
400         }
401
402         db_set_charset($db, $encoding);
403
404 /*/     {       // for debugging purposes
405         global $path_to_root;
406         $f = fopen($path_to_root.'/tmp/dbimport.txt', 'w+');
407         fwrite($f, print_r($set_names,true) ."\n");
408         fwrite($f, print_r($drop_queries,true) ."\n");
409         fwrite($f, print_r($table_queries,true) ."\n");
410         fwrite($f, print_r($data_queries,true));
411         fclose($f);
412         }
413 /*/
414         if ($return_errors)
415         {       // prevent errors display
416                 $save_debug = $go_debug;
417                 $go_debug = 0;
418         }
419         // execute drop tables if exists queries
420         if (is_array($drop_queries))
421         {
422                 foreach($drop_queries as $drop_query)
423                 {
424                         if (!db_query($drop_query[0]))
425                         {
426                                 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force)
427                                         $sql_errors[] = array(db_error_msg($db), $drop_query[1]);
428                         }
429                 }
430         }
431
432         // execute create tables queries
433         if (is_array($table_queries))
434         {
435                 foreach($table_queries as $table_query)
436                 {
437                         if (!db_query($table_query[0]))
438                         {       
439                                 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force) {
440                                         $sql_errors[] = array(db_error_msg($db), $table_query[1]);
441                                 }
442                         }
443                 }
444         }
445
446         // execute insert data queries
447         if (is_array($data_queries))
448         {
449                 foreach($data_queries as $data_query)
450                 {
451                         if (!db_query($data_query[0]))
452                         {
453                                 if (!in_array(db_error_no(),$ignored_mysql_errors) || !$force)
454                                         $sql_errors[] = array(db_error_msg($db), $data_query[1]);
455                         }
456                 }
457         }
458
459         if ($return_errors)
460                 $go_debug = $save_debug;
461
462         db_query("SET foreign_key_checks=1");
463         if ($delimiter != ';') db_query("delimiter ;"); // just for any case
464
465         db_set_charset($db, $old_encoding); // restore connection encoding
466
467         if (count($sql_errors)) {
468                 if ($return_errors)
469                         return $sql_errors;
470
471                 // display first failure message; the rest are probably derivative 
472                 $err = $sql_errors[0];
473                 display_error(sprintf(_("SQL script execution failed in line %d: %s"),
474                         $err[1], $err[0]));
475                 return false;
476         } else
477                 return true;
478 }
479
480 // returns the content of the gziped $path backup file. use of $mode see below
481 function db_ungzip($mode, $path)
482 {
483     $file_data = gzfile($path);
484     // returns one string or an array of lines
485     if ($mode != "lines")
486         return implode("",$file_data);
487     else
488         return $file_data;
489 }
490
491 // returns the content of the ziped $path backup file. use of $mode see below
492 function db_unzip($mode, $path)
493 {
494     $all = false;
495     $all = implode("", file($path));
496
497     // convert path to name of ziped file
498     $filename = preg_replace("/.*\//", "", $path);
499     $filename = substr($filename, 0, strlen($filename) - 4);
500
501     // compare filname in zip and filename from $_GET
502     if (substr($all, 30, strlen($filename)-4) . substr($all, 30+strlen($filename)+9, 4)
503           != $filename) {
504                 return '';     // exit if names differ
505     }
506     else
507     {
508         // get the suffix of the filename in hex
509                 $crc_bugfix = substr($all, 30, strlen($filename)+13);
510         $crc_bugfix = substr(substr($crc_bugfix, 0, strlen($crc_bugfix) - 4), 
511                                 strlen($crc_bugfix) - 12 - 4);
512         $suffix = false;
513         // convert hex to ascii
514         for ($i=0; $i < 12; )
515                 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
516
517         // remove central directory information (we have always just one ziped file)
518         $comp = substr($all, -(strlen($all) - 30 - strlen($filename)-13));
519         $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)-13));
520
521         // fix the crc bugfix (see function save_to_file)
522         $comp = "x\9c" . $comp . $suffix;
523         $file_data = gzuncompress($comp);
524     }
525
526     // returns one string or an array of lines
527     if ($mode != "lines")
528         return $file_data;
529     else
530         return explode("\n", $file_data);
531 }
532
533 function db_backup($conn, $ext='no', $comm='', $path=null)
534 {
535         if ($conn['tbpref'] != "")
536                 $filename = $conn['dbname'] . "_" . $conn['tbpref'] . date("Ymd_Hi") . ".sql";
537         else
538                 $filename = $conn['dbname'] . "_" . date("Ymd_Hi") . ".sql";
539
540         if (!isset($path))
541                 $path = BACKUP_PATH;
542
543         return db_export($conn, $path . clean_file_name($filename), $ext, $comm);
544 }
545 //
546 // Generates a dump of $db database
547 //
548 function db_export($conn, $filename, $zip='no', $comment='')
549 {
550
551         global $app_title, $version, $power_url, $path_to_root;
552
553     $error = false;
554     // set max string size before writing to file
555     $max_size = 1048576 * 2; // 2 MB
556     // changes max size if value can be retrieved
557     if (ini_get("memory_limit"))
558         $max_size = 900000 * ini_get("memory_limit");
559
560     // set backupfile name
561     if ($zip == "gzip")
562         $backupfile = $filename . ".gz";
563     elseif ($zip == "zip")
564         $backupfile = $filename . ".zip";
565     else
566         $backupfile = $filename;
567     $company = $conn['name']; // get_company_pref('coy_name');
568
569         if (file_exists($backupfile))   // prevent appends
570                 unlink($backupfile);
571
572     //create comment
573     $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
574     $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
575     $out.="# Built by " . $app_title . " " . $version ."\n";
576     $out.="# ".$power_url."\n";
577     $out.="# Company: ". @html_entity_decode($company, ENT_QUOTES, $_SESSION['language']->encoding)."\n";
578     $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
579     $out.="# Compatibility: ".get_company_pref('version_id')."\n\n";
580
581         // write users comment
582         if ($comment)
583         {
584                 $out .= "# Comment:\n";
585                 $comment=preg_replace("'\n'","\n# ","# ".$comment);
586                 //$comment=str_replace("\n", "\n# ", $comment);
587                 foreach(explode("\n",$comment) as $line)
588                         $out .= $line."\n";
589                 $out.="\n";
590         }
591
592     //$out.="use ".$db.";\n"; we don't use this option.
593
594         if (db_fixed())
595         {
596                 db_set_encoding();
597                 if ($mysql_enc = get_mysql_encoding_name($_SESSION['language']->encoding))
598                         $out .= "\nSET NAMES $mysql_enc;\n";
599         }
600     // get auto_increment values and names of all tables
601     $res = db_query("show table status");
602     $all_tables = array();
603     while($row = db_fetch($res))
604     {
605                 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
606                         ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) === 0))
607                 $all_tables[] = $row;
608     }
609         // get table structures
610         foreach ($all_tables as $table)
611         {
612                 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
613                 $tmp = db_fetch($res1);
614                 $table_sql[$table['Name']] = $tmp["Create Table"];
615         }
616
617         // find foreign keys
618         $fks = array();
619         if (isset($table_sql))
620         {
621                 foreach($table_sql as $tablenme=>$table)
622                 {
623                         $tmp_table=$table;
624                         // save all tables, needed for creating this table in $fks
625                         while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
626                         {
627                                 $tmp_table = substr($tmp_table, $ref_pos + 12);
628                                 $ref_pos = strpos($tmp_table, "(");
629                                 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
630                         }
631                 }
632         }
633         // order $all_tables
634         $all_tables = order_sql_tables($all_tables, $fks);
635
636         // as long as no error occurred
637         if (!$error)
638         {
639                 foreach ($all_tables as $row)
640                 {
641                         $tablename = $row['Name'];
642                         $auto_incr[$tablename] = $row['Auto_increment'];
643
644                         $out.="\n\n";
645                         // export tables
646                         $out.="### Structure of table `".$tablename."` ###\n\n";
647
648                         $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
649                         $out.=$table_sql[$tablename];
650
651                         // add auto_increment value
652 //                      if ($auto_incr[$tablename])
653 //                              $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
654                         $out.=" ;";
655                         $out.="\n\n";
656
657                         // export data
658                         if (!$error)
659                         {
660                                 $out.="### Data of table `".$tablename."` ###\n";
661
662                                 // check if field types are NULL or NOT NULL
663                                 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
664
665                                 $field_null = array();
666                                 for ($j = 0; $j < db_num_rows($res3); $j++)
667                                 {
668                                         $row3 = db_fetch($res3);
669                                         $field_null[] = $row3[2]=='YES' && $row3[4]===null;
670                                 }
671
672                                 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
673                                 $maxinsert = 0;
674                                 $insert = '';
675                                 for ($j = 0; $j < db_num_rows($res2); $j++)
676                                 {
677                                         $row2 = db_fetch_row($res2);
678                                         $values = '(';
679                                         for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
680                                         {
681                                                 $values .= db_escape($row2[$k], $field_null[$k]);
682                                                 if ($k < ($nf - 1))
683                                                         $values .= ', ';
684                                         }
685                                         $values .= ')';
686                                         $len = strlen($values);
687                                         if ($maxinsert < $len+1)
688                                         {
689                                                 $maxinsert = EXPORT_MAX_INSERT;
690                                                 if ($insert)
691                                                 {
692                                                         $out .= $insert .';'; // flush insert query
693                                                         $insert = '';
694                                                 }
695                                         }
696
697                                         if ($insert == '')
698                                         {
699                                                 $insert = "\nINSERT INTO `" . $tablename . "` VALUES\n";
700                                                 $maxinsert -= strlen($insert);
701                                         } else {
702                                                 $insert .= ",\n";
703                                         }
704
705                                         $maxinsert -= $len;
706                                         $insert .= $values;
707
708                                         // if saving is successful, then empty $out, else set error flag
709                                         if (strlen($out) > $max_size && $zip != "zip")
710                                         {
711                                                 if (save_to_file($backupfile, $zip, $out))
712                                                         $out = "";
713                                                 else
714                                                         $error = true;
715                                         }
716                                 }
717                                 if ($insert)
718                                         $out .= $insert. ';';
719                         // an error occurred! Try to delete file and return error status
720                         }
721                         elseif ($error)
722                         {
723                                 @unlink($backupfile);
724                                 return false;
725                         }
726
727                         // if saving is successful, then empty $out, else set error flag
728                         if (strlen($out) > $max_size && $zip != "zip")
729                         {
730                                 if (save_to_file($backupfile, $zip, $out))
731                                         $out= "";
732                                 else
733                                         $error = true;
734                         }
735                 }
736
737         // an error occurred! Try to delete file and return error status
738         }
739         else
740         {
741                 @unlink($backupfile);
742                 return false;
743         }
744
745         //if ($zip == "zip")
746         //      $zip = $time;
747         if (save_to_file($backupfile, $zip, $out))
748         {
749                 $out = "";
750         }
751         else
752         {
753                 @unlink($backupfile);
754                 return false;
755         }
756     return $backupfile;
757 }
758
759 // orders the tables in $tables according to the constraints in $fks
760 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
761 function order_sql_tables($tables, $fks)
762 {
763         // do not order if no contraints exist
764         if (!count($fks))
765                 return $tables;
766
767         // order
768         $new_tables = array();
769         $existing = array();
770         $modified = true;
771         while (count($tables) && $modified == true)
772         {
773                 $modified = false;
774             foreach ($tables as $key=>$row)
775             {
776                 // delete from $tables and add to $new_tables
777                 if (isset($fks[$row['Name']]))
778                 {
779                         foreach($fks[$row['Name']] as $needed)
780                         {
781                         // go to next table if not all needed tables exist in $existing
782                         if (!in_array($needed,$existing))
783                                 continue 2;
784                     }
785                 }
786             // delete from $tables and add to $new_tables
787                 $existing[] = $row['Name'];
788                         $new_tables[] = $row;
789             prev($tables);
790             unset($tables[$key]);
791             $modified = true;
792
793             }
794         }
795
796         if (count($tables))
797         {
798             // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
799             // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
800             // until now, just add the lasting tables to $new_tables, return them and print a warning
801             foreach($tables as $row)
802                 $new_tables[] = $row;
803             echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
804         }
805         return $new_tables;
806 }
807
808 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
809 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
810 function save_to_file($path, $zip, $fileData)
811 {
812         global $path_to_root;
813
814         $backupfile = basename($path);
815
816     if ($zip == "gzip")
817     {
818         if ($zp = @gzopen($path, "a9"))
819         {
820                         @gzwrite($zp, $fileData);
821                         @gzclose($zp);
822                         return true;
823         }
824         else
825         {
826                 return false;
827         }
828
829     // $zip contains the timestamp
830     }
831     elseif ($zip == "zip")
832     {
833         // based on zip.lib.php 2.2 from phpMyBackupAdmin
834         // offical zip format: http://www.pkware.com/appnote.txt
835
836         // End of central directory record
837         $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
838
839         // "local file header" segment
840         $unc_len = strlen($fileData);
841         $crc = crc32($fileData);
842         $zdata = gzcompress($fileData);
843
844                 // extend stored file name with suffix
845         // needed for decoding (because of crc bug)
846         $name_suffix = substr($zdata, -4, 4);
847         $name_suffix2 = "_";
848         for ($i = 0; $i < 4; $i++)
849                 $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
850
851         $name = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql";
852
853         // fix crc bug
854         $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
855         $c_len = strlen($zdata);
856
857         // dos time
858         $timearray = getdate();
859         $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
860             ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
861         $dtime = dechex($dostime);
862         $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
863         eval('$hexdtime="' . $hexdtime . '";');
864
865         // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
866         $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
867
868         // crc32, compressed filesize, uncompressed filesize
869         $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
870
871         $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
872
873         // length of filename, extra field length
874         $fr .= pack('v', strlen($name)) . pack('v', 0);
875         $fr .= $name;
876
877         // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
878         $fr .= $zdata . $sub2;
879
880         // now add to central directory record
881         $cdrec = "\x50\x4b\x01\x02";
882         $cdrec .= "\x00\x00";                // version made by
883         $cdrec .= $sub1 . $sub2;
884
885          // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
886         $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
887         $cdrec .= $name;
888
889         // combine data
890         $fileData = $fr . $cdrec . $eof_ctrl_dir;
891
892         // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
893         $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
894
895         if ($zp = @fopen($path, "w"))
896         {
897                         @fwrite($zp, $fileData);
898                         @fclose($zp);
899                         return true;
900         }
901         else
902         {
903                 return false;
904         }
905
906         // uncompressed
907     }
908     else
909     {
910         if ($zp = @fopen($path, "a"))
911         {
912                         @fwrite($zp, $fileData);
913                         @fclose($zp);
914                         return true;
915         }
916         else
917         {
918                 return false;
919         }
920     }
921 }
922
923 function create_comp_dirs($comp_path, $comp_subdirs)
924 {
925                 $index = "<?php\nheader(\"Location: ../index.php\");\n?>";
926             $cdir = $comp_path;
927             @mkdir($cdir);
928                 $f = @fopen("$cdir/index.php", "wb");
929                 @fwrite($f, $index);
930                 @fclose($f);
931
932             foreach($comp_subdirs as $dir)
933             {
934                         @mkdir($cdir.'/'.$dir);
935                         $f = @fopen("$cdir/$dir/index.php", "wb");
936                         @fwrite($f, $index);
937                         @fclose($f);
938             }
939 }
940
941 //
942 //      Checks $field existence in $table with given field $properties
943 //      $table - table name without prefix
944 //  $field -  optional field name
945 //  $properties - optional properties of field defined by MySQL:
946 //              'Type', 'Null', 'Key', 'Default', 'Extra'
947 //
948 function check_table($pref, $table, $field=null, $properties=null)
949 {
950         $tables = @db_query("SHOW TABLES LIKE '".$pref.$table."'");
951         if (!db_num_rows($tables))
952                 return 1;               // no such table or error
953
954         $fields = @db_query("SHOW COLUMNS FROM ".$pref.$table);
955         if (!isset($field)) 
956                 return 0;               // table exists
957
958         while( $row = db_fetch_assoc($fields)) 
959         {
960                 if ($row['Field'] == $field) 
961                 {
962                         if (!isset($properties)) 
963                                 return 0;
964                         foreach($properties as $property => $value) 
965                         {
966                                 if ($row[$property] != $value) 
967                                         return 3;       // failed type/length check
968                         }
969                         return 0; // property check ok.
970                 }
971         }
972         return 2; // field not found
973 }
974
975 /*
976         Update or create setting in simple php config file.
977 */
978 function update_config_var($file, $variable, $value, $comment='')
979 {
980         if (!is_file($file) || !is_writeable($file))
981                 return false;
982         $content = file_get_contents($file);
983         $strvalue = '$'."$variable = ".var_export($value, true).';';
984         $pattern = '/'.preg_quote('$'.$variable).'\s*=\s*[^;]*;/m';
985         $content = preg_replace($pattern, $strvalue, $content, -1, $result);
986         if (!$result)
987         {
988                 $strvalue = ($comment ? "// $comment" : '') ."\n$strvalue\n";
989                 $content = preg_replace('/\?>\s*/m', $strvalue, $content, -1, $result);
990                 if (!$result)
991                         $content .= $strvalue;
992         }
993
994         return file_put_contents($file, $content)!=false;
995 }
996
997
998 ?>