<?php 
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка форм Центра администрирования со ссылкой на доступ пользователей группы к действиям форм.
 * 
 * Файл: /admin/users_access/action/load_users_type_avents_access_forms.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);


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

	if (isset($_REQUEST['site_id']))
	{
		$site_id = to_int($_REQUEST['site_id']);
	}
	elseif (isset($_SESSION['current_site_id']))
	{

		$site_id = to_int($_SESSION['current_site_id']);
	}
	else
	{
		$site_id = 0;
	}

	$admin_forms->AddExternalReplace('{SITE_ID}', $site_id);

	// Запрос для выборки списока модулей, доступных группам пользователей системы администрирования.
	$s1 = $param['data'][] = "SELECT * FROM `admin_forms_table`
	LEFT JOIN `admin_words_table` ON admin_forms_table.admin_words_id = admin_words_table.admin_words_id
	LEFT JOIN `admin_words_value_table` ON admin_words_table.admin_words_id = admin_words_value_table.admin_words_id
	WHERE (admin_words_value_table.admin_language_id = 1 OR admin_forms_table.admin_words_id = 0)
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Посчитаем общее число, запрос ОБЯЗАТЕЛЬНО должен возвращать столбец `count`.
	$count = "SELECT count(*) AS count FROM `admin_forms_table`
	LEFT JOIN `admin_words_table` ON admin_forms_table.admin_words_id = admin_words_table.admin_words_id
	LEFT JOIN `admin_words_value_table` ON admin_words_table.admin_words_id = admin_words_value_table.admin_words_id
	WHERE (admin_words_value_table.admin_language_id = 1 OR admin_forms_table.admin_words_id = 0)
	       		{FILTER_STRING} "; 

	// Добавляем в список замен ID группы пользователей
	$admin_forms->AddExternalReplace('{users_type_id}', to_int($_REQUEST['users_type_id']));

	$user_access = new user_access();

	$users_type_resource = $user_access->select_user_type($users_type_id);

	if ($users_type_resource)
	{
		$users_type_row = mysql_fetch_assoc($users_type_resource);
		$users_type_name = $users_type_row['users_type_name'];
	}
	else
	{
		$users_type_name = '';
	}

	$param['path_array'] = array(
	array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/users_access/users_access.php', '', 7, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/users_access/users_access.php', '', 7, 'load_data'),
	'name' => $GLOBALS['MSG_user_access']['ua_link_users_type']),

	array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax("{$admin_forms->AAction}", "&action=show_users&users_type_id={$users_type_id}", 8, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax("{$admin_forms->AAction}", "&action=show_users&users_type_id={$users_type_id}", 8, 'load_data'),
	'name' => sprintf($GLOBALS['MSG_user_access']['ua_show_users_title'], $users_type_name))
	);

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


	$site = & singleton ('site');

	// Определяем название сайта
	$result_site= $site->select_site($site_id);

	$row_site = mysql_fetch_assoc($result_site);

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

	ob_start();
	?>
	<script type="text/javascript">
	function change_this(site_id)
	{
		DoLoadAjax('/admin/users_access/users_access.php', '&users_type_id=<?php echo to_int($_REQUEST['users_type_id'])?>&site_id=' + site_id + '&access_admin_forms_id=<?php echo $admin_form_id?>', 138, 'show_users_type_access_form', 0, 0, '0', '0');
		return false;
	}

	</script>
	<p>
	<?php echo $GLOBALS['MSG_user_access']['site']?>
	<select id="sites" name="sites" onchange="change_this(this.options[this.selectedIndex].value)">
	<?php 

	// Получаем данные о пользователе
	$UserAccess = new user_access();
	$user_row = $UserAccess->GetUserByName($_SESSION['valid_user']);
	
	// Выбираем доступные сайты
	$site_res = $site->SelectSites(array('users_type_id' => to_int($user_row['users_type_id'])));

	while ($site_row = mysql_fetch_assoc($site_res))
	{
		if ($site_row['site_id'] == $site_id)
		{
			$select_attribs = ' selected="selected" ';
		}
		else
		{
			$select_attribs = '';
		}

		?>
		<option value="<?php echo $site_row['site_id']?>" <?php echo $select_attribs?>><?php echo htmlspecialchars($site_row['site_name'])?></option>
		<?php 
	}
	?>
	</select>
	</p>
	<?php 

	$admin_forms->data_under_menu = ob_get_clean();

	if (isset($_REQUEST['site_id']))
	{
		$site_id = to_int($_REQUEST['site_id']);
	}
	elseif (isset($_SESSION['current_site_id']))
	{

		$site_id = to_int($_SESSION['current_site_id']);
	}
	else
	{
		$site_id = 0;
	}

	$param['title'] = sprintf($GLOBALS['MSG_user_access']['ua_show_user_form_access_title'], $users_type_name);

	/*$param['field_params'][0]['empty_field']['admin_forms_field_link'] =  $admin_forms->GetHtmlCallDoLoadAjax('/admin/users_access/users_access.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id={keyfield}", 79, 'load_data');
	$param['field_params'][0]['empty_field']['admin_forms_field_onclick'] =  $admin_forms->GetOnClickCallDoLoadAjax('/admin/users_access/users_access.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id={keyfield}", 79, 'load_data');*/

	/*$param['field_params'][0]['empty_field']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('show_users_access_avents', '&access_admin_forms_id={admin_forms_id}&users_type_id={users_type_id}&site_id='.$site_id, 139, 0, 0);
	$param['field_params'][0]['empty_field']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('show_users_access_avents', '&access_admin_forms_id={admin_forms_id}&users_type_id={users_type_id}&site_id='.$site_id, 139, 0, 0);*/

	return $param;
}

/**
 * Разрешить доступ к действиям формы
 *
 * @param array $param
 */
function change_events_access_status_on(&$param)
{
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$users_access = & singleton('user_access');
		$admin_forms = & singleton('admin_forms');

		if (isset($_REQUEST['site_id']))
		{
			$site_id = to_int($_REQUEST['site_id']);
		}
		elseif (isset($_SESSION['current_site_id']))
		{

			$site_id = to_int($_SESSION['current_site_id']);
		}
		else
		{
			$site_id = 0;
		}

		$params = array();

		if (isset($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $value)
				{
					// Определяем список действий формы
					$events_info = $admin_forms->GetAllAdminFormEvents($key);

					if (is_array($events_info) && count($events_info) > 0)
					{
						foreach ($events_info as $key_event => $value_event)
						{
							$param_access['access_value'] = 1;
							$param_access['users_type_id'] = to_int($_REQUEST['users_type_id']);
							$param_access['admin_form_event_id']  = $value_event['admin_forms_events_id'];
							$param_access['site_id'] = $site_id;
							$users_access->SetUsersTypeEventAccess($param_access);
						}
					}
				}
			}
		}

	}
}

/**
 * Запретить доступ к действиям формы
 *
 * @param array $param
 */
function change_events_access_status_off(&$param)
{
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$users_access = & singleton('user_access');

		$admin_forms = & singleton('admin_forms');

		// Идентификатор группы пользователей сайта
		$users_type_id = to_int($_REQUEST['users_type_id']);

		$params = array();

		if (isset($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_row = $admin_forms->GetAdminForm($key);

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$user_access->SetUsersTypeAccessFormEvents($key, $users_type_id, 0, CURRENT_SITE);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
}

?>