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;
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 .= "'dbuser' - the user name under which the company database should be accessed.\n";
79 $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";
80 $msg .= "'dbpassword' - the password required for the dbuser to authorise the above database user.\n\n";
81 $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";
82 $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 .= "\$def_coy = " . $def_coy . ";\n\n";
86 $msg .= "\$tb_pref_counter = " . $tb_pref_counter . ";\n\n";
87 $msg .= "\$db_connections = " .var_export($db_connections, true);
90 $filename = $path_to_root . "/config_db.php";
91 // Check if the file exists and is writable first.
92 if ((!file_exists($filename) && is_writable($path_to_root)) || is_writable($filename))
94 if (!$zp = fopen($filename, 'w'))
100 if (!fwrite($zp, $msg))
107 cache_invalidate($filename);
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'."),
167 cache_invalidate($filename);
171 //---------------------------------------------------------------------------------------------
173 // Update per-company list of installed extensions
175 function update_extensions($extensions) {
176 global $db_connections;
178 if (!write_extensions($extensions)) {
179 display_notification(_("Cannot update system extensions list."));
183 // update per company files
184 $cnt = max(1, count($db_connections));
185 for($i = 0; $i < $cnt; $i++)
187 $newexts = $extensions;
188 // update 'active' status
189 $exts = get_company_extensions($i);
190 foreach ($exts as $key => $ext)
192 if (isset($newexts[$key]))
193 $newexts[$key]['active'] = $exts[$key]['active'];
195 if(!write_extensions($newexts, $i))
197 display_notification(sprintf(_("Cannot update extensions list for company '%s'."),
198 $db_connections[$i]['name']));
206 function write_lang()
208 global $path_to_root, $installed_languages, $dflt_lang;
210 $installed_languages = array_natsort($installed_languages, 'code', 'code');
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";
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);
246 cache_invalidate($filename);
251 display_error(_("The language files folder ") . $path . _(" is not writable. Change its permissions so it is, then re-run the operation."));
258 $filename - sql file name
259 $connection - database connection
260 $force - ignore duplicate errors
261 $init - presume $filename is initialization file with '0_' prefix
262 $protect - protect users/roles
263 $return_errors - return errors instead of display them
265 function db_import($filename, $connection, $force=true, $init=true, $protect=false, $return_errors=false)
267 global $db, $SysPrefs;
269 $trail = $SysPrefs->sql_trail;
270 $SysPrefs->sql_trail = false;
272 $allowed_commands = array(
273 "create" => 'table_queries',
274 "delimiter" => 'table_queries',
275 "alter table" => 'table_queries',
276 "insert" => 'data_queries',
277 "update" => 'data_queries',
278 "set names" => 'set_names',
279 "drop table if exists" => 'drop_queries',
280 "drop function if exists" => 'drop_queries',
281 "drop trigger if exists" => 'drop_queries',
282 "select" => 'data_queries',
283 "delete" => 'data_queries',
291 $ignored_mysql_errors = array( //errors ignored in normal (non forced) mode
292 '1022', // duplicate key
293 '1050', // Table %s already exists
294 '1060', // duplicate column name
295 '1061', // duplicate key name
296 '1062', // duplicate key entry
297 '1091' // can't drop key/column check if exists
300 $set_names = array();
301 $data_queries = array();
302 $drop_queries = array();
303 $table_queries = array();
304 $sql_errors = array();
306 $old_encoding = db_get_charset($db);
308 ini_set("max_execution_time", max("180", ini_get("max_execution_time")));
309 db_query("SET foreign_key_checks=0");
311 if (isset($connection['collation']))
312 db_set_collation($db, $connection['collation']);
314 $check_line_len = false;
316 // uncompress gziped backup files
317 if (strpos($filename, ".gz") || strpos($filename, ".GZ"))
318 { $lines = db_ungzip("lines", $filename);
319 $check_line_len = true;
320 } elseif (strpos($filename, ".zip") || strpos($filename, ".ZIP"))
321 $lines = db_unzip("lines", $filename);
323 $lines = file("". $filename);
329 foreach($lines as $line_no => $line)
331 $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!
335 $line = str_replace("0_", $connection["tbpref"], $line);
337 if ($query_table == '')
338 { // check if line begins with one of allowed queries
339 foreach($allowed_commands as $cmd => $table)
341 if (strtolower(substr($line, 0, strlen($cmd))) == $cmd)
343 if ($cmd == 'delimiter') {
344 $delimiter = trim(substr($line, 10));
347 $query_table = $table;
351 foreach($protected as $protbl)
352 if (strpos($line, $connection["tbpref"].$protbl) !== false)
358 ${$query_table}[] = array('', $line_no+1);
363 if($query_table != '') // inside allowed query
365 $table = $query_table;
366 if (!$gzfile_bug && substr($line, -strlen($delimiter)) == $delimiter) // end of query found
368 $line = substr($line, 0, strlen($line) - strlen($delimiter)); // strip delimiter
372 ${$table}[count(${$table}) - 1][0] .= $line . "\n";
378 // 'set names' or equivalents should be used only on post 2.3 FA versions
379 // otherwise text encoding can be broken during import
381 $encoding = null; // UI encoding for default site language is the default
382 $new_db = $init || db_fixed();
383 $new_file = count($set_names);
388 if (count($set_names)) // standard db restore
390 if (preg_match('/set\s*names\s*[\']?(\w*)[\']?/i', $set_names[0][0], $match))
391 $encoding = $match[1];
393 // otherwise use default site ui encoding
398 if ($new_file) // import on old db is forbidden: this would destroy db content unless latin1 was used before in UI
400 $msg = _("This is new format backup file which cannot be restored on database not migrated to utf8.");
407 else // backup restore during upgrade failure
408 $encoding = 'latin1'; // standard encoding on mysql client
411 db_set_charset($db, $encoding);
413 /*/ { // for debugging purposes
414 global $path_to_root;
415 $f = fopen($path_to_root.'/tmp/dbimport.txt', 'w+');
416 fwrite($f, print_r($set_names,true) ."\n");
417 fwrite($f, print_r($drop_queries,true) ."\n");
418 fwrite($f, print_r($table_queries,true) ."\n");
419 fwrite($f, print_r($data_queries,true));
424 { // prevent errors display
425 $save_debug = $SysPrefs->go_debug;
426 $SysPrefs->go_debug = 0;
428 // execute drop tables if exists queries
429 if (is_array($drop_queries))
431 foreach($drop_queries as $drop_query)
433 if (!db_query($drop_query[0]))
435 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force)
436 $sql_errors[] = array(db_error_msg($db), $drop_query[1]);
441 // execute create tables queries
442 if (is_array($table_queries))
444 foreach($table_queries as $table_query)
446 if (!db_query($table_query[0]))
448 if (!in_array(db_error_no(), $ignored_mysql_errors) || !$force) {
449 $sql_errors[] = array(db_error_msg($db), $table_query[1]);
455 // execute insert data queries
456 if (is_array($data_queries))
458 foreach($data_queries as $data_query)
460 if (!db_query($data_query[0]))
462 if (!in_array(db_error_no(),$ignored_mysql_errors) || !$force)
463 $sql_errors[] = array(db_error_msg($db), $data_query[1]);
469 $SysPrefs->go_debug = $save_debug;
471 $SysPrefs->sql_trail = $trail;
473 db_query("SET foreign_key_checks=1");
474 if ($delimiter != ';') db_query("delimiter ;"); // just for any case
476 db_set_charset($db, $old_encoding); // restore connection encoding
478 if (count($sql_errors)) {
482 // display first failure message; the rest are probably derivative
483 $err = $sql_errors[0];
484 display_error(sprintf(_("SQL script execution failed in line %d: %s"),
491 // returns the content of the gziped $path backup file. use of $mode see below
492 function db_ungzip($mode, $path)
494 $file_data = gzfile($path);
495 // returns one string or an array of lines
496 if ($mode != "lines")
497 return implode("",$file_data);
502 // returns the content of the ziped $path backup file. use of $mode see below
503 function db_unzip($mode, $path)
506 $all = implode("", file($path));
508 // convert path to name of ziped file
509 $filename = preg_replace("/.*\//", "", $path);
510 $filename = substr($filename, 0, strlen($filename) - 4);
512 // compare filname in zip and filename from $_GET
513 if (substr($all, 30, strlen($filename)-4) . substr($all, 30+strlen($filename)+9, 4)
515 return ''; // exit if names differ
519 // get the suffix of the filename in hex
520 $crc_bugfix = substr($all, 30, strlen($filename)+13);
521 $crc_bugfix = substr(substr($crc_bugfix, 0, strlen($crc_bugfix) - 4),
522 strlen($crc_bugfix) - 12 - 4);
524 // convert hex to ascii
525 for ($i=0; $i < 12; )
526 $suffix .= chr($crc_bugfix[$i++] . $crc_bugfix[$i++] . $crc_bugfix[$i++]);
528 // remove central directory information (we have always just one ziped file)
529 $comp = substr($all, -(strlen($all) - 30 - strlen($filename)-13));
530 $comp = substr($comp, 0, (strlen($comp) - 80 - strlen($filename)-13));
532 // fix the crc bugfix (see function save_to_file)
533 $comp = "x
\9c" . $comp . $suffix;
534 $file_data = gzuncompress($comp);
537 // returns one string or an array of lines
538 if ($mode != "lines")
541 return explode("\n", $file_data);
544 function db_backup($conn, $ext='no', $comm='', $path='')
546 if ($conn['tbpref'] != "")
547 $filename = $conn['dbname'] . "_" . $conn['tbpref'] . date("Ymd_Hi") . ".sql";
549 $filename = $conn['dbname'] . "_" . date("Ymd_Hi") . ".sql";
551 return db_export($conn, $path . clean_file_name($filename), $ext, $comm);
554 // Generates a dump of $db database
556 function db_export($conn, $filename, $zip='no', $comment='')
559 global $SysPrefs, $version;
562 // set max string size before writing to file
563 $max_size = 1048576 * 2; // 2 MB
564 // changes max size if value can be retrieved
565 if (ini_get("memory_limit"))
566 $max_size = 900000 * ini_get("memory_limit");
568 // set backupfile name
570 $backupfile = $filename . ".gz";
571 elseif ($zip == "zip")
572 $backupfile = $filename . ".zip";
574 $backupfile = $filename;
575 $company = $conn['name']; // get_company_pref('coy_name');
577 if (file_exists($backupfile)) // prevent appends
581 $out="# MySQL dump of database '".$conn["dbname"]."' on host '".$conn["host"]."'\n";
582 $out.="# Backup Date and Time: ".date("Y-m-d H:i")."\n";
583 $out.="# Built by " . $SysPrefs->app_title . " " . $version ."\n";
584 $out.="# ".$SysPrefs->power_url."\n";
585 $out.="# Company: ". @html_entity_decode($company, ENT_QUOTES, $_SESSION['language']->encoding)."\n";
586 $out.="# User: ".$_SESSION["wa_current_user"]->name."\n\n";
587 $out.="# Compatibility: ".get_company_pref('version_id')."\n\n";
589 // write users comment
592 $out .= "# Comment:\n";
593 $comment=preg_replace("'\n'","\n# ","# ".$comment);
594 //$comment=str_replace("\n", "\n# ", $comment);
595 foreach(explode("\n",$comment) as $line)
603 if ($mysql_enc = get_mysql_encoding_name($_SESSION['language']->encoding))
604 $out .= "\nSET NAMES $mysql_enc;\n";
606 // get auto_increment values and names of all tables
607 $res = db_query("show table status");
608 $all_tables = array();
609 while($row = db_fetch($res))
611 if (($conn["tbpref"] == "" && !preg_match('/[0-9]+_/', $row['Name'])) ||
612 ($conn["tbpref"] != "" && strpos($row['Name'], $conn["tbpref"]) === 0))
613 $all_tables[] = $row;
615 // get table structures
616 foreach ($all_tables as $table)
618 $res1 = db_query("SHOW CREATE TABLE `" . $table['Name'] . "`");
619 $tmp = db_fetch($res1);
620 $table_sql[$table['Name']] = $tmp["Create Table"];
625 if (isset($table_sql))
627 foreach($table_sql as $tablenme=>$table)
630 // save all tables, needed for creating this table in $fks
631 while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
633 $tmp_table = substr($tmp_table, $ref_pos + 12);
634 $ref_pos = strpos($tmp_table, "(");
635 $fks[$tablenme][] = substr($tmp_table, 0, $ref_pos);
640 $all_tables = order_sql_tables($all_tables, $fks);
642 // as long as no error occurred
645 foreach ($all_tables as $row)
647 $tablename = $row['Name'];
648 $auto_incr[$tablename] = $row['Auto_increment'];
652 $out.="### Structure of table `".$tablename."` ###\n\n";
654 $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
655 $out.=$table_sql[$tablename];
663 $out.="### Data of table `".$tablename."` ###\n";
665 // check if field types are NULL or NOT NULL
666 $res3 = db_query("SHOW COLUMNS FROM `" . $tablename . "`");
668 $field_null = array();
669 for ($j = 0; $j < db_num_rows($res3); $j++)
671 $row3 = db_fetch($res3);
672 $field_null[] = $row3[2]=='YES' && $row3[4]===null;
675 $res2 = db_query("SELECT * FROM `" . $tablename . "`");
678 for ($j = 0; $j < db_num_rows($res2); $j++)
680 $row2 = db_fetch_row($res2);
682 for ($k = 0; $k < $nf = db_num_fields($res2); $k++)
684 $values .= db_escape($row2[$k], $field_null[$k]);
689 $len = strlen($values);
690 if ($maxinsert < $len+1)
692 $maxinsert = EXPORT_MAX_INSERT;
695 $out .= $insert .';'; // flush insert query
702 $insert = "\nINSERT INTO `" . $tablename . "` VALUES\n";
703 $maxinsert -= strlen($insert);
711 // if saving is successful, then empty $out, else set error flag
712 if (strlen($out) > $max_size && $zip != "zip")
714 if (save_to_file($backupfile, $zip, $out))
721 $out .= $insert. ';';
722 // an error occurred! Try to delete file and return error status
726 @unlink($backupfile);
730 // if saving is successful, then empty $out, else set error flag
731 if (strlen($out) > $max_size && $zip != "zip")
733 if (save_to_file($backupfile, $zip, $out))
740 // an error occurred! Try to delete file and return error status
744 @unlink($backupfile);
748 if (save_to_file($backupfile, $zip, $out))
754 @unlink($backupfile);
760 // orders the tables in $tables according to the constraints in $fks
761 // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
762 function order_sql_tables($tables, $fks)
764 // do not order if no contraints exist
769 $new_tables = array();
772 while (count($tables) && $modified == true)
775 foreach ($tables as $key=>$row)
777 // delete from $tables and add to $new_tables
778 if (isset($fks[$row['Name']]))
780 foreach($fks[$row['Name']] as $needed)
782 // go to next table if not all needed tables exist in $existing
783 if (!in_array($needed,$existing))
787 // delete from $tables and add to $new_tables
788 $existing[] = $row['Name'];
789 $new_tables[] = $row;
791 unset($tables[$key]);
799 // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
800 // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
801 // until now, just add the lasting tables to $new_tables, return them and print a warning
802 foreach($tables as $row)
803 $new_tables[] = $row;
804 echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. WA DOES NOT SUPPORT THEM. PROBABLY THE FOLOWING BACKUP IS DEFECT!</div>";
809 // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
810 // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
811 function save_to_file($path, $zip, $fileData)
814 $backupfile = basename($path);
818 if ($zp = @gzopen($path, "a9"))
820 @gzwrite($zp, $fileData);
829 // $zip contains the timestamp
831 elseif ($zip == "zip")
833 // based on zip.lib.php 2.2 from phpMyBackupAdmin
834 // offical zip format: http://www.pkware.com/appnote.txt
836 // End of central directory record
837 $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
839 // "local file header" segment
840 $unc_len = strlen($fileData);
841 $crc = crc32($fileData);
842 $zdata = gzcompress($fileData);
844 // extend stored file name with suffix
845 // needed for decoding (because of crc bug)
846 $name_suffix = substr($zdata, -4, 4);
848 for ($i = 0; $i < 4; $i++)
849 $name_suffix2 .= sprintf("%03d", ord($name_suffix[$i]));
851 $name = substr($backupfile, 0, strlen($backupfile) - 8) . $name_suffix2 . ".sql";
854 $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
855 $c_len = strlen($zdata);
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 . '";');
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;
868 // crc32, compressed filesize, uncompressed filesize
869 $sub2 = pack('V', $crc) . pack('V', $c_len) . pack('V', $unc_len);
871 $fr = "\x50\x4b\x03\x04" . $sub1. $sub2;
873 // length of filename, extra field length
874 $fr .= pack('v', strlen($name)) . pack('v', 0);
877 // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
878 $fr .= $zdata . $sub2;
880 // now add to central directory record
881 $cdrec = "\x50\x4b\x01\x02";
882 $cdrec .= "\x00\x00"; // version made by
883 $cdrec .= $sub1 . $sub2;
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);
890 $fileData = $fr . $cdrec . $eof_ctrl_dir;
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";
895 if ($zp = @fopen($path, "w"))
897 @fwrite($zp, $fileData);
910 if ($zp = @fopen($path, "a"))
912 @fwrite($zp, $fileData);
923 function create_comp_dirs($comp_path, $comp_subdirs)
925 $index = "<?php\nheader(\"Location: ../index.php\");\n";
928 $f = @fopen("$cdir/index.php", "wb");
932 foreach($comp_subdirs as $dir)
934 @mkdir($cdir.'/'.$dir);
935 $f = @fopen("$cdir/$dir/index.php", "wb");
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'
948 function check_table($pref, $table, $field=null, $properties=null)
950 $tables = @db_query("SHOW TABLES LIKE '".$pref.$table."'");
951 if (!db_num_rows($tables))
952 return 1; // no such table or error
954 $fields = @db_query("SHOW COLUMNS FROM ".$pref.$table);
956 return 0; // table exists
958 while( $row = db_fetch_assoc($fields))
960 if ($row['Field'] == $field)
962 if (!isset($properties))
964 foreach($properties as $property => $value)
966 if ($row[$property] != $value)
967 return 3; // failed type/length check
969 return 0; // property check ok.
972 return 2; // field not found
976 Update or create setting in simple php config file.
978 function update_config_var($file, $variable, $value, $comment='')
980 if (!is_file($file) || !is_writeable($file))
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);
988 $strvalue = ($comment ? "// $comment" : '') ."\n$strvalue\n";
989 $content = preg_replace('/\?>\s*/m', $strvalue, $content, -1, $result);
991 $content .= $strvalue;
994 return file_put_contents($file, $content)!=false;