<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка групп пользователей сайта, имеющих право изменять доступ к действию для другой группы пользователей в информационной группе.
 * 
 * Файл: /admin/InformationSystems/action/load_site_users_group_change_action.php
 * 
 * @author Hostmake LLC
 * @version 5.x
 */
function LoadAjaxData(&$admin_forms)
{
	$on_page = $admin_forms->GetOnPageCount();

	$page = to_int($_REQUEST['limit']);

	$begin = ($page == 0) ? 0 : ($page - 1) * $on_page;

	$param = array();

	$param['limit'][0] = array('begin' => $begin, 'count' => $on_page);

	$Sns = & singleton('Sns');
	$SiteUsers = & singleton('SiteUsers');
	$DataBase = & singleton('DataBase');	
	$InformationSystem = &singleton('InformationSystem');

	$site_id = CURRENT_SITE;
		
	
	$sns_id = to_int($_REQUEST['sns_id']);
	$site_users_group_id = to_int($_REQUEST['site_users_group_id']);
	$sns_action_id = to_int($_REQUEST['sns_action_id']);
	$information_system_id = to_int($_REQUEST['information_system_id']);
	$information_groups_parent_id = to_int($_REQUEST['information_groups_parent_id']);
	$information_group_id = to_int($_REQUEST['information_group_id']);
	$information_item_id = to_int($_REQUEST['information_item_id']);
			
	// Получаем информацию о действии социальной сети, для которого определяем группы пользователей, имеющих право изменять доступ к данному действию текущей группе пользователей. 
	$row_sns_action = $Sns->GetSnsAction($sns_action_id);
	
	if (!$information_item_id)
	{
		$query = "SELECT site_users_group_action_sns_id FROM site_users_group_action_sns_table 
			WHERE `site_users_group_id` = '{$site_users_group_id}' 
			AND `sns_action_id` = '{$sns_action_id}' 
			AND `information_groups_id` = '{$information_group_id }'";
	}	
	else
	{
		$query = "SELECT site_users_group_action_sns_id FROM site_users_group_action_sns_table 
			WHERE `site_users_group_id` = '{$site_users_group_id}' 
			AND `sns_action_id` = '{$sns_action_id}' 
			AND `information_items_id` = '{$information_item_id }'";
	}
		
	$resource = $DataBase->select($query);
	
	if (mysql_num_rows($resource)== 1)
	{
		$row = mysql_fetch_assoc($resource);		
		$site_users_group_action_sns_id = $row['site_users_group_action_sns_id'];		
		
		$param['data'][] = "SELECT DISTINCT site_users_group_table.site_users_group_id AS key_field, site_users_group_name, site_users_group_action_change_sns_table.site_users_group_action_change_sns_access
			FROM site_users_group_table
			LEFT JOIN site_users_group_action_change_sns_table ON ( site_users_group_table.site_users_group_id = site_users_group_action_change_sns_table.site_users_group_id
			AND site_users_group_action_sns_id ='{$site_users_group_action_sns_id}')
			LEFT JOIN sns_site_users_group_table ON ( sns_site_users_group_table.site_users_group_id = site_users_group_table.site_users_group_id )
			WHERE sns_site_users_group_table.sns_id = '{$sns_id}'
			{FILTER_STRING} {ORDER_STRING} {LIMIT}";
		
		// Число нужных записей
		$count = "SELECT COUNT(sns_site_users_group_table.sns_site_users_group_id) AS count 
			FROM site_users_group_table
			LEFT JOIN site_users_group_action_change_sns_table ON ( site_users_group_table.site_users_group_id = site_users_group_action_change_sns_table.site_users_group_id
			AND site_users_group_action_sns_id ='{$site_users_group_action_sns_id}')
			LEFT JOIN sns_site_users_group_table ON ( sns_site_users_group_table.site_users_group_id = site_users_group_table.site_users_group_id )
			WHERE sns_site_users_group_table.sns_id = '{$sns_id}'
			{FILTER_STRING} ";
	}
	else
	{
	
		$param['data'][] = "SELECT DISTINCT site_users_group_table.site_users_group_id AS key_field, site_users_group_name, '0' AS site_users_group_action_change_sns_access
			FROM site_users_group_table
			LEFT JOIN site_users_group_action_sns_table ON ( site_users_group_table.site_users_group_id = site_users_group_action_sns_table.site_users_group_id
			AND site_users_group_action_sns_table.site_users_group_id = '{$site_users_group_id}'
			AND site_users_group_action_sns_table.sns_action_id = '{$sns_action_id}' )
			LEFT JOIN sns_site_users_group_table ON ( sns_site_users_group_table.site_users_group_id = site_users_group_table.site_users_group_id )
			WHERE sns_site_users_group_table.sns_id = '{$sns_id}'
			{FILTER_STRING} {ORDER_STRING} {LIMIT}";
		
		// Число нужных записей
	$count = "SELECT COUNT(sns_site_users_group_table.sns_site_users_group_id) AS count 
			FROM site_users_group_table
			LEFT JOIN site_users_group_action_sns_table ON ( site_users_group_table.site_users_group_id = site_users_group_action_sns_table.site_users_group_id
			AND site_users_group_action_sns_table.site_users_group_id = '{$site_users_group_id}'
			AND site_users_group_action_sns_table.sns_action_id = '{$sns_action_id}' )
			LEFT JOIN sns_site_users_group_table ON ( sns_site_users_group_table.site_users_group_id = site_users_group_table.site_users_group_id )
			WHERE sns_site_users_group_table.sns_id = '{$sns_id}'
			{FILTER_STRING} ";
	}
	
	//GROUP BY site_users_group_table.site_users_group_id
	
	// Получаем информацию о группе пользователей
	$site_users_group_info = $SiteUsers->GetSiteUsersGroup($site_users_group_id);
	
	/////////////////////////////////////////
	
	// Строим "хлебные крошки"
	$path_array = $InformationSystem->GetInformationGroupsPathArray($information_group_id, $information_system_id);

	$new_path_array = array();

	$new_path_array[] = array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', '', 11, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', '', 11, 'load_data'),
	'name' => $GLOBALS['MSG_information_systems']['show_information_systems_title']);
	
	// Меняем порядок следования элементов в массиве на обратный
	$path_array = array_reverse($path_array, true);

	if (!$information_item_id)
	{
		// Получаем информацию о последнем элементе массива, содержащего путь
		$path_array_end = end($path_array);
		
		// Удаляем последний элемент из пути для удаления ссылки на информационную группу
		unset($path_array[$path_array_end['information_groups_id']]);
	}	

	// Преобразуем идентификаторы групп в ссылки на группы.
	if ($path_array)
	{
		foreach ($path_array as $information_groups_parent_id => $value)
		{
			$new_path_array[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
			'name' => $value['information_groups_name']);
		}
	}
	

	// Получаем информацию о группе пользователей
	$site_users_group_resource = $SiteUsers->SelectUserType($site_users_group_id);

	$site_users_group_row = mysql_fetch_array($site_users_group_resource);

	if (!$site_users_group_id)
	{
		$site_users_group_row['site_users_group_name'] = 'Неавторизованные';
	}
	
	// Получаем информацию о действии
	$row_sns_action = $Sns->GetSnsAction($sns_action_id);
	
	$path_array = $Sns->GetSnsActionPathArray($row_sns_action['sns_action_parent_id']);	
	
	// Меняем порядок следования элементов в массиве на обратный
	$path_array = array_reverse($path_array, true);		
		
	// Действия над информационной группой  
	if (!$information_item_id)
	{	
		$information_group_info = $InformationSystem->GetInformationGroup($information_group_id);
		
		$information_groups_name = to_str($information_group_info['information_groups_name']);
		
		$title = sprintf($GLOBALS['MSG_information_systems']['site_users_action_change_information_group_title'], to_str($row_sns_action['sns_action_name']), to_str($site_users_group_row['site_users_group_name']), $information_groups_name);

		$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_system_id={$information_system_id}", 174, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_system_id={$information_system_id}", 174, 'load_data'),
				'name' => sprintf($GLOBALS['MSG_information_systems']['site_users_groups_information_group_title'], $information_groups_name));
				
		$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}", 176, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}", 176, 'load_data'),
				'name' => sprintf($GLOBALS['MSG_information_systems']['site_users_information_group_title'], $GLOBALS['MSG_information_systems']['site_users_information_group_accessed_actions'], to_str($site_users_group_row['site_users_group_name']), $information_groups_name));			
				
		// Преобразуем идентификаторы групп в ссылки на группы.
		if ($path_array)
		{
			foreach ($path_array as $value)
			{
				$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_action_parent_id={$value['sns_action_id']}", 176, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_action_parent_id={$value['sns_action_id']}", 176, 'load_data'),
				'name' => $value['sns_action_name'] . ' (' . $value['sns_action_alias'] . ')');
			}
		}
		
		$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_id={$sns_id}&sns_action_id={$sns_action_id}", 179, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_id={$sns_id}&sns_action_id={$sns_action_id}", 179, 'load_data'),
				'name' => $title);						
	}
	else // Действия над информационным элементом
	{
		$item_row = $InformationSystem->GetInformationSystemItem($information_item_id);
		$item_name = to_str($item_row['information_items_name']);
		
		$title = sprintf($GLOBALS['MSG_information_systems']['site_users_action_change_information_item_title'], to_str($row_sns_action['sns_action_name']), to_str($site_users_group_row['site_users_group_name']),  $item_name);

		$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&information_system_id={$information_system_id}", 174, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&information_system_id={$information_system_id}", 174, 'load_data'),
				'name' => sprintf($GLOBALS['MSG_information_systems']['site_users_groups_information_item_title'], $item_name));

		$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}", 176, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}", 176, 'load_data'),
				'name' => sprintf($GLOBALS['MSG_information_systems']['site_users_information_item_title'], $GLOBALS['MSG_information_systems']['site_users_information_group_accessed_actions'], to_str($site_users_group_row['site_users_group_name']), $item_name));	

		// Преобразуем идентификаторы групп в ссылки на группы.
		if ($path_array)
		{
			foreach ($path_array as $value)
			{
				$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_action_parent_id={$value['sns_action_id']}", 176, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_action_parent_id={$value['sns_action_id']}", 176, 'load_data'),
				'name' => $value['sns_action_name'] . ' (' . $value['sns_action_alias'] . ')');
			}
		}
		
		$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_id={$sns_id}&sns_action_id={$sns_action_id}", 179, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_id={$sns_id}&sns_action_id={$sns_action_id}", 179, 'load_data'),
				'name' => $title);	
	}		

	//$param['path_array'] = $new_path_array;
	
	////////////////////////////////////////////////
	$param['path_array'] = $new_path_array;
	
	
	$param['field_params'][0][882]['callback_function'] = 'callback_function_default_change_action';
	
	// Функция обратного вызова для доступа к ограничению доступности действия по умолчанию
	function callback_function_default_change_action($field_value, $value, $row)
	{
		$DataBase = & singleton('DataBase');		
		$Sns = & singleton('Sns');
						
		$information_item_id = to_int($_REQUEST['information_item_id']);
		
		$action_id = to_int($_REQUEST['sns_action_id']);
		$change_access_action_site_users_group_id = $row['key_field'];
		$access_action_site_users_group_id = to_int($_REQUEST['site_users_group_id']);
		
		if ($information_item_id)
		{
			$information_group_id = to_int($_REQUEST['information_group_id']);
			
		}
		else
		{
			$information_group_id = to_int($_REQUEST['information_groups_parent_id']);
		}			 
		
		$access = $Sns->IssetActionChangeAccessSiteUsersGroup4InformationGroup($action_id, $change_access_action_site_users_group_id, $access_action_site_users_group_id, $information_group_id);
	
		$checked = $access == true ? ' checked="" ' : '';			
		?>
<input
	type="checkbox" disabled="disabled" <?php echo $checked; ?>
	name="check_0_<?php echo $change_access_action_site_users_group_id; ?>_fv_882" />
		<?php


	}
	
	$param['field_params'][0][881]['callback_function'] = 'callback_function_change_action';
	
	// Функция обратного вызова для доступа к ограничению доступности действия по умолчанию
	function callback_function_change_action($field_value, $value, $row)
	{
		$DataBase = & singleton('DataBase');		
		$Sns = & singleton('Sns');
						
		$information_item_id = to_int($_REQUEST['information_item_id']);
		$information_group_id = to_int($_REQUEST['information_group_id']);
		$action_id = to_int($_REQUEST['sns_action_id']);
		$change_access_action_site_users_group_id = $row['key_field'];
		$access_action_site_users_group_id = to_int($_REQUEST['site_users_group_id']);
		
		if ($information_item_id)
		{
			$access = $Sns->IssetActionChangeAccessSiteUsersGroup4InformationItem($action_id, $change_access_action_site_users_group_id, $access_action_site_users_group_id, $information_item_id);
		}
		else
		{
			$access = $Sns->IssetActionChangeAccessSiteUsersGroup4InformationGroup($action_id, $change_access_action_site_users_group_id, $access_action_site_users_group_id, $information_group_id);
		}			 
	
		$checked = $access == true ? ' checked="" ' : '';			
		?>
<input
	type="checkbox" <?php echo $checked; ?>
	onclick="DoModification('id_check_0_<?php echo $change_access_action_site_users_group_id;?>'); RowHighlight('row_0_<?php echo $change_access_action_site_users_group_id;?>');"
	id="id_check_0_<?php echo $change_access_action_site_users_group_id; ?>_fv_881"
	name="check_0_<?php echo $change_access_action_site_users_group_id; ?>_fv_881" />
		<?php


	}

	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	//$param['menus'] = $menu_array;
	$param['title'] = $title;
	
	// Доп. параметры
	$admin_forms->AAdditionalParams = "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_group_id}&information_item_id={$information_item_id }&site_users_group_id={$site_users_group_id}&sns_id={$sns_id}&sns_action_id={$sns_action_id}";

	return $param;
}
function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0:
			{
				switch ($field_name)
				{				
					case 'key_field':
						{
							$field_name = 'site_users_group_table.site_users_group_id';
							break;
						}					
				}
				break;
			}
	}
}

// Обработчик события "Применить" списка групп пользователей, имеющих право изменять доступа к действию группе пользователей сайта
function apply_changes(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{		

		if (isset($param['data'][0]))
		{
			$user_access = & singleton('user_access');			
			$Sns = & singleton('Sns');
			$site_users =  & singleton('SiteUsers');
			
			foreach ($param['data'][0] as $key => $row)
			{								
				// Определяем информацию об объекте
				$object_row = $site_users->GetSiteUsersGroup($key);

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{		
					$action_id = $_REQUEST['sns_action_id'];					
					$access_action_site_users_group_id = $_REQUEST['site_users_group_id'];
					$change_access_action_site_users_group_id  = $key;
					$access_value = $row['site_users_group_action_change_sns_access'];
										
					$information_item_id = to_int($_REQUEST['information_item_id']);
					
					if ($information_item_id)
					{
						$Sns->SetActionChangeAccessSiteUsersGroup4InformationItem($action_id, $change_access_action_site_users_group_id, $access_action_site_users_group_id, $information_item_id, $access_value);
					}
					else
					{
						$information_group_id = to_int($_REQUEST['information_group_id']);
						
						$Sns->SetActionChangeAccessSiteUsersGroup4InformationGroup($action_id, $change_access_action_site_users_group_id, $access_action_site_users_group_id, $information_group_id, $access_value);					
					}
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}
	$error = ob_get_clean();
	$param['error'] = $error;
}

// Обработчик события "По умолчанию" списка групп пользователей, имеющих право изменять доступа к действию информационной группе/элементу пользователей сайта
function apply_default_changes(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		if (isset($param['data'][0]))
		{
			$user_access = & singleton('user_access');
			$DataBase = & singleton('DataBase');
			$site_users =  & singleton('SiteUsers');
			
			foreach ($param['data'][0] as $key => $row)
			{								
				// Определяем информацию об объекте
				$object_row = $site_users->GetSiteUsersGroup($key);

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{		
					$action_id = $_REQUEST['sns_action_id'];					
					$access_action_site_users_group_id = $_REQUEST['site_users_group_id'];
					$change_access_action_site_users_group_id  = intval($key);
					$access_value = $row['site_users_group_action_change_sns_access'];
										
					$information_item_id = to_int($_REQUEST['information_item_id']);
					
					if ($information_item_id)
					{						
						$where = " AND `information_items_id` = '{$information_item_id}'";
					}
					else
					{
						$information_group_id = to_int($_REQUEST['information_group_id']);
						
						$where = " AND `information_groups_id` = '{$information_group_id}'";
					}
					$query = "SELECT site_users_group_action_sns_id FROM site_users_group_action_sns_table 
								WHERE `site_users_group_id` = '{$access_action_site_users_group_id}' 
								AND `sns_action_id` = '{$action_id}' $where";
						
					$resource = $DataBase->select($query);
					
					while($row_access_action = mysql_fetch_assoc($resource))
					{
							$query = "DELETE FROM site_users_group_action_change_sns_table 
							WHERE `site_users_group_action_sns_id` = {$row_access_action['site_users_group_action_sns_id']}
							AND `site_users_group_id` = {$change_access_action_site_users_group_id}";
							
							$DataBase->query($query);
					}
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}
	$error = ob_get_clean();
	$param['error'] = $error;
}
?>