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 ***********************************************************************/
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
21 define('EXPORT_MAX_INSERT', 50000);
23 function array_natsort($aryData, $strIndex, $strSortBy, $strSortType=false)
25 // if the parameters are invalid
26 if (!is_array($aryData) || !$strSortBy)
30 // create our temporary arrays
31 $arySort = $aryResult = array();
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];
38 // apply the natural sort
41 // if the sort type is descending
42 if ($strSortType=="desc")
46 // loop through the sorted and original data
47 foreach ($arySort as $arySortKey => $arySorted)
50 foreach ($aryData as $aryOriginal)
52 if ($aryOriginal[$strIndex]==$arySortKey)
53 // add it to the output array
54 array_push($aryResult, $aryOriginal);
56 $aryResult[$arySortKey] = $aryData[$arySortKey];
61 function update_admin_password($conn, $password)
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'");
68 function write_config_db($new = false)
70 global $path_to_root, $def_coy, $db_connections, $tb_pref_counter;
74 $n = count($db_connections);
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";
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);
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))
95 if (!$zp = fopen($filename, 'w'))
101 if (!fwrite($zp, $msg))
117 function write_extensions($extensions=null, $company = -1)
119 global $path_to_root, $installed_extensions, $next_extension_id;
121 if (!isset($extensions)) {
122 $extensions = $installed_extensions;
124 if (!isset($next_extension_id)) {
125 $next_extension_id = 1;
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.
136 \n\$next_extension_id = $next_extension_id; // unique id for next installed extension\n\n";
140 Do not edit this file manually. This copy of global file is overwritten
141 by extensions editor.
144 $msg .= "\$installed_extensions = ". var_export($extensions, true);
146 $filename = $path_to_root . ($company==-1 ? '' : '/company/'.$company)
147 .'/installed_extensions.php';
149 // Check if the file is writable first.
150 if (!$zp = @fopen($filename, 'w'))
152 display_error(sprintf(_("Cannot open the extension setup file '%s' for writing."),
158 if (!fwrite($zp, $msg))
160 display_error(sprintf(_("Cannot write to the extensions setup file '%s'."),
170 //---------------------------------------------------------------------------------------------
172 // Update per-company list of installed extensions
174 function update_extensions($extensions) {
175 global $db_connections;
177 if (!write_extensions($extensions)) {
178 display_notification(_("Cannot update system extensions list."));
182 // update per company files
183 $cnt = max(1, count($db_connections));
184 for($i = 0; $i < $cnt; $i++)
186 $newexts = $extensions;
187 // update 'active' status
188 $exts = get_company_extensions($i);
189 foreach ($exts as $key => $ext)
191 if (isset($newexts[$key]))
192 $newexts[$key]['active'] = $exts[$key]['active'];
194 if(!write_extensions($newexts, $i))
196 display_notification(sprintf(_("Cannot update extensions list for company '%s'."),
197 $db_connections[$i]['name']));
205 function write_lang()
207 global $path_to_root, $installed_languages, $dflt_lang;
209 $installed_languages = array_natsort($installed_languages, 'code', 'code');
210 $n = count($installed_languages);
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";
222 $msg .= "\$installed_languages = " . var_export($installed_languages, true);
224 $msg .= "\n\$dflt_lang = '$dflt_lang';\n?>\n";
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))
231 if (!$zp = fopen($filename, 'w'))
233 display_error(_("Cannot open the languages file - ") . $filename);
238 if (!fwrite($zp, $msg))
240 display_error(_("Cannot write to the language file - ") . $filename);
250 display_error(_("The language files folder ") . $path . _(" is not writable. Change its permissions so it is, then re-run the operation."));
256 function db_import($filename, $connection, $force=true)
258 global $db, $go_debug, $sql_trail;
262 $allowed_commands = array(
263 "create" => 'table_queries',
264 "delimiter" => 'table_queries',
265 "alter table" => 'table_queries',
266 "insert" => 'data_queries',
267 "update" => 'data_queries',
268 "drop table if exists" => 'drop_queries',
269 "drop function if exists" => 'drop_queries',
270 "drop trigger if exists" => 'drop_queries',
272 $ignored_mysql_errors = array( //errors ignored in normal (non forced) mode
273 '1022', // duplicate key
274 '1050', // Table %s already exists
275 '1060', // duplicate column name
276 '1061', // duplicate key name
277 '1062', // duplicate key entry
278 '1091' // can't drop key/column check if exists
280 $data_queries = array();
281 $drop_queries = array();
282 $table_queries = array();
283 $sql_errors = array();
285 ini_set("max_execution_time", "180");
286 db_query("SET foreign_key_checks=0");
287 $check_line_len = false;
288 // uncrompress gziped backup files
289 if (strpos($filename, ".gz") || strpos($filename, ".GZ"))
290 { $lines = db_ungzip("lines", $filename);
291 $check_line_len = true;
292 } elseif (strpos($filename, ".zip") || strpos($filename, ".ZIP"))
293 $lines = db_unzip("lines", $filename);
295 $lines = file("". $filename);
300 foreach($lines as $line_no => $line)
302 $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!
305 $line = str_replace("0_", $connection["tbpref"], $line);
307 if ($query_table == '')
308 { // check if line begins with one of allowed queries
309 foreach($allowed_commands as $cmd => $table)
311 if (strtolower(substr($line, 0, strlen($cmd))) == $cmd)
313 if ($cmd == 'delimiter') {
314 $delimiter = trim(substr($line, 10));
317 $query_table = $table;
318 ${$query_table}[] = array('', $line_no+1);
323 if($query_table != '') // inside allowed query
325 $table = $query_table;
326 if (!$gzfile_bug && substr($line, -strlen($delimiter)) == $delimiter) // end of query found
328 $line = substr($line, 0, strlen($line) - strlen($delimiter)); // strip delimiter
331 ${$table}[count(${$table}) - 1][0] .= $line . "\n";
336 { // for debugging purposes
337 global $path_to_root;
338 $f = fopen($path_to_root.'/tmp/dbimport.txt', 'w+');
339 fwrite($f, print_r($drop_queries,true) ."\n");
340 fwrite($f, print_r($table_queries,true) ."\n");
341 fwrite($f, print_r($data_queries,true));
345 // execute drop tables if exists queries
346 if (is_array($drop_queries))
348 foreach($drop_queries as $drop_query)
350 if (!db_query($drop_query[0]))
352 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force)
353 $sql_errors[] = array(db_error_msg($db), $drop_query[1]);
358 // execute create tables queries
359 if (is_array($table_queries))
361 foreach($table_queries as $table_query)
363 if (!db_query($table_query[0]))
365 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force) {
366 $sql_errors[] = array(db_error_msg($db), $table_query[1]);
372 // execute insert data queries
373 if (is_array($data_queries))
375 foreach($data_queries as $data_query)
377 if (!db_query($data_query[0]))
379 if (!in_array(db_error_no(),$ignored_mysql_errors) || !$force)
380 $sql_errors[] = array(db_error_msg($db), $data_query[1]);
385 db_query("SET foreign_key_checks=1");
386 if ($delimiter != ';') db_query("delimiter ;"); // just for any case
388 if (count($sql_errors)) {
389 // display first failure message; the rest are probably derivative
390 $err = $sql_errors[0];
391 display_error(sprintf(_("SQL script execution failed in line %d: %s"),
398 // returns the content of the gziped $path backup file. use of $mode see below
399 function db_ungzip($mode, $path)
401 $file_data = gzfile($path);
402 // returns one string or an array of lines
403 if ($mode != "lines")
404 return implode("",$file_data);
409 // returns the content of the ziped $path backup file. use of $mode see below
410 function db_unzip($mode, $path)
413 $all = implode("", file($path));
415 // convert path to name of ziped file
416 $filename = preg_replace("/.*\//", "", $path);
417 $filename = substr($filename, 0, strlen($filename) - 4);
419 // compare filname in zip and filename from $_GET
420 if (substr($all, 30, strlen($filename)-4) . substr($all, 30+strlen($filename)+9, 4)
422 return ''; // exit if names differ
426 // get the suffix of the filename in hex
427 $crc_bugfix = substr($all, 30, strlen($filename)+13);
428 $crc_bugfix = substr(substr($crc_bugfix, 0, strlen($crc_bugfix) - 4),
429 strlen($crc_bugfix) - 12 - 4);
431 // convert hex to ascii
432 for ($i=0; $i < 12; )
433 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
435 // remove central directory information (we have always just one ziped file)
436 $comp = substr($all, -(strlen($all) - 30 - strlen($filename)-13));
437 $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)-13));
439 // fix the crc bugfix (see function save_to_file)
440 $comp = "x
\9c" . $comp . $suffix;
441 $file_data = gzuncompress($comp);
444 // returns one string or an array of lines
445 if ($mode != "lines")
448 return explode("\n", $file_data);
451 function db_backup($conn, $ext='no', $comm='', $tbpref = TB_PREF)
453 if ($conn['tbpref'] != "")
454 $filename = $conn['dbname'] . "_" . $conn['tbpref'] . date("Ymd_Hi") . ".sql";
456 $filename = $conn['dbname'] . "_" . date("Ymd_Hi") . ".sql";
458 return db_export($conn, clean_file_name($filename), $ext, $comm, $tbpref);
461 // generates a dump of $db database
462 // $drop and $zip tell if to include the drop table statement or dry to pack
463 function db_export($conn, $filename, $zip='no', $comment='', $tbpref = TB_PREF, $no_default=false)
466 global $app_title, $version, $power_url, $path_to_root;
469 // set max string size before writing to file
470 $max_size = 1048576 * 2; // 2 MB
471 // changes max size if value can be retrieved
472 if (ini_get("memory_limit"))
473 $max_size = 900000 * ini_get("memory_limit");
475 // set backupfile name
477 $backupfile = $filename . ".gz";
478 elseif ($zip == "zip")
479 $backupfile = $filename . ".zip";
481 $backupfile = $filename;
482 $company = get_company_pref('coy_name', $tbpref);
485 $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
486 $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
487 $out.="# Built by " . $app_title . " " . $version ."\n";
488 $out.="# ".$power_url."\n";
489 $out.="# Company: ". @html_entity_decode($company, ENT_QUOTES, $_SESSION['language']->encoding)."\n";
490 $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
492 // write users comment
495 $out .= "# Comment:\n";
496 $comment=preg_replace("'\n'","\n# ","# ".$comment);
497 //$comment=str_replace("\n", "\n# ", $comment);
498 foreach(explode("\n",$comment) as $line)
503 //$out.="use ".$db.";\n"; we don't use this option.
505 // get auto_increment values and names of all tables
506 $res = db_query("show table status");
507 $all_tables = array();
508 while($row = db_fetch($res))
510 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
511 ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) === 0))
512 $all_tables[] = $row;
514 // get table structures
515 foreach ($all_tables as $table)
517 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
518 $tmp = db_fetch($res1);
519 $table_sql[$table['Name']] = $tmp["Create Table"];
524 if (isset($table_sql))
526 foreach($table_sql as $tablenme=>$table)
529 // save all tables, needed for creating this table in $fks
530 while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
532 $tmp_table = substr($tmp_table, $ref_pos + 12);
533 $ref_pos = strpos($tmp_table, "(");
534 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
539 $all_tables = order_sql_tables($all_tables, $fks);
541 // as long as no error occurred
544 foreach ($all_tables as $row)
546 $tablename = $row['Name'];
547 $auto_incr[$tablename] = $row['Auto_increment'];
551 $out.="### Structure of table `".$tablename."` ###\n\n";
553 $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
554 if ($no_default && ($def_pos = strpos($table_sql[$tablename], "DEFAULT CHARSET")) > 0)
555 $table_sql[$tablename] = substr($table_sql[$tablename], 0, $def_pos);
556 $out.=$table_sql[$tablename];
558 // add auto_increment value
559 // if ($auto_incr[$tablename])
560 // $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
567 $out.="### Data of table `".$tablename."` ###\n";
569 // check if field types are NULL or NOT NULL
570 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
572 $field_null = array();
573 for ($j = 0; $j < db_num_rows($res3); $j++)
575 $row3 = db_fetch($res3);
576 $field_null[] = $row3[2]=='YES' && $row3[4]===null;
579 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
582 for ($j = 0; $j < db_num_rows($res2); $j++)
584 $row2 = db_fetch_row($res2);
586 for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
588 $values .= db_escape($row2[$k], $field_null[$k]);
593 $len = strlen($values);
594 if ($maxinsert < $len+1)
596 $maxinsert = EXPORT_MAX_INSERT;
599 $out .= $insert .';'; // flush insert query
606 $insert = "\nINSERT INTO `" . $tablename . "` VALUES\n";
607 $maxinsert -= strlen($insert);
615 // if saving is successful, then empty $out, else set error flag
616 if (strlen($out) > $max_size && $zip != "zip")
618 if (save_to_file($backupfile, $zip, $out))
625 $out .= $insert. ';';
626 // an error occurred! Try to delete file and return error status
630 @unlink(BACKUP_PATH . $backupfile);
634 // if saving is successful, then empty $out, else set error flag
635 if (strlen($out) > $max_size && $zip != "zip")
637 if (save_to_file($backupfile, $zip, $out))
644 // an error occurred! Try to delete file and return error status
648 @unlink(BACKUP_PATH . $backupfile);
654 if (save_to_file($backupfile, $zip, $out))
660 @unlink(BACKUP_PATH . $backupfile);
666 // orders the tables in $tables according to the constraints in $fks
667 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
668 function order_sql_tables($tables, $fks)
670 // do not order if no contraints exist
675 $new_tables = array();
678 while (count($tables) && $modified == true)
681 foreach ($tables as $key=>$row)
683 // delete from $tables and add to $new_tables
684 if (isset($fks[$row['Name']]))
686 foreach($fks[$row['Name']] as $needed)
688 // go to next table if not all needed tables exist in $existing
689 if (!in_array($needed,$existing))
693 // delete from $tables and add to $new_tables
694 $existing[] = $row['Name'];
695 $new_tables[] = $row;
697 unset($tables[$key]);
705 // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
706 // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
707 // until now, just add the lasting tables to $new_tables, return them and print a warning
708 foreach($tables as $row)
709 $new_tables[] = $row;
710 echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
715 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
716 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
717 function save_to_file($backupfile, $zip, $fileData)
719 global $path_to_root;
723 if ($zp = @gzopen(BACKUP_PATH . $backupfile, "a9"))
725 @gzwrite($zp, $fileData);
734 // $zip contains the timestamp
736 elseif ($zip == "zip")
738 // based on zip.lib.php 2.2 from phpMyBackupAdmin
739 // offical zip format: http://www.pkware.com/appnote.txt
741 // End of central directory record
742 $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
744 // "local file header" segment
745 $unc_len = strlen($fileData);
746 $crc = crc32($fileData);
747 $zdata = gzcompress($fileData);
749 // extend stored file name with suffix
750 // needed for decoding (because of crc bug)
751 $name_suffix = substr($zdata, -4, 4);
753 for ($i = 0; $i < 4; $i++)
754 $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
756 $name = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql";
759 $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
760 $c_len = strlen($zdata);
763 $timearray = getdate();
764 $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
765 ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
766 $dtime = dechex($dostime);
767 $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
768 eval('$hexdtime="' . $hexdtime . '";');
770 // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
771 $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
773 // crc32, compressed filesize, uncompressed filesize
774 $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
776 $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
778 // length of filename, extra field length
779 $fr .= pack('v', strlen($name)) . pack('v', 0);
782 // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
783 $fr .= $zdata . $sub2;
785 // now add to central directory record
786 $cdrec = "\x50\x4b\x01\x02";
787 $cdrec .= "\x00\x00"; // version made by
788 $cdrec .= $sub1 . $sub2;
790 // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
791 $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
795 $fileData = $fr . $cdrec . $eof_ctrl_dir;
797 // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
798 $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
800 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
802 @fwrite($zp, $fileData);
815 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
817 @fwrite($zp, $fileData);
828 function create_comp_dirs($comp_path, $comp_subdirs)
830 $index = "<?php\nheader(\"Location: ../index.php\");\n?>";
833 $f = @fopen("$cdir/index.php", "wb");
837 foreach($comp_subdirs as $dir)
839 @mkdir($cdir.'/'.$dir);
840 $f = @fopen("$cdir/$dir/index.php", "wb");
847 // Checks $field existence in $table with given field $properties
848 // $table - table name without prefix
849 // $field - optional field name
850 // $properties - optional properties of field defined by MySQL:
851 // 'Type', 'Null', 'Key', 'Default', 'Extra'
853 function check_table($pref, $table, $field=null, $properties=null)
855 $tables = @db_query("SHOW TABLES LIKE '".$pref.$table."'");
856 if (!db_num_rows($tables))
857 return 1; // no such table or error
859 $fields = @db_query("SHOW COLUMNS FROM ".$pref.$table);
861 return 0; // table exists
863 while( $row = db_fetch_assoc($fields))
865 if ($row['Field'] == $field)
867 if (!isset($properties))
869 foreach($properties as $property => $value)
871 if ($row[$property] != $value)
872 return 3; // failed type/length check
874 return 0; // property check ok.
877 return 2; // field not found