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

	// Идентификатор формы, поля которой необходимо отобразить.
	$admin_forms_id = to_int($_REQUEST['admin_forms_edit_id']);

	// Выборка нужных записей.
	$param['data'][] = "SELECT * FROM `admin_forms_field_table`
	LEFT JOIN `admin_words_table` ON admin_forms_field_table.admin_words_id = admin_words_table.admin_words_id
	LEFT JOIN `admin_words_value_table` ON admin_words_table.admin_words_id = admin_words_value_table.admin_words_id
	WHERE admin_forms_field_table.admin_forms_id = $admin_forms_id AND (admin_words_value_table.admin_language_id = ".CURRENT_LANGUAGE_ID." OR admin_forms_field_table.admin_words_id = 0)
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(admin_forms_field_id) as count FROM `admin_forms_field_table`
	LEFT JOIN `admin_words_table` ON admin_forms_field_table.admin_words_id = admin_words_table.admin_words_id
	LEFT JOIN `admin_words_value_table` ON admin_words_table.admin_words_id = admin_words_value_table.admin_words_id
	WHERE admin_forms_field_table.admin_forms_id = $admin_forms_id AND (admin_words_value_table.admin_language_id = ".CURRENT_LANGUAGE_ID." OR admin_forms_field_table.admin_words_id = 0)
	{FILTER_STRING}";

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

	$p = 0;

	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_admin_forms']['show_form_fields_menu_add_new'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_field', 'check_0_0', 2, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_field', 'check_0_0', 2, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/textfield_add.gif';

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

	$form_row = $admin_forms->GetAdminForm($admin_forms_id);

	if ($form_row)
	{
		$form_word_row = $admin_forms->GetAdminFormsWord(to_int($form_row['admin_words_id']));
	}

	$new_path_array[] = array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/admin_forms/admin_forms.php', '', 1, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/admin_forms/admin_forms.php', '', 1, 'load_data'),
	'name' => $GLOBALS['MSG_admin_forms']['show_form_fields_menu_admin_forms']);

	$new_path_array[] = array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/admin_forms/admin_forms.php', "&admin_forms_edit_id=$admin_forms_id", 2, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/admin_forms/admin_forms.php', "&admin_forms_edit_id=$admin_forms_id", 2, 'load_data'),
	'name' => htmlspecialchars(to_str($form_word_row['name'])));

	$param['path_array'] = $new_path_array;

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

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

	$param['title'] = sprintf($GLOBALS['MSG_admin_forms']['show_form_fields_title'], to_str($form_word_row['name']));

	return $param;
}


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

	$admin_forms_id = to_int($_REQUEST['admin_forms_edit_id']);

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

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

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

				include(CMS_FOLDER . '/admin/admin_forms/action/form_edit_add_admin_forms_field.php');

				$admin_forms = & singleton('admin_forms');

				$form_row = $admin_forms->GetAdminForm($admin_forms_id);

				if ($form_row)
				{
					$form_word_row = $admin_forms->GetAdminFormsWord(to_int($form_row['admin_words_id']));
				}

				$param['title'] = $admin_forms_field_id == 0
				? $GLOBALS['MSG_admin_forms']['form_add_forms_field_title']
				: sprintf($GLOBALS['MSG_admin_forms']['form_edit_forms_field_title'], to_str($form_word_row['name']));

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

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

/**
 * Обработчик события "Применить" поля формы Центра администрирования
 */
function apply_changes_field(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$adm_forms = new admin_forms();

		$count_changes_fields = 0;

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

				$adm_forms = new admin_forms();

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$field_param = array();
					$field_param['admin_forms_field_id'] = $key;
					$field_param['admin_forms_field_order'] = to_int($row['admin_forms_field_order']);
					$field_param['admin_forms_field_allow_order'] = to_int($row['admin_forms_field_allow_order']);
					$field_param['admin_forms_field_allow_filter'] = to_int($row['admin_forms_field_allow_filter']);

					if ($adm_forms->InsertAdminFormsField($field_param))
					{
						++$count_changes_fields;
						$flag_success_changes_field = true;
					}
					else
					{
						$flag_success_changes_field = false;
					}
				}
				else
				{
					$flag_success_changes_field = false;
					$user_access->MessageOnlyOwn();
				}
			}

			if ($flag_success_changes_field)
			{
				if ($count_changes_fields == 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_field_edit_success']);
				}
				elseif ($count_changes_fields > 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_fields_edit_success']);
				}
			}
			else
			{
				show_error_message($GLOBALS['MSG_admin_forms']['show_form_field_edit_error']);
			}
		}
	}
	$param['error'] = ob_get_clean();
}

/**
 * Обработчик события "Удалить" поля формы Центра администрирования
 */
function delete_field(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$adm_forms = new admin_forms();

		$count_deleted_admin_form_fields = 0;

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

				$adm_forms = new admin_forms();

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					if ($adm_forms->DeleteAdminFormsField($key))
					{
						++$count_deleted_admin_form_fields;
						$flag_success_delete_admin_form_field = true;
					}
					else
					{
						$flag_success_delete_admin_form_field = false;
					}
				}
				else
				{
					$flag_success_delete_admin_form_field = false;
					$user_access->MessageOnlyOwn();
				}
			}

			if ($flag_success_delete_admin_form_field)
			{
				if ($count_deleted_admin_form_fields == 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_field_delete_success']);
				}
				elseif ($count_deleted_admin_form_fields >1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_fields_delete_success']);
				}
			}
			else
			{
				show_error_message($GLOBALS['MSG_admin_forms']['show_form_fields_delete_error']);
			}
		}
	}
	$param['error'] = ob_get_clean();
}


/**
 * Обработчик события "Копировать" поля формы Центра администрирования
 */
function copy_field(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{

		$adm_forms_fields = new admin_forms_fields();

		$count_copy_admin_form_fields = 0;

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

				$adm_forms = new admin_forms();

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					if ($adm_forms_fields->CopyAdminFormField($key))
					{
						++$count_copy_admin_form_fields;
						$flag_success_copy_admin_form_field = true;
					}
					else
					{
						$flag_success_copy_admin_form_field = false;
					}
				}
				else
				{
					$flag_success_copy_admin_form_field = false;
					$user_access->MessageOnlyOwn();
				}

			}

			if ($flag_success_copy_admin_form_field)
			{
				if ($count_copy_admin_form_fields == 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_field_copy_success']);
				}
				elseif ($count_copy_admin_form_fields >1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_fields_copy_success']);
				}
			}
			else
			{
				show_error_message($GLOBALS['MSG_admin_forms']['show_form_fields_copy_error']);
			}
		}
	}

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

}
?>