<?php
require_once('env-parser.php');
require_once('file-util.php');

function admin_password_crypt($value)
{
    return md5($value);
}

function get_localized_schema_files()
{
	$schema_files = array( 'schema.sql' => 'main' );
	$schema_files['admin_user.sql'] = 'main';
	
	//Set schema_version
	$schema_files['schema_schema_version.sql'] = 'main';

	$sample_data = fetch_env_var('SETTINGS_sample_data');
	if (strlen($sample_data) > 0 && $sample_data == 'no') {
		return $schema_files;
	}
	
	//check if setting id is install_sample_data (APS 1.2)
	$sample_data_aps12 = fetch_env_var('SETTINGS_install_sample_data');
	if (strlen($sample_data_aps12) > 0 && $sample_data_aps12 == '0') {
		return $schema_files;
	}

	$locale = fetch_env_var('SETTINGS_locale');
	$fname = "${locale}_data.sql";
	if (!@file_exists($fname))
	{
		$fname = 'en-GB_data.sql';
	}
	$schema_files[$fname] = 'main';

	return $schema_files;
}

function rebuild_config_file($old_config_file, $file_source, $file_dest, $meta_settings) {
    $file_content = read_file($file_source);
	
	require_once "$old_config_file";
	$old_conf = new JConfig();

	foreach (get_object_vars($old_conf) as $key => $value) {
		foreach ($meta_settings as $field) {
			if ($key == $field) {
				continue 2;
			}
		}
		$file_content = preg_replace('/public \$'.$key.' = .*?;\n/', 'public \$'.$key." = '".php_quote($value)."';\n", $file_content);
	}
    write_file($file_dest, $file_content);
}

function get_additional_modify_hash()
{
    $parameters = array();
    $parameters['@@SECRET_KEY@@'] = genRandomPassword(16);
    return $parameters;
}

function genRandomPassword($length = 8)
{
        $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $len = strlen($salt);
        $makepass = '';
        mt_srand(10000000 * (double) microtime());

        for ($i = 0; $i < $length; $i ++) {
                $makepass .= $salt[mt_rand(0, $len -1)];
        }

        return $makepass;
}

function install_extra_component($root_dir, $locale, $prefix) {
	// install localization and components only in not migration mode
		
	if (version_compare(PHP_VERSION, '5.3.1', '<'))
	{
		//problem on Plesk ignoring php version requirement
		return;
	}		
	install_component($locale.'_joomla_lang_full.zip', $root_dir);
	install_component('com_extplorer.zip', $root_dir);
	install_component('com_akeeba.zip', $root_dir);
	install_component('plugin_googlemap.zip', $root_dir);
	install_component('pkg_xmap.zip', $root_dir);
	install_component('plg_autologin.zip', $root_dir);
	//Enable plg_autologin by default
	enable_plg_autologin($prefix);
}


function enable_plg_autologin($prefix)
{
	$db_id = "main";
	mysql_db_connect(get_db_address($db_id),
			get_db_login($db_id),
			get_db_password($db_id),
			get_db_name($db_id));

	$result = mysql_query("UPDATE `".$prefix."extensions` SET `enabled`=1, `params`='{\"urlredirect\":\"\",\"authmethod\":\"0\"}' WHERE `name`='System - Autologin' AND `type`='plugin' AND `element`='autologin';");
}


function install_component($zip_file, $root_dir)
{
	if (version_compare(PHP_VERSION, '5.3.1', '<'))
	{
		//problem on Plesk ignoring php version requirement
		return;
	}

	defined('APS_EXTENSION_INSTALL') || define('APS_EXTENSION_INSTALL', 'on');
	$script_dir = getcwd();
	chdir($root_dir);
	ob_start();
	require_once($root_dir."/cli/install_package_cli.php");
	$joomlaExtensionFromAPS = new InstallJoomlaExtensionFromAPS();
	$joomlaExtensionFromAPS->install($root_dir."/tmp/distributives/${zip_file}");
	 if (ob_get_length() > 0) {
	ob_end_clean();
	}
	chdir($script_dir);
}


/************************************************************************/
/* 						Get Joomla Admin User Id						*/
/* 		Old Joomla APS Admin User Id is diferent (like Joomla 2.5.1)	*/
/************************************************************************/
function getJoomlaAdminUserId($prefix)
{
	$joomlaAdminUserId=62;
	$db_id = "main";
	mysql_db_connect(get_db_address($db_id),
			get_db_login($db_id),
			get_db_password($db_id),
			get_db_name($db_id));

	$result = mysql_query("SELECT `id` FROM `".$prefix."users` LIMIT 1");
	if ($result)
	{
		$joomlaAdminUserId = mysql_result($result, 0);
	}
	return $joomlaAdminUserId;
}


/************************************************************************/
/* 					Delete Old Joomla Files (Plesk bug)					*/
/************************************************************************/
function deleteOldJoomlaFiles($root_dir) {
	$old_filelist = 'old_joomla_files.files';
	if (file_exists($old_filelist)) {
		$lines = file($old_filelist);
		foreach ($lines as $lnum => $fpath) {
			$fpath = rtrim($fpath, "\r\n");
			if (file_exists($root_dir ."/".$fpath)) {
				@unlink($root_dir."/".$fpath);
			}
		}
	}
}

/* 
/* removing 1.7.x.sql files to avoid error message in Extensions -> Database
/* If these files present, there is 2 messages of kind "Table 'content' does not have column 'title_alias' with type 'VARCHAR(255)'. (From file 1.7.3-2011-10-15.sql.)"
*/
function removeJoomla17UpgradeScripts($root_dir) {
	$mysql_updates_dir = "$root_dir/administrator/components/com_admin/sql/updates/mysql/";
	if ($handle = @opendir($mysql_updates_dir)) {
		while (strlen($file = readdir($handle))) {
			if (preg_match("/^1\.7\..*\.sql$/", $file)) {
				@unlink($mysql_updates_dir.$file);
			}
		}
	}
	@closedir($handle);
}

function get_table_prefix($db_modify_hash,$psa_modify_hash) {
    $dbprefix = $db_modify_hash['@@DB_MAIN_PREFIX@@']; // this is our default prefix. Get the one from configuration.php just in case
    $config_content = read_file($psa_modify_hash['@@ROOT_DIR@@'].'/configuration.php');
    if (preg_match('#public \$dbprefix *= *[\'\"]([^\'\"]*)[\'\"]#m', $config_content, $mres)) {
        $dbprefix = $mres[1];
    }
    return $dbprefix;
}


?>
