<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка действий социальной сети, доступных группе пользователей информационной группы.
 *
 * Файл: /admin/InformationSystems/action/load_site_users_group_action_information_group.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);
	
	$information_item_id = to_int($_REQUEST['information_item_id']);
	$information_groups_id = to_int($_REQUEST['information_group_id']);
	$information_groups_parent_id = to_int($_REQUEST['information_groups_parent_id']);
	$sns_action_parent_id = to_int($_REQUEST['sns_action_parent_id']);

	$InformationSystem = & singleton('InformationSystem');
	$Sns = & singleton('Sns');
	$SiteUsers = & singleton ('SiteUsers');
		
	$information_group_info = $InformationSystem->GetInformationGroup($information_groups_id);
	
	// Тип социальной сети
	$sns_type_id = $information_group_info['sns_type_id'];

	$information_system_id = to_int($_REQUEST['information_system_id']);

	$sns_info = $Sns->GetSnsAssociatedInformationSystem($information_system_id);

	$sns_id = to_int($sns_info['sns_id']);
	
	// Строим "хлебные крошки"
	$path_array = $InformationSystem->GetInformationGroupsPathArray($information_groups_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_id = to_int($_REQUEST['site_users_group_id']);

	// Получаем информацию о группе пользователей
	$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'] = 'Все пользователи';
	}
	
	// Действия над информационной группой  
	if (!$information_item_id)
	{
		$title = 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']), to_str($information_group_info['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_groups_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_groups_id}&information_system_id={$information_system_id}", 174, 'load_data'),
				'name' => sprintf($GLOBALS['MSG_information_systems']['site_users_groups_information_group_title'], to_str($information_group_info['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_groups_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_groups_id}&site_users_group_id={$site_users_group_id}", 176, '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_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);

		$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_groups_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_groups_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_groups_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_groups_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}", 176, 'load_data'),
				'name' => $title);		
	}		

	$path_array = $Sns->GetSnsActionPathArray($sns_action_parent_id);

	// Меняем порядок следования элементов в массиве на обратный
	$path_array = array_reverse($path_array, true);

	// Преобразуем идентификаторы групп в ссылки на группы.
	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_groups_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_groups_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'] . ')');
		}
	}
	$param['path_array'] = $new_path_array;

	$param['data'][] = "SELECT *, sns_action_table.sns_action_id AS key_field, site_users_group_action_sns_table.site_users_group_action_sns_access AS access, 
			{$information_item_id} AS information_item_id, {$information_groups_id} AS information_group_id, 
			{$information_groups_parent_id} AS information_groups_parent_id, {$information_system_id} AS information_system_id, 
			{$site_users_group_id} AS site_users_group_id, {$sns_action_parent_id} AS sns_action_parent_id
			 FROM  sns_action_table 
			LEFT JOIN site_users_group_action_sns_table 
			ON (sns_action_table.sns_action_id = site_users_group_action_sns_table.sns_action_id 
			AND site_users_group_action_sns_table.site_users_group_id = '{$site_users_group_id}'),
			sns_type_action_table 
			WHERE sns_action_table.sns_id = '{$sns_id}' 
			AND sns_action_table.sns_action_parent_id  = '{$sns_action_parent_id}'
			AND sns_type_action_table.sns_action_id = sns_action_table.sns_action_id
			{FILTER_STRING} GROUP BY sns_action_table.sns_action_id {ORDER_STRING} {LIMIT}";

	// Число нужных записей
	$count = "SELECT COUNT(sns_action_table.sns_action_id) AS count 
		FROM  sns_action_table LEFT JOIN site_users_group_action_sns_table 
		ON (sns_action_table.sns_action_id = site_users_group_action_sns_table.sns_action_id 
		AND site_users_group_action_sns_table.site_users_group_id = '{$site_users_group_id}'),
		sns_type_action_table 
		WHERE sns_action_table.sns_id = '{$sns_id}'
		AND sns_action_table.sns_action_parent_id  = '{$sns_action_parent_id}'
		AND sns_type_action_table.sns_action_id = sns_action_table.sns_action_id
		{FILTER_STRING} GROUP BY sns_action_table.sns_action_id ";

	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;

	// Заголовок формы
	$param['title'] = $title;

	$param['field_params'][0][868]['callback_function'] = 'callback_function_default_action';
	
	// Функция обратного вызова для действия по умолчанию
	function callback_function_default_action($field_value, $value, $row)
	{
		$DataBase = & singleton('DataBase');		
		$Sns = & singleton('Sns');
				
		$information_item_id = to_int($_REQUEST['information_item_id']);
		
		$checked = '';

		$param_access = array();
		$param_access['site_users_group_id'] = Array (0, to_int($_REQUEST['site_users_group_id']));
		$param_access['sns_action_id'] = intval($row['key_field']);
		
		// Определяем доступ к элементу
		if ($information_item_id)
		{
			$param_access['information_item_id'] = $information_item_id;

			$access = $Sns->GetAccessSiteUsers2ItemSnsAction($param_access);
		}		
		else
		{				
			$param_access['information_group_id'] = $_REQUEST['information_group_id'];
			$param_access['cache'] = false;

			$access = $Sns->GetAccessSiteUsers2SnsAction($param_access);
		}

		$checked = $access == true ? ' checked="checked" ' : '';
		?>
<input type="checkbox" disabled="disabled" <?php echo $checked; ?> name="check_0_<?php echo $row['key_field']; ?>_fv_868" />
		<?php
	}

	$param['field_params'][0][849]['callback_function'] = 'callback_function_access_action';

	// Функция обратного вызова для доступа к действию
	function callback_function_access_action($field_value, $value, $row)
	{
		$DataBase = & singleton('DataBase');		
		$Sns = & singleton('Sns');

		$information_item_id = to_int($_REQUEST['information_item_id']);

		$param_access = array();
		$param_access['site_users_group_id'] = to_int($_REQUEST['site_users_group_id']);
		$param_access['sns_action_id'] = intval($row['key_field']);

		// Определяем доступ к элементу
		if ($information_item_id)
		{
			$param_access['information_item_id'] = $information_item_id;

			$access = $Sns->GetAccessSiteUsers2ItemSnsAction($param_access);
		}
		else
		{				
			$param_access['information_group_id'] = to_int($_REQUEST['information_group_id']);
			$param_access['cache'] = false;

			$access = $Sns->GetAccessSiteUsers2SnsAction($param_access);
		}

		$checked = $access == true ? ' checked="checked" ' : '';

		?>
<input id="check_0_<?php echo $row['key_field']; ?>_fv_849"	
type="checkbox" <?php echo $checked; ?>
onclick="DoModification('id_check_0_<?php echo $row['key_field']; ?>'); RowHighlight('row_0_<?php echo $row['key_field']; ?>');"
	name="check_0_<?php echo $row['key_field']; ?>_fv_849" />
		<?php
	}
	
	///admin/InformationSystems/InformationSystems.php?admin_forms_id=179&operation=show_list_site_users_groups_information_groups&check_0_{key_field}=1
	$param['field_params'][0][878]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_groups_id}&information_item_id={$information_item_id}&site_users_group_id={site_users_group_id}&sns_id={sns_id}&sns_action_id={key_field}", 179, 'load_data');
	
	// Доп. параметры
	$admin_forms->AAdditionalParams = "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_groups_id}&information_item_id={$information_item_id}&site_users_group_id={$site_users_group_id}&sns_action_parent_id={$sns_action_parent_id}";
	
	return $param;
}

function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0:
			{
				switch ($field_name)
				{
					case 'key_field':
						{
							$field_name = 'sns_action_table.sns_action_id';
							break;
						}

					case 'access':
						{
							$field_name = 'site_users_group_action_sns_table.site_users_group_action_sns_access';
							break;
						}
					case 'sns_action_name':
						{
							$field_name = 'sns_action_table.sns_action_name';
							break;
						}
					case 'sns_action_alias':
						{
							$field_name = 'sns_action_table.sns_action_alias';
							break;
						}

					default:
						{
							$field_name = '';
							break;
						}
				}
				break;
			}
	}
}

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

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

		$kernel->ReadMode();
	}
	else
	{
		$Sns = & singleton('Sns');
		$site_users =  & singleton('SiteUsers');

		$param_access = array();		
		// $param_access['sns_id'] = to_int($_REQUEST['sns_id']);

		if (isset($param['data'][0]))
		{
			$user_access = & singleton('user_access');

			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))
				{
					$param_access['site_users_group_id']  = to_int($_REQUEST['site_users_group_id']);
					$param_access['sns_action_id'] = $key;
					$param_access['access_value']  = $row['access'];
					$param_access['information_group_id'] = to_int($_REQUEST['information_group_id']);
					$param_access['information_item_id'] = to_int($_REQUEST['information_item_id']);

					print_r ($param_access);
					$Sns->SetAccessSiteUsersGroup2SnsAction($param_access);
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}

	$param['error'] = ob_get_clean();
}

// Обработчик события "По умолчанию" списка доступа действий группе пользователей сайта
function apply_site_users_group_action_information_group_default(&$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');
			$DataBase = & singleton('DataBase');

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$key = intval($key);
					
					$information_item_id = to_int($_REQUEST['information_item_id']);
					$information_group_id = to_int($_REQUEST['information_group_id']);
					$site_users_group_id = to_int($_REQUEST['site_users_group_id']);
					
					if ($information_item_id || $information_group_id)
					{
						if ($information_item_id)
						{
							$where = " `information_items_id` = {$information_item_id}";
						}
						else
						{
							$where = " `information_groups_id` = {$information_group_id}";
						}
						// Получаем идентификатор таблицы доступности действия 
						$query = "SELECT site_users_group_action_sns_id 
							FROM site_users_group_action_sns_table 
							WHERE `sns_action_id` = {$key} 
							AND `site_users_group_id` = {$site_users_group_id} 
							AND {$where}";
							
						$resource_access_action = $DataBase->select($query);

						if (mysql_num_rows($resource_access_action) > 0)
						{
							$row_access_action = mysql_fetch_assoc($resource_access_action);	
							
							// Удаляем из таблицы с правами изменения доступа к действию соответствующие записи 
							$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'];	
							
							$DataBase->query($query);
							
							$query = "DELETE FROM site_users_group_action_sns_table 
							WHERE `sns_action_id` = {$key} 
							AND `site_users_group_id` = {$site_users_group_id} 
							AND {$where}";
						
							$DataBase->query($query);
						}
					
						
					}														
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}

	$param['error'] = ob_get_clean();
}

?>