<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка разделов информационных систем.
 * 
 * Файл: /admin/InformationSystems/action/load_information_systems.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']['all'] = array('begin' => $begin, 'count' => $on_page);
	
	$information_systems_dir_parent_id = to_int($_REQUEST['information_systems_dir_parent_id']);
	
	$InformationSystem = & singleton('InformationSystem');
		
	if ($information_systems_dir_parent_id)
	{
		// Строим "хлебные крошки"
		$path_array = $InformationSystem->GetInformationSystemsDirPathArray($information_systems_dir_parent_id);
	
		$new_path_array = array();
		
		$new_path_array[] = array(
		'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', '&information_systems_dir_parent_id=0', 11, 'load_data'),
		'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', '&information_systems_dir_parent_id=0', 11, 'load_data'),
		'name' => $GLOBALS['MSG_information_systems']['show_information_systems_title']);
		
		// Меняем порядок следования элементов в массиве на обратный
		$path_array = array_reverse($path_array, true);

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

		$param['path_array'] = $new_path_array;
	}
		
	// Запрос для выборки разделов инфосистем
	$param['data'][] = "SELECT information_systems_dir_id AS key_field, information_systems_dir_name AS name
	FROM information_systems_dir_table
	WHERE `site_id` = " . intval(CURRENT_SITE) . " AND `information_systems_dir_parent_id` = $information_systems_dir_parent_id 	 
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Количество разделов информационных групп
	$count_dirs = "SELECT count(information_systems_dir_id) as count
	FROM information_systems_dir_table
	WHERE `site_id` = " . intval(CURRENT_SITE) . " AND `information_systems_dir_parent_id` = $information_systems_dir_parent_id
	{FILTER_STRING}";
	
	// Выборка информационных систем
	$param['data'][] = "SELECT information_systems_id AS key_field, information_systems_name AS name, information_systems_dir_id FROM information_systems_table
	WHERE `information_systems_dir_id` ={$information_systems_dir_parent_id} 
	AND `site_id`=" . intval(CURRENT_SITE) . "
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(information_systems_id) as count FROM information_systems_table
	WHERE `information_systems_dir_id` ={$information_systems_dir_parent_id} 
	AND `site_id`=" . intval(CURRENT_SITE) . " {FILTER_STRING}";

	// Формируем верхнее меню.		
	$menu = array();
	$menu[$k = 0]['name'] = $GLOBALS['MSG_information_systems']['show_comments_link4'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();
	$sub_menu[$p = 0]['name'] = $GLOBALS['MSG_information_systems']['show_information_systems_menu_add_is_dir'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_information_system', 'check_0_0', 11, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_information_system', 'check_0_0', 11, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/folder_page_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;
		
	$menu[++$k]['name'] = $GLOBALS['MSG_information_systems']['show_comments_link3'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();
	$sub_menu[$p = 0]['name'] = $GLOBALS['MSG_information_systems']['show_information_systems_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_information_system', 'check_1_0', 11, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_information_system', 'check_1_0', 11, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/folder_page_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;
		

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

	$param['total_count'][0] = $count_dirs;
	$param['total_count'][1] = $count;
	
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;

	// Заголовок формы
	$param['title'] = $GLOBALS['MSG_information_systems']['information_systems_add_form_link'];
	
	$param['field_params'][0][864]['admin_forms_field_image'] = "=/admin/images/folder.gif";
	
	$param['field_params'][0][43]['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&information_systems_dir_parent_id={key_field}", 11, 'load_data');
	$param['field_params'][0][43]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&information_systems_dir_parent_id={key_field}", 11, 'load_data');
	
	$param['field_params'][1][43]['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&information_systems_dir_parent_id={information_systems_dir_id}&information_system_id={key_field}", 12, 'load_data');
	$param['field_params'][1][43]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&information_systems_dir_parent_id={information_systems_dir_id}&information_system_id={key_field}", 12, 'load_data');

	return $param;
}

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

	switch ($dataset_id)
	{
		case 0: // Список разделов информационных систем
			{
				if ($field_name == 'name')
				{
					$field_name = 'information_systems_dir_name';
				}
				elseif ($field_name == 'key_field')
				{
					$field_name = 'information_systems_dir_id';
				}				

				break;
			}
		case 1: // Список информационных систем
			{
				if ($field_name == 'name')
				{
					$field_name = 'information_systems_name';
				}
				elseif ($field_name == 'key_field')
				{
					$field_name = 'information_systems_id';
				}
				
				break;
			}
	}
	return true;
}

// Обработчик события "Редактировать" раздела информационных систем
function edit_information_system(&$param)
{
	ob_start();

	$InformationSystem = & 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 = $InformationSystem->GetInformationSystemsDir($key);

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

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

					$action_name = 'edit_information_system';

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

					$param['title'] = $information_systems_dir_id == 0 ? $GLOBALS['MSG_information_systems']['information_systems_dir_add_form_title'] : $GLOBALS['MSG_information_systems']['information_systems_dir_edit_form_title'];

					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_res = $InformationSystem->SelectInformationSystem($key);

				if ($object_res)
				{
					$object_row = mysql_fetch_assoc($object_res);
				}

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

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

					$action_name = 'edit_information_system';

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

					$param['title'] = $information_system_id == 0 ? $GLOBALS['MSG_information_systems']['information_systems_add_form_title'] : $GLOBALS['MSG_information_systems']['information_systems_edit_form_title'];

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

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


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

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

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

		$count_copy_information_systems = 0;

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

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					if ($InformationSystem->CopyInformationSystem($key))
					{						
						$flag_copy_information_system_success = true;
						$count_copy_information_systems++;
					}
					else
					{
						$flag_copy_information_system_success = false;
					}

				}
				else
				{
					$user_access->MessageOnlyOwn();
					$flag_copy_information_system_success = false;
				}
			}

			// Документ(ы) успешно скопирован(ы)
			if ($flag_copy_information_system_success)
			{
				if ($count_copy_information_systems == 1)
				{
					show_message($GLOBALS['MSG_information_systems']['information_system_copy_success_message']);
				}
				elseif ($count_copy_information_systems > 1)
				{
					show_message($GLOBALS['MSG_information_systems']['information_systems_success_message']);
				}
			}
			else
			{
				show_error_message($GLOBALS['MSG_information_systems']['information_system_copy_error_message']);
			}

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

}

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

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

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

					// Определяем информацию об объекте
					$object_row = $InformationSystem->GetInformationSystemsDir($key);
					
					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$InformationSystem->DeleteInformationSystemsDir($key))
						{
							$flag_success_dir = false;
						}
						else
						{
							++$count_deleted_information_systems_dir;

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

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

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

					if ($object_res)
					{
						$object_row = mysql_fetch_assoc($object_res);
					}

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$InformationSystem->DelInformationSystem($key))
						{
							$flag_success = false;
						}
						else
						{
							++$count_deleted_information_system;

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

						$flag_success = false;
					}
				}
				
				if ($flag_success)
				{
					if ($count_deleted_information_system == 1)
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_system']);
					}
					elseif ($count_deleted_information_system > 1)
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_systems']);
					}
				}	
			}							
			
			/*else
			{
			show_error_message($GLOBALS['MSG_information_systems']['delete_information_system_error']);
			}*/
		}
	}
	
	$error = ob_get_clean();

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