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

	$structure = & singleton('Structure');

	$param = array();

	$param['limit'][0] = array('begin' => $begin, 'count' => $on_page);

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

	$struct = & singleton('Structure');

	$path_array = $struct->GetStructurePathArray($structure_parent_id, false);

	// Массив "хлебных крошек"
	$new_path_array = array();

	$new_path_array[0]['name'] = $GLOBALS['MSG_structure']['parent_dir'];
	$new_path_array[0]['link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&action=show&structure_parent_id={$structure_parent_id}", 82, 'load_data');
	$new_path_array[0]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&action=show&structure_parent_id={$structure_parent_id}", 82, 'load_data');

	if ($path_array)
	{
		foreach ($path_array as $keys => $values)
		{
			foreach ($values as $key => $value)
			{
				if (!is_numeric($key))
				{
					//$addon_path[] = $value;
				}
				else
				{
					$new_path_array[] = array (
					'link' => $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&action=show&structure_parent_id={$key}", 82, 'load_data'),
					'onclick' => $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&action=show&structure_parent_id={$key}", 82, 'load_data'),
					'name' => $value);
				}
			}
		}
	}

	$new_path_array[1]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/structure/structure.php', "&action=show_structure_propertys&structure_parent_id={$structure_parent_id}", 86, 'load_data');
	$new_path_array[1]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/structure/structure.php', "&action=show_structure_propertys&structure_parent_id={$structure_parent_id}", 86, 'load_data');
	$new_path_array[1]['name'] = $GLOBALS['MSG_structure']['structure_propertys_show_title'];

	$param['path_array'] = $new_path_array;

	// Выборка нужных записей.
	$param['data'][] = "SELECT * FROM `structure_propertys_table` WHERE `site_id`=".CURRENT_SITE."
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(*) AS count FROM `structure_propertys_table` WHERE `site_id`=".CURRENT_SITE."
	{FILTER_STRING}";

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

	$p = 0;

	// Формируем подэлементы.
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_structure']['add_properties'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_node_prop', 'check_0_0', 86, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_node_prop', 'check_0_0', 86, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/structure_gear_add.gif';

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

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

	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;
	$param['title'] = $GLOBALS['MSG_structure']['structure_propertys_show_title'];

	return $param;

}

// Применить изменения
function apply_change(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$params = array();

		$DataBase = & singleton('DataBase');

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

					$structure = & singleton('Structure');

					// Определяем информацию об объекте
					$object_res = $structure->SelectStructurePropertys(CURRENT_SITE, $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))
					{
						$val = to_int($value['structure_propertys_order']);

						$key = to_int($key);

						$query = "UPDATE `structure_propertys_table` SET `structure_propertys_order` = '$val' WHERE `structure_propertys_id` = '$key'";

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

	$error = ob_get_clean();

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

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

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

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

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

				// Определяем информацию об объекте
				$object_row = $structure->GetStructureItem($key, array('cache_off' => true));

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

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

// Обработчик удаления меню
function delete_node_prop(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$count = 0;

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

					$structure = & singleton('Structure');

					// Определяем информацию об объекте
					$object_res = $structure->SelectStructurePropertys(CURRENT_SITE, $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 (!$structure->DelStructurePropertys($key))
						{
							$flag_success = false;
						}
						else
						{
							$count++;

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

						$flag_success = false;
					}
				}
			}

			if ($flag_success)
			{
				if ($count == 1)
				{
					show_message($GLOBALS['MSG_structure']['delete_structure_propertys']);
				}
				else
				{
					show_message($GLOBALS['MSG_structure']['deletes_structure_propertys']);
				}
			}
		}
	}

	$error = ob_get_clean();

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

// Обработчик добавления/редактирования дополнительного свойства узлов структуры
function edit_node_prop(&$param)
{
	ob_start();

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

	if (isset($param['data']))
	{
		$structure_propertys_id = 0;

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

				$structure = & singleton('Structure');

				// Определяем информацию об объекте
				$object_res = $structure->SelectStructurePropertys(CURRENT_SITE, $structure_propertys_id);

				if (mysql_num_rows($object_res) == 1)
				{
					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;
					}
				}
				else
				{
					$object_user_id = 0;
				}

				//echo '$object_user_id = '.$object_user_id.'<br>';
				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					include(CMS_FOLDER.'admin/structure/action/edit_structure_propertys.php');

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

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

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

	return true;
}

?>