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

	$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", 50, '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", 50, 'load_data'),
	'name' => (sprintf($GLOBALS['MSG_information_systems']['bread_crumbs_property_list'], $row_information_system['information_systems_name'])));

	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;
	}
	
	// Дополнительные хлебные крошки для хождения по группам дополнительных свойств инфоэлементов
	$path_array = $InformationSystem->GetAdditionalPropertyPathArray($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}", 50, '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}", 50, 'load_data'),
			'name' => $value);
		}
	}

	$param['path_array'] = $parray;

	// Запрос для выборки групп дополнительных свойств
	$param['data'][] = "SELECT information_propertys_items_dir_id AS code, information_propertys_items_dir_name AS name, information_propertys_items_dir_order AS order_field FROM `information_propertys_items_dir_table`
	WHERE `information_systems_id` = '$information_system_id'
	AND `information_propertys_items_dir_parent_id`='$ext_is_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

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


	// Запрос для выборки дополнительных свойств информационных элементов.
	$param['data'][] = "SELECT information_propertys_id AS code, information_propertys_name AS name, information_propertys_order AS order_field, information_propertys_xml_name FROM `information_propertys_table`
	WHERE `information_systems_id` = '$information_system_id'
	AND `information_propertys_items_dir_id`='$ext_is_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Посчитаем общее число дополнительных свойств информационных элементов.
	$count = "SELECT count(information_propertys_id) AS count FROM `information_propertys_table`
	WHERE `information_systems_id` = '$information_system_id'
	AND `information_propertys_items_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_info_prop', 'check_1_0', 50, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_info_prop', 'check_1_0', 50, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/page_gear_add.gif';

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


	$menu[++$k]['name'] = $GLOBALS['MSG_information_systems']['menu2_caption'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_information_systems']['submenu2_caption'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_info_prop', 'check_0_0', 50, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_info_prop', 'check_0_0', 50, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/page_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}", 50, '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}", 50, 'load_data');

	$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_title'], $row_information_system['information_systems_name']);

	return $param;
}


/**
 * Необязательная функция для определения реального имени столбца по псевдониму.
 *
 * @param string $field_name
 * @param integer $dataset_id
 * @return boolean
 */
function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 1:
			{
				switch ($field_name)
				{
					case 'order_field':
						{
							$field_name = 'information_propertys_order';
							break;
						}
					case 'information_propertys_xml_name':
						{
							$field_name = 'information_propertys_xml_name';
							break;
						}
					case 'name':
						{
							$field_name = 'information_propertys_name';
							break;
						}
					case 'code':
						{
							$field_name = 'information_propertys_id';
							break;
						}
					default:
						{
							$field_name = '';
							break;
						}
				}
				break;
			}
		case 0:
			{
				switch ($field_name)
				{
					case 'order_field':
						{
							$field_name = 'information_propertys_items_dir_order';
							break;
						}
					case 'information_propertys_xml_name':
						{
							$field_name = '';
							break;
						}
					case 'name':
						{
							$field_name = 'information_propertys_items_dir_name';
							break;
						}
					case 'code':
						{
							$field_name = 'information_propertys_items_dir_id';
							break;
						}
					default:
						{
							$field_name = '';
							break;
						}
				}
				break;
			}
	}
	return true;
}

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

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

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

		$InformationSystem = & singleton('InformationSystem');

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

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						// Выбираем данные
						$result = $InformationSystem->GetInformationSystemItemProperty($key);

						if ($result)
						{
							$param['information_propertys_id'] = $key;
							$param['information_system_id'] = $information_system_id;
							$param['information_propertys_name'] = $result['information_propertys_name'];
							$param['information_propertys_type'] = $result['information_propertys_type'];
							$param['information_propertys_order'] =$row['order_field'];
							$param['information_propertys_define_value'] = $result['information_propertys_define_value'];
							$param['information_propertys_xml_name'] = $result['information_propertys_xml_name'];
							$param['information_propertys_lists_id'] = $result['information_propertys_lists_id'];
							$param['information_propertys_items_dir_id'] = $result['information_propertys_items_dir_id'];
							$param['information_propertys_information_systems_id'] = $result['information_propertys_information_systems_id'];
							$param['users_id'] = false;
							
							$param['information_propertys_default_big_width'] = $result['information_propertys_default_big_width'];
							$param['information_propertys_default_small_width'] = $result['information_propertys_default_small_width'];
							$param['information_propertys_default_big_height'] = $result['information_propertys_default_big_height'];
							$param['information_propertys_default_small_height'] = $result['information_propertys_default_small_height'];

							// Обновляем данные о порядке сортировки
							$InformationSystem->InsertInformationPropertys($param);
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $row)
				{

					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{


						$InformationSystem->InsertPropertysItemsDir(array('information_propertys_items_dir_id' => $key, 'information_propertys_items_dir_order' => $row['order_field']));

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

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

// Обработчик события "Редактировать" дополнительного свойства информационных элементов.
function edit_info_prop(&$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'][0]))
		{
			foreach ($param['data'][0] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				// Определяем информацию об объекте
				$object_row = $information_system->GetPropertysItemsDir($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_items_dir_id = intval($key);

					include(CMS_FOLDER . 'admin/InformationSystems/action/form_edit_add_information_propertys_dir.php');

					// Устанавливаем <title> для страницы
					$param['title'] = ($information_propertys_items_dir_id == 0) ? $GLOBALS['MSG_information_systems']['add_property_dir']:$GLOBALS['MSG_information_systems']['edit_property_dir'];

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

				// Определяем информацию об объекте
				$object_row = $information_system->GetInformationSystemItemProperty($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_items_id = intval($key);

					include(CMS_FOLDER . 'admin/InformationSystems/action/form_edit_add_information_propertys_items.php');

					// Устанавливаем <title> для страницы
					$param['title'] = ($information_property_items_id == 0) ? $GLOBALS['MSG_information_systems']['add_property']:$GLOBALS['MSG_information_systems']['edit_property'];

					break;
				}
				else
				{
					$flag_success_delete = false;
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}

	$param['result'] = ob_get_clean();
	return true;
}

// Обработчик события "Копировать" дополнительного свойства информационных элементов
function copy_items_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->GetInformationSystemItemProperty($key);

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

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

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

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

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

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

		$count_deleted_propertys_items = 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->GetInformationSystemItemProperty($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->del_information_propertys($key))
						{
							$flag_success_delete = false;
						}
						else
						{
							++$count_deleted_propertys_items;

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

						$flag_success_delete = false;
					}
				}

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

					// Определяем информацию об объекте
					$object_row = $information_system->GetPropertysItemsDir($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->DeletePropertysItemsDir($key))
						{
							$flag_success_delete = false;
						}
						else
						{
							++$count_deleted_propertys_items;

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

						$flag_success_delete = false;
					}
				}

				if ($flag_success_delete)
				{
					if ($count_deleted_propertys_items == 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();

}

?>