<?php
$CONFIG_KEYS =
array(
'id',
'debug',
'log',
'dblog',
'slash',
'language',
'default_country_id',
'default_timezone',
'default_dst',
'default_currency',
'default_date_format',
'default_date_seperator',
'default_time_format',
'default_first_weekday',
'default_decimal_seperator',
'default_thousands_seperator',
'theme',
'allow_themes',
'allow_password_change',
'allow_registration',
'allow_duplicate_email',
'auto_activate_accounts',
'notify_admin_of_registration',
'registration_fields',
'required_registration_fields',
'register_modules_read',
'register_modules_write',
'register_user_groups',
'register_visible_user_groups',
'host',
'full_url',
'title',
'webmaster_email',
'root_path',
'tmpdir',
'local_path',
'local_url',
'max_users',
'refresh_rate',
'login_screen',
'db_type',
'db_host',
'db_name',
'db_user',
'db_pass',
'auth_sources',
'sync_auth_source_key',
'mime_types_file',
'file_storage_path',
'max_file_size',
'user_quota',
'dav_switch',
'dav_apachedir',
'dav_drafts',
'dav_auth',
'dav_alias',
'dav_accessfilename',
'name_of_sharedir',
'mailer',
'smtp_server',
'smtp_port',
'smtp_username',
'smtp_password',
'email_connectstring_options',
'user_home_dirs',
'email_vacation',
'max_attachment_size',
'cmd_zip',
'cmd_unzip',
'cmd_tar',
'cmd_chpasswd',
'cmd_sudo',
'cmd_quota',
'cmd_alias',
'cmd_edquota',
'cmd_wbxml2xml',
'cmd_xml2wbxml',
'cmd_tnef',
'quota_protouser',
'force_fullscreen',
'logout_url',
'use_jupload',
'db_charset'
);

function is__writable($path) {
//will work in despite of Windows ACLs bug
//NOTE: use a trailing slash for folders!!!
//see http://bugs.php.net/bug.php?id=27609
//see http://bugs.php.net/bug.php?id=30931

    if ($path{strlen($path)-1}=='/') // recursively return a temporary file path
        return is__writable($path.uniqid(mt_rand()).'.tmp');
    else if (is_dir($path))
        return is__writable($path.'/'.uniqid(mt_rand()).'.tmp');
    // check tmp file for read/write capabilities
    $rm = file_exists($path);
    $f = @fopen($path, 'a');
    if ($f===false)
        return false;
    fclose($f);
    if (!$rm)
        unlink($path);
    return true;
}

function escape_config_value($value)
{
	return str_replace('\\"', '"', addslashes($value));
}

function save_config($config)
{
	global $CONFIG_KEYS, $CONFIG_FILE;

	//create mode needs some special handling

	$config_data = "<?php\n/*Configuration file generated by Group-Office*/\n";

	for($i=0;$i<count($CONFIG_KEYS);$i++)
	{
		$config_data .= '$config[\''.$CONFIG_KEYS[$i].'\']=';

		if(is_bool($config->$CONFIG_KEYS[$i]))
		{
			$value = $config->$CONFIG_KEYS[$i] ? 'true' : 'false';
			$config_data .= $value.";\n";
		}else
		{
			if($CONFIG_KEYS[$i]=='create_mode' && !is_string($config->create_mode))
			{
				$config->create_mode=strval(decoct($config->create_mode));
				/*if(strlen($config->create_mode)==3)
				{
					$config->create_mode ='0'.$config->create_mode;
				}*/
			}
			$config_data .= "'".escape_config_value($config->$CONFIG_KEYS[$i])."';\n";			
		}
	}

	$config_data .= "?>";

	if (!$fp = fopen($CONFIG_FILE, 'w+'))
	{
		exit("Failed to open config file");
	}elseif(!fwrite($fp, $config_data))
	{
		exit("Failed to write to config file");
	}else
	{
		return fclose($fp);
	}
}

function whereis($cmd)
{
	exec('whereis '.$cmd, $return);
	
	if(isset($return[0]))
	{
		$locations = explode(' ', $return[0]);
		if(isset($locations[1]))
		{
			return $locations[1];
		}
		return false;
	}
}

function return_bytes($val) {
   $val = trim($val);
   $last = strtolower($val{strlen($val)-1});
   switch($last) {
       // The 'G' modifier is available since PHP 5.1.0
       case 'g':
           $val *= 1024;
       case 'm':
           $val *= 1024;
       case 'k':
           $val *= 1024;
   }
   return $val;
}

function install_required_modules()
{
	global $GO_CONFIG,$GO_MODULES, $GO_SECURITY;
	
	require_once ($GO_CONFIG->class_path.'filesystem.class.inc');
	$fs = new filesystem();
	
	$modules = $fs->get_folders($GO_CONFIG->module_path);
	$module_count = count($modules);
	while($module = array_shift($modules))
	{
		if (!$sql_module = $GO_MODULES->get_module($module['name']))
		{
			$version = '';
			$sort_order = '1000';			
	
			$info_file = $module['path'].'/module.info';
			$module_info = $GO_MODULES->get_module_info($module['name']);			
			$required = isset($module_info['required']) ? $module_info['required'] : false;
			
			if($required)
			{			
				$version = $module_info['version'];
				$sort_order = isset($module_info['sort_order']) ? $module_info['sort_order'] : '1000';
				$admin_menu = isset($module_info['admin_menu']) ? $module_info['admin_menu'] : '0';
				
				$acl_read = $GO_SECURITY->get_new_acl('Module read: '.$module['name'], 0);
				$acl_write = $GO_SECURITY->get_new_acl('Module write: '.$module['name'], 0);
		
				if ($acl_read > 0 && $acl_write > 0) {
					if (!$GO_MODULES->add_module($module['name'], $version, $acl_read, $acl_write, $sort_order, $admin_menu)) {
						$feedback = '<p class="Error">'.$strSaveError.'</p>';
					}
				} else {
					$GO_SECURITY->delete_acl($acl_read);
					$GO_SECURITY->delete_acl($acl_write);
				}
			}
		}
	}
}
