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

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

	$InformationSystem = & singleton('InformationSystem');

	$row_information_system = $InformationSystem->GetInformationSystem($information_system_id);

	if (isset($_REQUEST['ext_is_groups_parent_id']))
	{
		$ext_is_groups_parent_id = intval($_REQUEST['ext_is_groups_parent_id']);
	}
	else
	{
		$ext_is_groups_parent_id = 0;
	}

	$parray = array();

	// Строим "хлебные крошки"
	$parray[] = 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']);
	
	// Идентификатор текущей группы (раздела) информационных систем
	$information_systems_dir_parent_id = to_int($_REQUEST['information_systems_dir_parent_id']);
	
	// Путь по группам инфосистем
	if ($information_systems_dir_parent_id)
	{
		$information_systems_dir_path_array = $InformationSystem->GetInformationSystemsDirPathArray($information_systems_dir_parent_id);
		
		// Меняем порядок следования элементов в массиве на обратный
		$information_systems_dir_path_array = array_reverse($information_systems_dir_path_array, true);
		
		foreach ($information_systems_dir_path_array as $key => $value)
		{
			$parray[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$key}", 11, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$key}", 11, 'load_data'),
			'name' => $value['information_systems_dir_name']);
		}
	}	

	$parray[] = array('link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
	'name' => htmlspecialchars($row_information_system['information_systems_name']));

	$parray[] = array('link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}&ext_is_groups_parent_id=0", 51, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}&ext_is_groups_parent_id=0", 51, 'load_data'),
	'name' => sprintf($GLOBALS['MSG_information_systems']['bread_crumbs_property_groups_list'], $row_information_system['information_systems_name']));

	// Дополнительные хлебные крошки для хождения по группам дополнительных свойств инфоэлементов
	$path_array = $InformationSystem->GetAdditionalPropertyPathArrayGroup($ext_is_groups_parent_id);

	if (count($path_array) > 0)
	{
		foreach ($path_array as $key => $value)
		{
			$parray[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}&ext_is_groups_parent_id={$key}", 51, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}&ext_is_groups_parent_id={$key}", 51, 'load_data'),
			'name' => $value);
		}
	}


	$param['path_array'] = $parray;


	// Запрос для выборки групп дополнительных свойств информационных групп.
	$param['data'][] = "SELECT information_propertys_groups_dir_id AS code,
 	information_propertys_groups_dir_name AS name, information_propertys_groups_dir_order AS order_field 
 	FROM `information_propertys_groups_dir_table`
	WHERE `information_systems_id` = '$information_system_id'
	AND `information_propertys_groups_dir_parent_id`='$ext_is_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Количество групп
	$count_groups = "SELECT count(*) AS count
	FROM `information_propertys_groups_dir_table`
	WHERE `information_systems_id` = '$information_system_id'
	AND `information_propertys_groups_dir_parent_id`='$ext_is_groups_parent_id'
	{FILTER_STRING}";	

	// Запрос для выборки дополнительных свойств информационных групп.
	$param['data'][] = "SELECT information_propertys_groups_id AS code,
	information_propertys_groups_name AS name, 
	information_propertys_groups_order AS order_field, 
	information_propertys_groups_xml_name as xml_name
	FROM `information_propertys_groups_table`
	WHERE `information_systems_id` = '$information_system_id'
	AND `information_propertys_groups_dir_id`='$ext_is_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Посчитаем общее число дополнительных свойств информационных групп.
	$count = "SELECT count(*) AS count
	FROM `information_propertys_groups_table`
	WHERE `information_systems_id` = '$information_system_id'
	AND `information_propertys_groups_dir_id`='$ext_is_groups_parent_id'
	{FILTER_STRING}";
	
	// Формируем верхнее меню.
	$k = 0;

	$menu = array();
	$menu[$k]['name'] = $GLOBALS['MSG_information_systems']['information_prop'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$p = 0;

	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_information_systems']['show_information_propertys_link1'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_ext_prop_group', 'check_1_0', 51, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_ext_prop_group', 'check_1_0', 51, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/folder_gear_add.gif';

	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	// Формируем верхнее меню.
	$k++;

	//	$menu = array();
	$menu[$k]['name'] = $GLOBALS['MSG_information_systems']['menu2_caption'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$p++;

	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_information_systems']['submenu2_caption'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_ext_prop_group', 'check_0_0', 51, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_ext_prop_group', 'check_0_0', 51, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/folder_gear_add.gif';

	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	// Формируем массив меню.
	$menu_array = array();
	$menu_array[] = $menu;

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

	$param['field_params'][0]['name']['admin_forms_field_type'] = 4;
	$param['field_params'][0]['name']['admin_forms_field_link'] =  $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id=$information_system_id&ext_is_groups_parent_id={code}", 51, 'load_data');
	$param['field_params'][0]['name']['admin_forms_field_onclick'] =  $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id=$information_system_id&ext_is_groups_parent_id={code}", 51, 'load_data');
	
	//$param['field_params'][0]['information_propertys_groups_xml_name']['admin_forms_field_type'] = 0;

	$param['field_params'][0]['type']['admin_forms_field_image'] = "=/admin/images/folder.gif";
	$param['field_params'][1]['type']['admin_forms_field_image'] = "=/admin/images/page.gif";

	$param['title'] = sprintf($GLOBALS['MSG_information_systems']['show_information_propertys_groups_title'], $row_information_system['information_systems_name']);

	return $param;
}

// Необязательная функция для определения реального имени столбца по псевдониму.
function ResolveFieldName(&$field_name, $dataset_id)
{

	switch ($dataset_id)
	{
		case 0: // Список групп доп. свойств информационных групп
		{				
			if ($field_name == 'name')
			{
				$field_name = 'information_propertys_groups_dir_name';
			}
			
			
			if ($field_name == 'xml_name')
			{
				$field_name = '';
			}
			

			break;
			
		}
		
		case 1: // Список доп. свойств информационных групп
		{
			if ($field_name == 'name')
			{
				$field_name = 'information_propertys_groups_name';
			}				
			
			if ($field_name == 'order_field')
			{
				$field_name = 'information_propertys_groups_order';
			}
									
			if ($field_name == 'xml_name')
			{
				$field_name = 'information_propertys_groups_xml_name';
			}

			break;
		}
	}
	return true;
}


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

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

		$kernel->ReadMode();
	}
	else
	{
		$information_system_id = to_int($_REQUEST['information_system_id']);

		$information_system = & singleton('InformationSystem');

		if (isset($param['data']) && is_array($param['data']))
		{
			if (isset($param['data'][0]))
			{

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

					$InformationSystem = & singleton('InformationSystem');

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$param_property = array();
						$param_property['information_propertys_groups_dir_id']  = $key;
						$param_property['information_propertys_groups_dir_order'] = $row['order_field'];

						$information_system->InsertPropertyGroupsDir($param_property);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}

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

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$result = $information_system->GetInformationGroupsPropertys($key);

						$param['information_propertys_groups_id'] = $key;
						$param['information_system_id'] = $information_system_id;
						$param['information_propertys_groups_name'] = $result['information_propertys_groups_name'];
						$param['information_propertys_groups_type'] = $result['information_propertys_groups_type'];
						$param['information_propertys_groups_order'] = $row['order_field'];
						$param['information_propertys_groups_default_value'] = $result['information_propertys_groups_default_value'];
						$param['information_propertys_groups_xml_name'] = $result['information_propertys_groups_xml_name'];
						$param['information_propertys_groups_lists_id'] =  $result['information_propertys_groups_lists_id'];
						$param['information_propertys_groups_information_system_id'] = $result['information_propertys_groups_information_systems_id'];
						$param['information_propertys_groups_dir_id'] = $result['information_propertys_groups_dir_id'];
						$param['information_propertys_groups_big_width'] = $result['information_propertys_groups_big_width'];
						$param['information_propertys_groups_big_height'] = $result['information_propertys_groups_big_height'];
						$param['information_propertys_groups_small_width'] = $result['information_propertys_groups_small_width'];
						$param['information_propertys_groups_small_height'] = $result['information_propertys_groups_small_height'];
						$param['users_id'] = false;

						$information_system->InsertInformationPropertysGroups($param);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

	$param['error'] = $error;
}

// Обработчик события "Редактировать" дополнительного свойства информационных групп
function edit_ext_prop_group(&$param)
{
	$information_system_id = to_int($_REQUEST['information_system_id']);

	$information_group_id = to_int($_REQUEST["information_group_id"]);

	ob_start();

	$information_system = & singleton('InformationSystem');

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

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$information_property_groups_id =  intval($key);

					include(CMS_FOLDER . 'admin/InformationSystems/action/form_edit_add_information_propertys_groups.php');
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
		if (isset($param['data'][0]))
		{
			foreach ($param['data'][0] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$information_propertys_groups_dir_id =  intval($key);

					include(CMS_FOLDER . 'admin/InformationSystems/action/form_edit_add_information_propertys_dir_group.php');
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}

	$param['result'] = ob_get_clean();

	return true;
}

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

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

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

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

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$InformationSystem->CopyGroupsProperty($key);
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}			
		}
	}
	
	$param['error'] = ob_get_clean();
}

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

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

		$kernel->ReadMode();
	}
	else
	{
		$information_system = & singleton('InformationSystem');

		$count_deleted_propertys_groups = 0;

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

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$information_system->DelInformationGroupPropertys($key))
						{
							$flag_success_delete = false;
						}
						else
						{
							++$count_deleted_propertys_groups;

							$flag_success_delete = true;
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success_delete = false;
					}
				}
				if ($flag_success_delete)
				{
					if ($count_deleted_propertys_groups == 1)
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_property_groups_success']);
					}
					else
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_propertys_groups_success']);
					}
				}
				else
				{
					show_error_message($GLOBALS['MSG_information_systems']['delete_information_propertys_groups_error']);
				}
			}
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					$InformationSystem = & singleton('InformationSystem');

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$information_system->DeletePropertyGroupsDir($key))
						{
							$flag_success_delete = false;
						}
						else
						{
							++$count_deleted_propertys_groups;

							$flag_success_delete = true;
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success_delete = false;
					}
				}
				if ($flag_success_delete)
				{
					if ($count_deleted_propertys_groups == 1)
					{
						show_message($GLOBALS['MSG_information_systems']['success_delete_info_group']);
					}
					else
					{
						show_message($GLOBALS['MSG_information_systems']['success_delete_info_groups']);
					}
				}
				else
				{
					show_error_message($GLOBALS['MSG_information_systems']['error_delete_info_group']);
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}

?>