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 function array_natsort($aryData, $strIndex, $strSortBy, $strSortType=false)
23 // if the parameters are invalid
24 if (!is_array($aryData) || !$strSortBy)
28 // create our temporary arrays
29 $arySort = $aryResult = array();
31 // loop through the array
32 foreach ($aryData as $key => $aryRow)
33 // set up the value in the array
34 $arySort[$strIndex ? $aryRow[$strIndex] : $key] = $aryRow[$strSortBy];
36 // apply the natural sort
39 // if the sort type is descending
40 if ($strSortType=="desc")
44 // loop through the sorted and original data
45 foreach ($arySort as $arySortKey => $arySorted)
48 foreach ($aryData as $aryOriginal)
50 if ($aryOriginal[$strIndex]==$arySortKey)
51 // add it to the output array
52 array_push($aryResult, $aryOriginal);
54 $aryResult[$arySortKey] = $aryData[$arySortKey];
59 function update_admin_password($conn, $password)
61 $sql = "UPDATE ".$conn['tbpref']."users SET password=".db_escape($password) . "
62 WHERE user_id='admin'";
63 db_query($sql, "could not update user password for 'admin'");
66 function write_config_db($new = false)
68 global $path_to_root, $def_coy, $db_connections, $tb_pref_counter;
72 $n = count($db_connections);
74 $msg .= "/*Connection Information for the database\n";
75 $msg .= "\$def_coy - the default company that is pre-selected on login\n\n";
76 $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";
77 $msg .= "'dbuser' - the user name under which the company database should be accessed.\n";
78 $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";
79 $msg .= "'dbpassword' - the password required for the dbuser to authorise the above database user.\n\n";
80 $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";
81 $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 .= "\$def_coy = " . $def_coy . ";\n\n";
85 $msg .= "\$tb_pref_counter = " . $tb_pref_counter . ";\n\n";
86 $msg .= "\$db_connections = " .var_export($db_connections, true);
89 $filename = $path_to_root . "/config_db.php";
90 // Check if the file exists and is writable first.
91 if ((!file_exists($filename) && is_writable($path_to_root)) || is_writable($filename))
93 if (!$zp = fopen($filename, 'w'))
99 if (!fwrite($zp, $msg))
115 function write_extensions($extensions=null, $company = -1)
117 global $path_to_root, $installed_extensions, $next_extension_id;
119 if (!isset($extensions)) {
120 $extensions = $installed_extensions;
122 if (!isset($next_extension_id)) {
123 $next_extension_id = 1;
129 "/* List of installed additional extensions. If extensions are added to the list manually
130 make sure they have unique and so far never used extension_ids as a keys,
131 and \$next_extension_id is also updated. More about format of this file yo will find in
132 FA extension system documentation.
134 \n\$next_extension_id = $next_extension_id; // unique id for next installed extension\n\n";
138 Do not edit this file manually. This copy of global file is overwritten
139 by extensions editor.
142 $msg .= "\$installed_extensions = ". var_export($extensions, true);
144 $filename = $path_to_root . ($company==-1 ? '' : '/company/'.$company)
145 .'/installed_extensions.php';
147 // Check if the file is writable first.
148 if (!$zp = @fopen($filename, 'w'))
150 display_error(sprintf(_("Cannot open the extension setup file '%s' for writing."),
156 if (!fwrite($zp, $msg))
158 display_error(sprintf(_("Cannot write to the extensions setup file '%s'."),
168 //---------------------------------------------------------------------------------------------
170 // Update per-company list of installed extensions
172 function update_extensions($extensions) {
173 global $db_connections;
175 if (!write_extensions($extensions)) {
176 display_notification(_("Cannot update system extensions list."));
180 // update per company files
181 $cnt = count($db_connections);
182 for($i = 0; $i < $cnt; $i++)
184 $newexts = $extensions;
185 // update 'active' status
186 $exts = get_company_extensions($i);
187 foreach ($exts as $key => $ext)
189 if (isset($newexts[$key]))
190 $newexts[$key]['active'] = $exts[$key]['active'];
192 if(!write_extensions($newexts, $i))
194 display_notification(sprintf(_("Cannot update extensions list for company '%s'."),
195 $db_connections[$i]['name']));
203 function write_lang()
205 global $path_to_root, $installed_languages, $dflt_lang;
207 $installed_languages = array_natsort($installed_languages, 'code', 'code');
208 $n = count($installed_languages);
211 $msg .= "/* How to make new entries here for non-packaged languages:\n\n";
212 $msg .= "-- 'code' should match the name of the directory for the language under \\lang\n.";
213 $msg .= "-- 'name' is the name that will be displayed in the language selection list (in Users and Display Setup)\n";
214 $msg .= "-- 'rtl' only needs to be set for right-to-left languages like Arabic and Hebrew\n";
215 $msg .= "-- 'encoding' used in translation file\n";
216 $msg .= "-- 'version' always set to '' for manually installed languages.\n";
217 $msg .= "-- 'path' installation path related to FA root (e.g. 'lang/en_US').\n";
220 $msg .= "\$installed_languages = " . var_export($installed_languages, true);
222 $msg .= "\n\$dflt_lang = '$dflt_lang';\n?>\n";
224 $path = $path_to_root . "/lang";
225 $filename = $path.'/installed_languages.inc';
226 // Check if directory exists and is writable first.
227 if (file_exists($path) && is_writable($path))
229 if (!$zp = fopen($filename, 'w'))
231 display_error(_("Cannot open the languages file - ") . $filename);
236 if (!fwrite($zp, $msg))
238 display_error(_("Cannot write to the language file - ") . $filename);
248 display_error(_("The language files folder ") . $path . _(" is not writable. Change its permissions so it is, then re-run the operation."));
254 function db_import($filename, $connection, $force=true)
256 global $db, $go_debug;
258 $allowed_commands = array(
259 "create" => 'table_queries',
260 "alter table" => 'table_queries',
261 "insert" => 'data_queries',
262 "update" => 'data_queries',
263 "drop table if exists" => 'drop_queries');
264 $ignored_mysql_errors = array( //errors ignored in normal (non forced) mode
265 '1022', // duplicate key
266 '1050', // Table %s already exists
267 '1060', // duplicate column name
268 '1061', // duplicate key name
269 '1062', // duplicate key entry
270 '1091' // can't drop key/column check if exists
272 $data_queries = array();
273 $drop_queries = array();
274 $table_queries = array();
275 $sql_errors = array();
277 ini_set("max_execution_time", "180");
278 db_query("SET foreign_key_checks=0");
279 // uncrompress gziped backup files
280 if (strpos($filename, ".gz") || strpos($filename, ".GZ"))
281 $lines = db_ungzip("lines", $filename);
282 elseif (strpos($filename, ".zip") || strpos($filename, ".ZIP"))
283 $lines = db_unzip("lines", $filename);
285 $lines = file("". $filename);
289 foreach($lines as $line_no => $line)
293 $line = str_replace("0_", $connection["tbpref"], $line);
295 if ($query_table == '')
296 { // check if line begins with one of allowed queries
297 foreach($allowed_commands as $cmd => $table)
299 if (strtolower(substr($line, 0, strlen($cmd))) == $cmd)
301 $query_table = $table;
302 ${$query_table}[] = array('', $line_no+1);
307 if($query_table != '') // inside allowed query
309 $table = $query_table;
310 if (substr($line, -1) == ';') // end of query found
312 $line = substr($line, 0, strlen($line) - 1); // strip ';'
315 ${$table}[count(${$table}) - 1][0] .= $line . "\n";
320 { // for debugging purposes
321 global $path_to_root;
322 $f = fopen($path_to_root.'/tmp/dbimport.txt', 'w+');
323 fwrite($f, print_r($drop_queries,true) ."\n");
324 fwrite($f, print_r($table_queries,true) ."\n");
325 fwrite($f, print_r($data_queries,true));
329 // execute drop tables if exists queries
330 if (is_array($drop_queries))
332 foreach($drop_queries as $drop_query)
334 if (!db_query($drop_query[0]))
336 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force)
337 $sql_errors[] = array(db_error_msg($db), $drop_query[1]);
342 // execute create tables queries
343 if (is_array($table_queries))
345 foreach($table_queries as $table_query)
347 if (!db_query($table_query[0]))
349 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force) {
350 $sql_errors[] = array(db_error_msg($db), $table_query[1]);
356 // execute insert data queries
357 if (is_array($data_queries))
359 foreach($data_queries as $data_query)
361 if (!db_query($data_query[0]))
363 if (!in_array(db_error_no(),$ignored_mysql_errors) || !$force)
364 $sql_errors[] = array(db_error_msg($db), $data_query[1]);
369 db_query("SET foreign_key_checks=1");
371 if (count($sql_errors)) {
372 // display first failure message; the rest are probably derivative
373 $err = $sql_errors[0];
374 display_error(sprintf(_("SQL script execution failed in line %d: %s"),
381 // returns the content of the gziped $path backup file. use of $mode see below
382 function db_ungzip($mode, $path)
384 $file_data = gzfile($path);
385 // returns one string or an array of lines
386 if ($mode != "lines")
387 return implode("",$file_data);
392 // returns the content of the ziped $path backup file. use of $mode see below
393 function db_unzip($mode, $path)
396 $all = implode("", file($path));
398 // convert path to name of ziped file
399 $filename = preg_replace("/.*\//", "", $path);
400 $filename = substr($filename, 0, strlen($filename) - 4);
402 // compare filname in zip and filename from $_GET
403 if (substr($all, 30, strlen($filename)-4) . substr($all, 30+strlen($filename)+9, 4)
405 return ''; // exit if names differ
409 // get the suffix of the filename in hex
410 $crc_bugfix = substr($all, 30, strlen($filename)+13);
411 $crc_bugfix = substr(substr($crc_bugfix, 0, strlen($crc_bugfix) - 4),
412 strlen($crc_bugfix) - 12 - 4);
414 // convert hex to ascii
415 for ($i=0; $i < 12; )
416 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
418 // remove central directory information (we have always just one ziped file)
419 $comp = substr($all, -(strlen($all) - 30 - strlen($filename)-13));
420 $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)-13));
422 // fix the crc bugfix (see function save_to_file)
423 $comp = "x
\9c" . $comp . $suffix;
424 $file_data = gzuncompress($comp);
427 // returns one string or an array of lines
428 if ($mode != "lines")
431 return explode("\n", $file_data);
434 function db_backup($conn, $ext='no', $comm='', $tbpref = TB_PREF)
436 if ($conn['tbpref'] != "")
437 $filename = $conn['dbname'] . "_" . $conn['tbpref'] . date("Ymd_Hi") . ".sql";
439 $filename = $conn['dbname'] . "_" . date("Ymd_Hi") . ".sql";
441 return db_export($conn, clean_file_name($filename), $ext, $comm, $tbpref);
444 // generates a dump of $db database
445 // $drop and $zip tell if to include the drop table statement or dry to pack
446 function db_export($conn, $filename, $zip='no', $comment='', $tbpref = TB_PREF, $no_default=false)
449 global $app_title, $version, $power_url, $path_to_root;
452 // set max string size before writing to file
453 $max_size = 1048576 * 2; // 2 MB
454 // changes max size if value can be retrieved
455 if (ini_get("memory_limit"))
456 $max_size = 900000 * ini_get("memory_limit");
458 // set backupfile name
460 $backupfile = $filename . ".gz";
461 elseif ($zip == "zip")
462 $backupfile = $filename . ".zip";
464 $backupfile = $filename;
465 $company = get_company_pref('coy_name', $tbpref);
468 $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
469 $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
470 $out.="# Built by " . $app_title . " " . $version ."\n";
471 $out.="# ".$power_url."\n";
472 $out.="# Company: ". @html_entity_decode($company, ENT_QUOTES, $_SESSION['language']->encoding)."\n";
473 $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
475 // write users comment
478 $out .= "# Comment:\n";
479 $comment=preg_replace("'\n'","\n# ","# ".$comment);
480 //$comment=str_replace("\n", "\n# ", $comment);
481 foreach(explode("\n",$comment) as $line)
486 //$out.="use ".$db.";\n"; we don't use this option.
488 // get auto_increment values and names of all tables
489 $res = db_query("show table status");
490 $all_tables = array();
491 while($row = db_fetch($res))
493 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
494 ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) === 0))
495 $all_tables[] = $row;
497 // get table structures
498 foreach ($all_tables as $table)
500 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
501 $tmp = db_fetch($res1);
502 $table_sql[$table['Name']] = $tmp["Create Table"];
507 if (isset($table_sql))
509 foreach($table_sql as $tablenme=>$table)
512 // save all tables, needed for creating this table in $fks
513 while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
515 $tmp_table = substr($tmp_table, $ref_pos + 12);
516 $ref_pos = strpos($tmp_table, "(");
517 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
522 $all_tables = order_sql_tables($all_tables, $fks);
524 // as long as no error occurred
527 foreach ($all_tables as $row)
529 $tablename = $row['Name'];
530 $auto_incr[$tablename] = $row['Auto_increment'];
534 $out.="### Structure of table `".$tablename."` ###\n\n";
536 $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
537 if ($no_default && ($def_pos = strpos($table_sql[$tablename], "DEFAULT CHARSET")) > 0)
538 $table_sql[$tablename] = substr($table_sql[$tablename], 0, $def_pos);
539 $out.=$table_sql[$tablename];
541 // add auto_increment value
542 // if ($auto_incr[$tablename])
543 // $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
550 $out.="### Data of table `".$tablename."` ###\n\n";
552 // check if field types are NULL or NOT NULL
553 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
555 $field_null = array();
556 for ($j = 0; $j < db_num_rows($res3); $j++)
558 $row3 = db_fetch($res3);
559 $field_null[] = $row3[2]=='YES' && $row3[4]===null;
562 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
563 for ($j = 0; $j < db_num_rows($res2); $j++)
565 $out .= "INSERT INTO `" . $tablename . "` VALUES (";
566 $row2 = db_fetch_row($res2);
567 // run through each field
568 for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
570 $out .= db_escape($row2[$k], $field_null[$k]);
576 // if saving is successful, then empty $out, else set error flag
577 if (strlen($out) > $max_size && $zip != "zip")
579 if (save_to_file($backupfile, $zip, $out))
586 // an error occurred! Try to delete file and return error status
590 @unlink(BACKUP_PATH . $backupfile);
594 // if saving is successful, then empty $out, else set error flag
595 if (strlen($out) > $max_size && $zip != "zip")
597 if (save_to_file($backupfile, $zip, $out))
604 // an error occurred! Try to delete file and return error status
608 @unlink(BACKUP_PATH . $backupfile);
614 if (save_to_file($backupfile, $zip, $out))
620 @unlink(BACKUP_PATH . $backupfile);
626 // orders the tables in $tables according to the constraints in $fks
627 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
628 function order_sql_tables($tables, $fks)
630 // do not order if no contraints exist
635 $new_tables = array();
638 while (count($tables) && $modified == true)
641 foreach ($tables as $key=>$row)
643 // delete from $tables and add to $new_tables
644 if (isset($fks[$row['Name']]))
646 foreach($fks[$row['Name']] as $needed)
648 // go to next table if not all needed tables exist in $existing
649 if (!in_array($needed,$existing))
653 // delete from $tables and add to $new_tables
654 $existing[] = $row['Name'];
655 $new_tables[] = $row;
657 unset($tables[$key]);
665 // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
666 // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
667 // until now, just add the lasting tables to $new_tables, return them and print a warning
668 foreach($tables as $row)
669 $new_tables[] = $row;
670 echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
675 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
676 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
677 function save_to_file($backupfile, $zip, $fileData)
679 global $path_to_root;
683 if ($zp = @gzopen(BACKUP_PATH . $backupfile, "a9"))
685 @gzwrite($zp, $fileData);
694 // $zip contains the timestamp
696 elseif ($zip == "zip")
698 // based on zip.lib.php 2.2 from phpMyBackupAdmin
699 // offical zip format: http://www.pkware.com/appnote.txt
701 // End of central directory record
702 $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
704 // "local file header" segment
705 $unc_len = strlen($fileData);
706 $crc = crc32($fileData);
707 $zdata = gzcompress($fileData);
709 // extend stored file name with suffix
710 // needed for decoding (because of crc bug)
711 $name_suffix = substr($zdata, -4, 4);
713 for ($i = 0; $i < 4; $i++)
714 $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
716 $name = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql";
719 $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
720 $c_len = strlen($zdata);
723 $timearray = getdate($zip);
724 $dostime = (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
725 ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
726 $dtime = dechex($dostime);
727 $hexdtime = "\x" . $dtime[6] . $dtime[7] . "\x" . $dtime[4].$dtime[5] . "\x" . $dtime[2] . $dtime[3] . "\x" . $dtime[0] . $dtime[1];
728 eval('$hexdtime="' . $hexdtime . '";');
730 // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
731 $sub1 = "\x14\x00" . "\x00\x00" . "\x08\x00" . $hexdtime;
733 // crc32, compressed filesize, uncompressed filesize
734 $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
736 $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
738 // length of filename, extra field length
739 $fr .= pack('v', strlen($name)) . pack('v', 0);
742 // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
743 $fr .= $zdata . $sub2;
745 // now add to central directory record
746 $cdrec = "\x50\x4b\x01\x02";
747 $cdrec .= "\x00\x00"; // version made by
748 $cdrec .= $sub1 . $sub2;
750 // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
751 $cdrec .= pack('v', strlen($name)) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V',0);
755 $fileData = $fr . $cdrec . $eof_ctrl_dir;
757 // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
758 $fileData .= pack('v', 1) . pack('v', 1) . pack('V', strlen($cdrec)) . pack('V', strlen($fr)) . "\x00\x00";
760 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
762 @fwrite($zp, $fileData);
775 if ($zp = @fopen(BACKUP_PATH . $backupfile, "a"))
777 @fwrite($zp, $fileData);
788 function create_comp_dirs($comp_path, $comp_subdirs)
790 $index = "<?php\nheader(\"Location: ../index.php\");\n?>";
793 $f = @fopen("$cdir/index.php", "wb");
797 foreach($comp_subdirs as $dir)
799 @mkdir($cdir.'/'.$dir);
800 $f = @fopen("$cdir/$dir/index.php", "wb");
807 // Checks $field existence in $table with given field $properties
808 // $table - table name without prefix
809 // $field - optional field name
810 // $properties - optional properties of field defined by MySQL:
811 // 'Type', 'Null', 'Key', 'Default', 'Extra'
813 function check_table($pref, $table, $field=null, $properties=null)
815 $tables = @db_query("SHOW TABLES LIKE '".$pref.$table."'");
816 if (!db_num_rows($tables))
817 return 1; // no such table or error
819 $fields = @db_query("SHOW COLUMNS FROM ".$pref.$table);
821 return 0; // table exists
823 while( $row = db_fetch_assoc($fields))
825 if ($row['Field'] == $field)
827 if (!isset($properties))
829 foreach($properties as $property => $value)
831 if ($row[$property] != $value)
832 return 3; // failed type/length check
834 return 0; // property check ok.
837 return 2; // field not found