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

	// Получаем текущий алиас сайта
	$site = & singleton ('site');

	$current_alias = $site->GetCurrentAlias(to_int($_SESSION['current_site_id']));
	$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=0", 82, 'load_data');
	$new_path_array[0]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&action=show&structure_parent_id=0", 82, 'load_data');

	$addon_path[0] = '';

	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);
				}
			}
		}
	}

	if ($structure_parent_id == 0)
	{
		unset($new_path_array[0]);
	}

	$param['path_array'] = $new_path_array;

	$addon_path = implode('/', $addon_path);

	$site_id = CURRENT_SITE;

	// Выборка нужных записей.
	$param['data'][] = "SELECT * FROM `structure_table`LEFT JOIN `menu_table`
	ON  structure_table.menu_id = menu_table.menu_id
	WHERE structure_table.structure_parent_id = '$structure_parent_id' 
	AND structure_table.site_id=$site_id
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(*) AS count FROM `structure_table` LEFT JOIN `menu_table`
	ON  structure_table.menu_id = menu_table.menu_id
	WHERE structure_table.structure_parent_id = '$structure_parent_id' 
	AND structure_table.site_id=$site_id
	{FILTER_STRING}";

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

	$p = 0;

	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_structure']['structure_add_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_node', 'check_0_0', 82, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_node', 'check_0_0', 82, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/structure_add.gif';

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_structure']['structure_external_properties_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/structure/structure.php', '', 86, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/structure/structure.php', '', 86, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/structure_gear.gif';

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

	$k++;
	$menu[$k]['name'] = $GLOBALS['MSG_structure']['menu_item_site'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$p = 0;
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_structure']['menu_item_site'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/structure/structure.php', "&action=show_structure_propertys&structure_parent_id={$structure_parent_id}", 87, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/structure/structure.php', "&action=show_structure_propertys&structure_parent_id={$structure_parent_id}", 87, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/menu.gif';

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

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

	$param['field_params'][0]['structure_path_name']['callback_function'] = 'callback_function_page_path';

	// Перекрываем некоторые данные формы
	$param['field_params'][0]['structure_activity']['admin_forms_field_type'] = 7;// картинка-ссылка
	$param['field_params'][0]['structure_activity']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('active', 'check_0_{structure_id}', 82, 0, 0);
	$param['field_params'][0]['structure_activity']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('active', 'check_0_{structure_id}', 82, 0, 0);
	$param['field_params'][0]['structure_activity']['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_structure']['structure_is_active']
	. "\n1=".$GLOBALS['MSG_structure']['structure_is_active'];
	$param['field_params'][0]['structure_activity']['admin_forms_field_title'] = "0=".$GLOBALS['MSG_structure']['structure_is_active']
	. "\n1=".$GLOBALS['MSG_structure']['structure_is_active'];


	$param['field_params'][0]['structure_allow_indexation']['admin_forms_field_type'] = 7;// картинка-ссылка
	$param['field_params'][0]['structure_allow_indexation']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('index', 'check_0_{structure_id}', 82, 0, 0);
	$param['field_params'][0]['structure_allow_indexation']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('index', 'check_0_{structure_id}', 82, 0, 0);

	$param['field_params'][0]['structure_allow_indexation']['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_structure']['structure_is_indexation']
	. "\n1=".$GLOBALS['MSG_structure']['structure_is_indexation'];
	$param['field_params'][0]['structure_allow_indexation']['admin_forms_field_title'] = "0=".$GLOBALS['MSG_structure']['structure_is_indexation']
	. "\n1=".$GLOBALS['MSG_structure']['structure_is_indexation'];

	$param['field_params'][0]['structure_path_name']['admin_forms_field_link'] = $addon_path.'/{structure_path_name}/';

	$param['field_params'][0]['structure_menu_name']['admin_forms_field_type'] = 4; // Ссылка.
	$param['field_params'][0]['structure_menu_name']['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&structure_parent_id={structure_id}", 82, 'load_data');
	$param['field_params'][0]['structure_menu_name']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&structure_parent_id={structure_id}", 82, 'load_data');

	// Функция обратного вызова для ФИЛЬТРА поля "Дата"
	$param['field_params']['filter']['menu_table.menu_id']['filter_callback_function'] = 'filter_callback_function_menu_name';

	function filter_callback_function_menu_name ($field_value, $value, $row)
	{
		$menu = new menu();

		$resource_menu = $menu->GetAllMenu(CURRENT_SITE);
		?>
<select
	name="admin_form_filter_<?php echo $row['admin_forms_field_id']?>">
	<option value="">Все</option>
	<?php
	while ($row_menu = mysql_fetch_assoc($resource_menu))
	{
		if ($row_menu['menu_id'] == to_int($_GET['admin_form_filter_'.$row['admin_forms_field_id']]))
		{
			$selected = ' selected=""';
		}
		else
		{
			$selected = '';
		}
		?>
	<option value="<?php echo $row_menu['menu_id']?>"
	<?php echo $selected;?>><?php echo $row_menu['menu_name']?></option>
	<?php

	$selected = '';
	}
	?>
</select>
	<?php
	}

	$param['field_params'][0]['menu_table.menu_id']['callback_function'] = 'callback_function_menu_name';

	function callback_function_menu_name ($field_value, $value, $row)
	{
		$menu = new menu();
		$menu_info = $menu->SelectMenu($row['menu_id']);
		echo to_str($menu_info['menu_name']);
	}

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

	// Функция обратного вызова для отображениия пути к странице сайта,
	// соответствующей данному узлу структуры
	function callback_function_page_path($field_value, $value, $row)
	{
		$structure_id = to_int($row['structure_id']);

		$Structure = & singleton('Structure');

		// Получаем полный путь к узлу структуры
		$structure_full_path = $Structure->GetStructurePath($structure_id, 0);

		$value = trim($value);

		$url = new url();

		$site_id = CURRENT_SITE;

		// Выбираем основной алиас текущего сайта, для ссылки со страницы
		$site = & singleton ('site');

		$alias_name = $site->GetCurrentAlias($site_id);

		if (!$alias_name)
		{
			$alias_name = '';
		}

		if ($row['structure_activity'] == 0)
		{
			$prefix = '<div style="text-decoration: line-through">';
			$suffix = '</div>';
		}
		else
		{
			$prefix = '';
			$suffix = '';
		}
		
		if (mb_strlen($value) != 0)
		{
			?><?php echo $prefix?><a href="http://<?php echo htmlspecialchars($alias_name . '/' . $structure_full_path)?>" target="_blank"><?php echo  '/' . urldecode($structure_full_path)?></a><?php echo $suffix?><?php
		}
		else
		{
			?>&nbsp;<?php
		}
	}

	return $param;
}

// Изменение статуса активности узла структуры
function active(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$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_row = $structure->GetStructureItem($key, array('cache_off' => true));

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

					if ($object_row && $user_access->IssetUserAccessForObject($object_user_id))
					{
						// Изменяем статус активности
						$query = "UPDATE `structure_table` SET `structure_activity` = 1 - `structure_activity` WHERE `structure_id` = '$key'";
						$DataBase->query($query);

						// Добавляем индексирование информационного элемента
						if (class_exists('Search'))
						{
							$result = $structure->IndexationStructure(0, 1, array('structure_id' => $key));

							if (count($result) != 0)
							{
								$Search = & singleton('Search');
								$line = each($result);
								if (isset($line['value'][1]))
								{
									$Search->Delete_search_words($line['value'][1], $line['value'][4]);
										
									// Данные получаем еще раз после изменения.
									$object_row = $structure->GetStructureItem($key, array('cache_off' => true));
										
									if ($object_row['structure_activity'] == 1
									&& $object_row['structure_allow_indexation'] == 1)
									{
										$Search->Insert_search_word($result);
									}
								}
							}
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}

	$error = ob_get_clean();

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

// Изменение статуса индексации узла структуры
function index(&$param)
{
	ob_start();

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

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

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

					$structure = & singleton('Structure');

					// Определяем информацию об объекте
					$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))
					{
						if (class_exists('Search'))
						{
							$result = $structure->IndexationStructure(0, 1, array('structure_id' => $key));
						
							if (count($result) != 0)
							{
								$Search = & singleton('Search');
								$line = each($result);
								if (isset($line['value'][1]))
								{
									$Search->Delete_search_words($line['value'][1], $line['value'][4]);
								}
							}
						}
						
						$query = "UPDATE `structure_table` SET `structure_allow_indexation` = 1 - `structure_allow_indexation` WHERE `structure_id` = '$key'";
						$DataBase->query($query);

						// Добавляем индексирование информационного элемента
						if (class_exists('Search'))
						{
							$result = $structure->IndexationStructure(0, 1, array('structure_id' => $key));

							if (count($result) != 0)
							{
								$Search = & singleton('Search');
								$line = each($result);
								if (isset($line['value'][1]))
								{
									//$Search->Delete_search_words($line['value'][1], $line['value'][4]);
										
									// Данные получаем еще раз после изменения.
									$object_row = $structure->GetStructureItem($key, array('cache_off' => true));
										
									if ($object_row['structure_activity'] == 1
									&& $object_row['structure_allow_indexation'] == 1)
									{
										$Search->Insert_search_word($result);
									}
								}
							}
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}

	$error = ob_get_clean();

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

// Применить изменения
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_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))
					{
						$val = to_int($value['structure_order']);

						$query = "UPDATE `structure_table` SET `structure_order` = '$val' WHERE `structure_id` = '$key'";

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

	$error = ob_get_clean();

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

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

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

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

		$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_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))
					{
						if (!$structure->DeleteStructure($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']['structure_node_delete_success_message']);
				}
				else
				{
					show_message($GLOBALS['MSG_structure']['structure_nodes_delete_success_message']);
				}
			}
			/*else
			 {
				show_error_message($GLOBALS['MSG_structure']['structure_nodes_delete_error_message']);
				}*/
		}

	}
	$error = ob_get_clean();

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


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

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

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

				$structure = & singleton('Structure');

				// Определяем информацию об объекте
				$object_row = $structure->GetStructureItem($structure_id, 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))
				{
					include(CMS_FOLDER . 'admin/structure/action/add_edit_form.php');

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

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

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

	return true;
}


// Обработчик события "Копировать" структуры сайта
function copy_node(&$param)
{
	ob_start();

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

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

		$count_copys_structure = 0;

		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_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))
					{
						if ($structure->CopyStructure($key))
						{
							$count_copys_structure++;

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

						$flag_success_structure_copy = false;
					}
				}


				if ($flag_success_structure_copy)
				{
					if ($count_copys_structure == 1)
					{
						show_message($GLOBALS['MSG_structure']['structure_node_copy_success_message']);
					}
					else
					{
						show_message($GLOBALS['MSG_structure']['structure_nodes_copy_success_message']);
					}
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}
?>