<?php
$_db_migration_to = '28.06';
if (!isset($migrations) || !is_object($migrations))
	die("This file cannot be executed directly");
$migrations->CheckValid($_db_migration_to);
//===========================================================================================



$migrations->Run('01_hpl_zone_start_month.php', <<<'DB_UPDATE_FILE'
<?php
/** @var \Claromentis\Setup\SetupFacade $migrations */
$db = $migrations->GetDb();

$db->AddColumn("hpl_zones_config", "year_start", "INT NOT_NULL DEFAULT 1");

$config = $migrations->GetConfigFull();
$year_start = $config->Get('cfg_holidays_year_start');

if (!$year_start)
	$year_start = 1;

$db->query("UPDATE hpl_zones_config SET year_start=int:start", $year_start);

$config->Delete('cfg_holidays_year_start');
$config->Save();

DB_UPDATE_FILE
);


$migrations->Run('01_infocapture_noticefield_directory.php', <<<'DB_UPDATE_FILE'
<?php

$base = realpath($GLOBALS['INTRANET'].'/../').'/';
$new_dir = $base.'appdata/infocapture/field/';

// Create $new_dir path with 0777 permissions
if (!is_dir($new_dir))
	mkdir($new_dir, 0777, true);
DB_UPDATE_FILE
);


$migrations->Run('02_remove_hpl_stat.php', <<<'DB_UPDATE_FILE'
<?php
/** @var \Claromentis\Setup\SetupFacade $migrations */
$db = $migrations->GetDb();

//$db->DropTable('hpl_stat');

DB_UPDATE_FILE
);


$migrations->Run('03_add_year_closed.php', <<<'DB_UPDATE_FILE'
<?php
/** @var \Claromentis\Setup\SetupFacade $migrations */
$db = $migrations->GetDb();

$db->AddColumn('hpl_users', "is_year_closed", "BOOL DEFAULT 0");

$db->query("UPDATE hpl_users SET is_year_closed=1 WHERE year<int:year", date('Y')-1);

DB_UPDATE_FILE
);


$migrations->Run('03_delete_conf_common_year.php', <<<'DB_UPDATE_FILE'
<?php
/** @var \Claromentis\Setup\SetupFacade $migrations */
$config = $migrations->GetConfigFull();

$config->Delete('cfg_holidays_common_year');
$config->Save();
DB_UPDATE_FILE
);


$migrations->Run('03_oauth_upgrade.php', <<<'DB_UPDATE_FILE'
<?php

/** @var $migrations \Claromentis\Setup\SetupFacade */
$db = $migrations->GetDb();

// The session tables are not needed anymore

$db->DropColumn('oauth_auth_codes', 'session_id');
$db->DropIndex('oauth_access_tokens', 'oauth_access_tokens_session_id_foreign');
$db->DropColumn('oauth_access_tokens', 'session_id');
$db->DropTable('oauth_sessions');
$db->DropTable('oauth_session_scopes');

// The new session system doesn't seem to store scopes in the DB with auth codes now.

$db->DropTable('oauth_auth_code_scopes');
DB_UPDATE_FILE
);


$migrations->Run('04_generate_oauth2_keys.php', <<<'DB_UPDATE_FILE'
<?php

// Create private/public key pair for OAuth2

/** @var $migrations \Claromentis\Setup\SetupFacade */
$key_dir = $migrations->GetDataDir() . '/config';

$result = false;

// Try the extension first
if (function_exists('openssl_pkey_new'))
	$result = CreateKeysViaExtension($key_dir);

// Next try the command line
if (!$result)
	$result = CreateKeysViaShell($key_dir);

if ($result)
	FixKeyPerms($key_dir);

function CreateKeysViaExtension($key_dir)
{
	$res = openssl_pkey_new([
		'private_key_type' => OPENSSL_KEYTYPE_RSA,
		'private_key_bits' => 1024
	]);
	if ($res === false)
		return false;
	$success = openssl_pkey_export_to_file($res, $key_dir . '/oauth_private_key');
	if (!$success)
		echo "Error saving private key to DATA_DIR/oauth_private_key\n";

	$public_res = openssl_pkey_get_details($res);
	$public_key = $public_res["key"];
	$public_success = file_put_contents($key_dir . '/oauth_public_key', $public_key);

	if ($public_success === false)
	{
		echo "Error saving public key to DATA_DIR/oauth_public_key\n";
		$success = false;
	}

	return $success;
}

function CreateKeysViaShell($key_dir)
{
	$return_val = 0;
	exec('openssl genrsa -out ' . $key_dir . '/oauth_private_key 1024 2>&1', $result, $code);
	$return_val += $code;

	exec('openssl rsa -in ' . $key_dir . '/oauth_private_key -pubout -out ' . $key_dir . '/oauth_public_key 2>&1', $result, $code);
	$return_val += $code;

	return $return_val === 0;
}

function FixKeyPerms($key_dir)
{
	if ((file_exists($key_dir . '/oauth_private_key')) &&
		(file_exists($key_dir . '/oauth_public_key')))
	{
		// The league OAuth2 library requires either 600 or 660 and will throw errors otherwise
		chmod($key_dir . '/oauth_private_key', 0660);
		chmod($key_dir . '/oauth_public_key', 0660);
	}
}
DB_UPDATE_FILE
);


//===========================================================================================
$migrations->SetVersion('28.06');
