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