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



$migrations->Run('01_gallery_administrators_migration.php', <<<'DB_UPDATE_FILE'
<?php
//This migration supports the move of the gallery admin functionality from the back end of the system to the front end.
//Specifically, this script takes the old backend admins and portsa them into the newly defined permissions class.
//This is so that users should experience the same permissions context without their admins having to manually add their
//admins to the new permissions class.
/** @var \Claromentis\Setup\SetupFacade $migrations */
$db = $migrations->GetDb();
//Define permissions information
$class_id = 141;
$object_id = 1;
$perm_owner_class_id = 1;
$old_rights = 1;
$new_rights = 7;
$object_code = "image_gallery";

//Get list of current gallery admins
//shorthand query
$current_gallery_admins_results = $db->query("SELECT a.object_code, a.user_id, a.rights FROM simple_acl a WHERE a.object_code eq:str:object_code AND ".$db->bitwiseand('a.rights', $old_rights)." = int:rights;", $object_code, $old_rights);

while($row = $current_gallery_admins_results->fetchArray()){

	//Shorthand query
	$existing_perms_results = $db->query("SELECT a.class_id, a.object_id, a.perm_owner_class_id, a.perm_owner_id FROM permissions a WHERE a.perm_owner_id eq:int:user_id AND a.class_id eq:int:class_id",$row['user_id'], $class_id);

	if($existing_perms_results->hasData()){

		//Do nothing
	} else {
		//Insert permission into the database
		//Shorthand query
		$db->DisableTokenCheck();
		$insert_result = $db->query("INSERT INTO permissions (class_id, object_id, perm_owner_class_id, perm_owner_id, rights) VALUES (int:class_id,int:object_id,int:perm_owner_class_id,int:user_id,int:rights);",$class_id,$object_id,$perm_owner_class_id,$row['user_id'], $new_rights);
		$db->EnableTokenCheck();
	}
}

DB_UPDATE_FILE
);


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