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

	// Запрос для выборки списока модулей, доступных группам пользователей системы администрирования.
	$s1 = $param['data'][] = "SELECT admin_forms_events_table.admin_forms_events_id,
		admin_words_value_table.admin_words_value_name,
		admin_forms_events_table.admin_forms_events_function,
		IF (users_type_events_access_table.admin_forms_events_id IS NULL, 0, 1) AS events_id
         FROM  admin_forms_events_table LEFT JOIN users_type_events_access_table
         ON (admin_forms_events_table.admin_forms_events_id = users_type_events_access_table.admin_forms_events_id
         AND users_type_events_access_table.site_id = ".$site_id." 
         AND users_type_events_access_table.users_type_id = '$users_type_id'),
         admin_words_value_table
         WHERE admin_forms_events_table.admin_forms_id = $admin_form_id AND
         admin_forms_events_table.admin_words_id = admin_words_value_table.admin_words_id 
         AND admin_words_value_table.admin_language_id = ".CURRENT_LANGUAGE_ID." 						
       {FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Посчитаем общее число, запрос ОБЯЗАТЕЛЬНО должен возвращать столбец `count`.
	$count = "SELECT count(admin_forms_events_table.admin_forms_events_id) AS count
         FROM  admin_forms_events_table LEFT JOIN users_type_events_access_table
         ON (admin_forms_events_table.admin_forms_events_id = users_type_events_access_table.admin_forms_events_id
         AND users_type_events_access_table.site_id = ".$site_id." 
         AND users_type_events_access_table.users_type_id = '$users_type_id'),
         admin_words_value_table
         WHERE admin_forms_events_table.admin_forms_id = $admin_form_id 
         AND admin_forms_events_table.admin_words_id = admin_words_value_table.admin_words_id 
         AND admin_words_value_table.admin_language_id = " . CURRENT_LANGUAGE_ID . " 	
         			{FILTER_STRING}"; 

	$admin_forms_fields = new admin_forms_fields();

	$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_fields->AAction}", "&action=show_users&users_type_id={$users_type_id}", 8, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax("{$admin_forms_fields->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)),

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

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

	$form_info = $admin_forms->GetAdminForm($admin_form_id);

	$form_info = $admin_forms->GetAdminFormsWord($form_info['admin_words_id']);

	$site = & singleton ('site');

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

	$row_site = mysql_fetch_assoc($result_site);

	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?>', 139, '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();

	$site_id = to_int($_REQUEST['sites']);

	$param['title'] = sprintf($GLOBALS['MSG_user_access']['ua_show_user_form_events_access_title'], $form_info['name'] ,htmlspecialchars($users_type_name));

	return $param;
}


// Необязательная функция для определения реального имени столбца по псевдониму.
function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0: // Права доступа групп пользователей к модулям
		{
			if ($field_name == 'events_id')
			{
				$field_name = 'users_type_events_access_table.admin_forms_events_id';
			}


			break;
		}
	}
	return true;
}

/**
 * Применить изменения
 */
function apply_users_type_access(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$users_access = new user_access();

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

		$admin_forms = & singleton('admin_forms');

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

				// Определяем информацию об объекте
				$object_row = $admin_forms->GetAdminFormsEvent($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['access_value'] = $row['events_id'];
					$param_access['users_type_id'] = to_int($_REQUEST['users_type_id']);
					$param_access['admin_form_event_id']  = $key;
					$param_access['site_id'] = $site_id;
					$users_access->SetUsersTypeEventAccess($param_access);
				}
				else
				{
					$user_access->MessageOnlyOwn();
				}

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


/**
 * Запретить доступ
 */
function access_denied(&$param)
{
	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;
	}

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

		$kernel->ReadMode();
	}
	else
	{

		$users_access = new user_access();

		$params = array();

		// Идентификатор сайта
		$params['site_id'] = $site_id;

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

		// Идентификатор сайта
		$site_id = $site_id;

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

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$params['modules_id'] = to_int($key);

						$params['users_access_value'] = 0;

						$users_access->SetUsersTypeAccess($params);
					}
					else
					{
						$user_access->MessageOnlyOwn();
					}

				}
			}
		}

	}
}
?>