<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка групп пользователей сайта, связанных с социальной сетью.
 * 
 * Файл: /admin/InformationSystems/action/load_information_group_site_users_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);
	
	$information_item_id = to_int($_REQUEST['information_item_id']);
	
	$information_groups_parent_id = to_int($_REQUEST['information_groups_parent_id']);
	
	if (!$information_item_id)
	{
		$information_groups_id = to_int($_REQUEST['information_group_id']);
	}
	else
	{
		$information_groups_id = $information_groups_parent_id;
	}
	
	$InformationSystem = & singleton('InformationSystem');
			
	$information_group_info = $InformationSystem->GetInformationGroup($information_groups_id);
			
	$Sns = & singleton('Sns');
	
	$information_system_id = to_int($_REQUEST['information_system_id']);
	
	$admin_forms->information_system_id = $information_system_id;
	$admin_forms->information_groups_id = $information_groups_id;
	$admin_forms->information_groups_parent_id = $information_groups_parent_id;
			
	$sns_info = $Sns->GetSnsAssociatedInformationSystem($information_system_id);
	
	$sns_id = to_int($sns_info['sns_id']);
	
		
	// Строим "хлебные крошки"
	$path_array = $InformationSystem->GetInformationGroupsPathArray($information_groups_id, $information_system_id);

	$new_path_array = array();

	$new_path_array[] = 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']);

	// Меняем порядок следования элементов в массиве на обратный
	$path_array = array_reverse($path_array, true);

	// Список групп пользователей для информационной группы
	if (!$information_item_id)
	{
		// Получаем информацию о последнем элементе массива, содержащего путь 	
		$path_array_end = end($path_array);
		
		// Удаляем последний элемент из пути
		unset($path_array[$path_array_end['information_groups_id']]);
	}
	

	// Преобразуем идентификаторы групп в ссылки на группы.
	if ($path_array)
	{
		foreach ($path_array as $information_groups_parent_id => $value)
		{
			$new_path_array[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
			'name' => $value['information_groups_name']);
		}
	}
		
	// Список групп пользователей для информационной группы
	if (!$information_item_id)
	{
		$title = sprintf($GLOBALS['MSG_information_systems']['site_users_groups_information_group_title'], to_str($information_group_info['information_groups_name']));
	}
	else
	{		
		$item_row = $InformationSystem->GetInformationSystemItem($information_item_id);
		
		$item_name = to_str($item_row['information_items_name']);
		
		$title = sprintf($GLOBALS['MSG_information_systems']['site_users_groups_information_item_title'], $item_name);
	}
	
	$new_path_array[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_groups_id}&information_item_id={$information_item_id}&information_system_id={$information_system_id}", 174, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_groups_id}&information_item_id={$information_item_id}&information_system_id={$information_system_id}", 174, 'load_data'),
			'name' => $title);
	
	$param['path_array'] = $new_path_array;
		
	$kernel = & singleton('kernel');
	
	$users_id = $kernel->GetCurrentUser();
		
	// Выборка нужных записей.	
	$param['data'][] = "SELECT site_users_group_table.site_users_group_id AS site_users_group_id, site_users_group_table.site_users_group_name" .
					   " FROM sns_site_users_group_table, site_users_group_table " .					  
					   " WHERE sns_site_users_group_table.sns_id = $sns_id" .
					   " AND sns_site_users_group_table.site_users_group_id = site_users_group_table.site_users_group_id" .
		   			   " HAVING (1) {FILTER_STRING}
		   			   UNION SELECT 0, 	'Все пользователи'
		   			    {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(sns_site_users_group_id) AS count " .
			 " FROM sns_site_users_group_table, site_users_group_table " .			 
			 " WHERE sns_site_users_group_table.sns_id =$sns_id" .
			 " AND sns_site_users_group_table.site_users_group_id = site_users_group_table.site_users_group_id" .
		   	 " HAVING (1) {FILTER_STRING}";	   	 
	
	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	
	// Заголовок формы
	$param['title'] = $title;
	
	//$param['field_params'][0][828]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_id}&site_users_group_id={site_users_group_id}", 175, 'load_data');
	
	$param['field_params'][0][828]['callback_function'] = 'callback_function_users';
	// Функция обратного вызова для пользователей сайта
	function callback_function_users($field_value, $value, $row)
	{
		$information_item_id = to_int($_REQUEST['information_item_id']);
		
		$admin_forms = & singleton('admin_forms');			
		$information_groups_id = $admin_forms->information_groups_id;
		$information_groups_parent_id = $admin_forms->information_groups_parent_id;
		
		if (!$information_item_id && $row['site_users_group_id'] != 0 && $information_groups_parent_id == 0)
		{
			$information_system_id = $admin_forms->information_system_id;
					
			?>
			<a href="/admin/InformationSystems/InformationSystems.php?admin_forms_id=175&operation=load_data&limit=0&information_system_id=<?php echo $information_system_id?>&information_groups_parent_id=<?php echo $information_groups_parent_id?>&information_group_id=<?php echo $information_groups_id?>&site_users_group_id=<?php echo $row['site_users_group_id']?>"><img src="/admin/images/users_group.gif"></a>
			<?php 							
		}
		else
		{
			echo '&mdash';
		}
	}
	
	$param['field_params'][0][840]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_groups_id}&information_item_id={$information_item_id}&site_users_group_id={site_users_group_id}", 176, 'load_data');
	
	// Доп. параметры
	$admin_forms->AAdditionalParams = "&information_system_id={$information_system_id}&information_groups_parent_id={$information_groups_parent_id}&information_group_id={$information_groups_id}&information_item_id={$information_item_id}";
				
	return $param;
}
/*
function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0:
			{
				switch ($field_name)
				{
					case 'site_users_group_id':
						{
							// ` нужны именно в таком виде!
							$field_name = '`site_users_group_table.site_users_group_id`';
							break;
						}					
					default:
						{
							$field_name = '';
							break;
						}
				}
				break;
			}
	}
}
*/

// Закоментировано до факта выяснения причин, добавления "этого" - "сюда"
if (1 == 2)
{
	// Обработчик события "Редактировать" информационной системы.
	function edit_information_system(&$param)
	{
		ob_start();

		$InformationSystem = & singleton('InformationSystem');

		if (isset($param['data']))
		{
			foreach ($param['data'] as $dataset)
			{
				foreach ($dataset 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'][0]))
			{
				foreach ($param['data'][0] 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;

				foreach ($param['data'] as $dataset)
				{
					foreach ($dataset 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;
	}
}
?>