<?php

/*
 * 0 - PHP-генерация
 * 1 - XSL-генерация
 */
$type = 0;

// Настройки типовой динамической старницы "GoogleSiteMap"
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";

$Structure = & singleton('Structure');

$param = array();

// Показывать группы информационных систем в карте сайта
$param['show_groups'] = to_bool($GLOBALS['LA']['show_groups']);

// Показывать элементы информационных систем в карте сайта
$param['show_items'] = to_bool($GLOBALS['LA']['show_items']);

// Показывать группы магазина в карте сайта
$param['show_shop_groups'] = to_bool($GLOBALS['LA']['show_shop_groups']);

// Показывать товары магазина в карте сайта
$param['show_shop_items'] = to_bool($GLOBALS['LA']['show_shop_items']);

if ($type == 0)
{
	echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";

	$parent_id = 0;

	$site_id = CURRENT_SITE;

	if (class_exists('SiteUsers'))
	{
		$SiteUsers = & singleton('SiteUsers');
		$site_user_id = $SiteUsers->GetCurrentSiteUser();

		if ($site_user_id > 0)
		{
			$access = $SiteUsers->GetGroupsForUser($site_user_id);
		}
	}
	else
	{
		$site_user_id = 0;
	}

	// Добавляем информацию о сайте
	$DataBase = & singleton('DataBase');

	$query = "SELECT * FROM structure_table
	WHERE `site_id` = '{$site_id}'
	ORDER BY structure_parent_id, structure_order, structure_menu_name";

	$result = $DataBase->select($query);

	while ($row = mysql_fetch_assoc($result))
	{
		$Structure->StructureMass[$row['structure_id']] = $row;

		// Нужно для вывода подстраниц из инфосистем, когда у самой структуры потомков нет
		if (!isset ($Structure->StructureParentMass[$row['structure_id']]))
		{
			$Structure->StructureParentMass[$row['structure_id']] = array ();
		}

		// Для массива родителей сохраняем только ID элементов
		$Structure->StructureParentMass[intval($row['structure_parent_id'])][] = intval($row['structure_id']);
	}

	mysql_free_result($result);

	function ShowXmlNode($loc, $changefreq, $priority)
	{
		echo "<url>\n";
		echo "<loc>{$loc}</loc>\n";

		switch ($changefreq)
		{
			case 0 : { $sChangefreq = 'always'; break; }
			case 1 : { $sChangefreq = 'hourly'; break; }
			default:
			case 2 : { $sChangefreq = 'daily'; break; }
			case 3 : { $sChangefreq = 'weekly'; break; }
			case 4 : { $sChangefreq = 'monthly'; break; }
			case 5 : { $sChangefreq = 'yearly'; break; }
			case 6 : { $sChangefreq = 'never'; break; }
		}

		echo "<changefreq>" . str_for_xml($sChangefreq) . "</changefreq>\n";
		echo "<priority>" . str_for_xml($priority) . "</priority>\n";
		echo "</url>\n";
	}

	function GetStructureXml($structure_id, $param)
	{
		$Structure = & singleton('Structure');
		$structure_row = $Structure->GetStructureItem($structure_id);

		// получем право доступа к узлу структуры
		$structure_access = $Structure->GetStructureAccess($structure_row['structure_id']);

		$access = array(0);

		if (class_exists('SiteUsers'))
		{
			$SiteUsers = & singleton('SiteUsers');
			$site_user_id = $SiteUsers->GetCurrentSiteUser();

			if ($site_user_id > 0)
			{
				$access = $SiteUsers->GetGroupsForUser($site_user_id);
			}
		}
		else
		{
			$site_user_id = 0;
		}

		// если есть доступ к данному разделу и которые активны
		if (in_array($structure_access, $access) && $structure_row['structure_activity'] == 1)
		{
			$site = & singleton('site');
			$alias = $site->GetCurrentAlias(CURRENT_SITE);

			if (!(($structure_row['documents_id'] == 0 && mb_strlen((trim($structure_row['structure_external_link']))) == 0)
			&& $structure_row['structure_type'] == 0))
			{
				if (!isset($structure_row['full_path']))
				{
					// Полный путь к файлу
					$path = $Structure->GetStructurePath($structure_row['structure_id'], 0);

					if (trim($path) != '/')
					{
						$path = '/' . $path;
					}

					$Structure->StructureMass[$structure_row['structure_id']]['full_path'] = $path;
					$structure_row['full_path'] = $path;
				}

				// ----

				$loc = "http://{$alias}{$structure_row['full_path']}";
				$changefreq = $structure_row['structure_change_frequency'];
				$priority = $structure_row['structure_priority'];

				ShowXmlNode($loc, $changefreq, $priority);

				// Формируем массив подпунктов по двум готовым массивам и генерирем для него XML
				if (isset ($Structure->StructureParentMass[$structure_row['structure_id']])
				&& is_array($Structure->StructureParentMass[$structure_row['structure_id']]))
				{
					foreach ($Structure->StructureParentMass[$structure_row['structure_id']] as $key => $value)
					{
						// Вызываем рекурсивно построение XML для подпунктов
						GetStructureXml($value, $param);
					}
				}
			}
		}

		// Удаляем использованый элемент из массива для экономии памяти
		if (isset($Structure->StructureMass[$structure_id]))
		{
			unset ($Structure->StructureMass[$structure_id]);
		}
	}

	if (isset ($Structure->StructureParentMass[$parent_id]))
	{
		// Получаем количество узлов для указанного родителя
		$count = count($Structure->StructureParentMass[$parent_id]);

		for ($i = 0; $i < $count; $i++)
		{
			$structure_id = $Structure->StructureParentMass[$parent_id][$i];
			GetStructureXml($structure_id, $param);
		}
	}

	//---------------------

	$site = & singleton('site');
	$alias = $site->GetCurrentAlias(CURRENT_SITE);

	if ($param['show_items'] || $param['show_groups'])
	{
		$InformatioSystem = & singleton('InformationSystem');

$query = "SELECT * FROM information_systems_table
		WHERE `site_id` = '$site_id' AND structure_id > 0";

		$rows = $DataBase->select($query);

		// Получаем массив инф. систем
		$Structure->MassIS = array ();

		while ($row = mysql_fetch_assoc($rows))
		{
$structure_row = $Structure->GetStructureItem($row['structure_id']);

if($structure_row && $structure_row['structure_activity'] == 1)
{
			$Structure->MassIS[$row['structure_id']] = $row['information_systems_id'];

			// Сохраняем в массив ИС полученные данные
			$InformatioSystem->cache_InformationSystem[$row['information_systems_id']] = $row;
}
		}

		if (count($Structure->MassIS) > 0)
		{
			if ($param['show_groups'])
			{
				$query = "SELECT * FROM information_groups_table
				WHERE `information_groups_activity` = 1
				AND `information_systems_id` IN (" . implode(', ', $Structure->MassIS) . ")";

				$rows = $DataBase->select($query);

				while ($row = mysql_fetch_assoc($rows))
				{
					// Проверяем права доступа текущего зарегистрированного пользователя к информационной группе
					if ($InformatioSystem->IssetAccessForInformationSystemGroup($site_user_id, $row['information_groups_id'], $row['information_systems_id'], $row))
					{
						$infsys_row = $InformatioSystem->GetInformationSystem($row['information_systems_id']);
							
						if ($infsys_row)
						{
							$structure_path = '/'.$Structure->GetStructurePath($infsys_row['structure_id'], 0);

							$structure_row = $Structure->GetStructureItem($infsys_row['structure_id']);

							$current_path = $structure_path . $InformatioSystem->GetPathGroup($row['information_groups_id']);
								
							// ----
							$loc = "http://{$alias}{$current_path}";
							$changefreq = $structure_row['structure_change_frequency'];
							$priority = $structure_row['structure_priority'];
								
							ShowXmlNode($loc, $changefreq, $priority);
								
							$InformatioSystem->MasGroup = array();
						}
					}
				}

				mysql_free_result($rows);
			}
				
			if ($param['show_items'])
			{
				$current_date = date('Y-m-d H:i:s');

				$query_select_information_system = "SELECT * FROM information_items_table
				WHERE `information_systems_id` IN (" . implode(', ', $Structure->MassIS) . ")
				AND information_items_table.information_items_putoff_date <= '$current_date'
				AND(information_items_table.information_items_putend_date >= '$current_date'
				OR information_items_table.information_items_putend_date = '0000-00-00 00:00:00')
				AND information_items_table.information_items_status = '1'
				AND information_items_table.information_items_shortcut_id = '0'";

				$rows = $DataBase->select($query_select_information_system);

				while ($row = mysql_fetch_assoc($rows))
				{
					/* Проверяем права доступа к элементу*/
					if ($InformatioSystem->GetAccessItem($site_user_id, $row['information_items_id'], $row))
					{
						$infsys_row = $InformatioSystem->GetInformationSystem($row['information_systems_id']);

						if ($infsys_row)
						{
							$structure_path = '/'.$Structure->GetStructurePath($infsys_row['structure_id'], 0);
								
							$structure_row = $Structure->GetStructureItem($infsys_row['structure_id']);

							$current_path = $structure_path . $InformatioSystem->GetPathItem($row['information_items_id'], '', $row);
								
							// ----
							$loc = "http://{$alias}{$current_path}";
							$changefreq = $structure_row['structure_change_frequency'];
							$priority = $structure_row['structure_priority'];
								
							ShowXmlNode($loc, $changefreq, $priority);
								
							$InformatioSystem->MasGroup = array();
							$InformatioSystem->ItemMass = array();
						}
					}
				}

				mysql_free_result($rows);
			}
		}
	}


	if (class_exists('shop'))
	{
		$Structure->MassShopShops = array ();

		$shop = & singleton('shop');

		if ($param['show_shop_groups'] || $param['show_shop_items'])
		{
			$query = "SELECT * FROM shop_shops_table
			WHERE site_id = '$site_id' AND structure_id > 0";

			$rows = $DataBase->select($query);

			while ($row = mysql_fetch_assoc($rows))
			{
$structure_row = $Structure->GetStructureItem($row['structure_id']);

if($structure_row && $structure_row['structure_activity'] == 1)
{
				$Structure->MassShopShops[$row['structure_id']] = $row['shop_shops_id'];

				// Сохраняем в массив магазинов полученные данные
				$shop->g_array_shop[$row['shop_shops_id']] = $row;
}
			}

if (count($Structure->MassShopShops) > 0)
{
			if ($param['show_shop_groups'])
			{
				$query = "SELECT * FROM shop_groups_table
				WHERE `shop_groups_activity` = 1
				AND `shop_shops_id` IN (" . implode(', ', $Structure->MassShopShops) . ")";

				$rows = $DataBase->select($query);

				while ($row = mysql_fetch_assoc($rows))
				{
					// Проверяем права доступа текущего зарегистрированного пользователя к группе
					$param_group_access = array();
					$param_group_access['site_users_id'] = $site_user_id;
					$param_group_access['shop_group_id'] = $row['shop_groups_id'];
					$param_group_access['shop_id'] = $row['shop_shops_id'];
					$param_group_access['shop_group_info'] = $row;
						
					if ($shop->IssetAccessForShopGroup($param_group_access))
					{
						$shop_row = $shop->GetShop($row['shop_shops_id']);
							
						if ($shop_row)
						{
							$structure_path = '/'.$Structure->GetStructurePath($shop_row['structure_id'], 0);

							$structure_row = $Structure->GetStructureItem($shop_row['structure_id']);

							$current_path = $structure_path . $shop->GetPathGroup($row['shop_groups_id']);
								
							// ----
							$loc = "http://{$alias}{$current_path}";
							$changefreq = $structure_row['structure_change_frequency'];
							$priority = $structure_row['structure_priority'];
								
							ShowXmlNode($loc, $changefreq, $priority);
								
							$shop->MasGroup = array();
						}
					}
				}

				mysql_free_result($rows);
			}

			if ($param['show_shop_items'] && count($Structure->MassShopShops) > 0)
			{
				$current_date = date('Y-m-d H:i:s');

				$query_select_shop = "SELECT * FROM shop_items_catalog_table
				WHERE `shop_shops_id` IN (" . implode(', ', $Structure->MassShopShops) . ")
				AND shop_items_catalog_table.shop_items_catalog_putoff_date <= '$current_date'
				AND(shop_items_catalog_table.shop_items_catalog_putend_date >= '$current_date'
				OR shop_items_catalog_table.shop_items_catalog_putend_date = '0000-00-00 00:00:00')
				AND shop_items_catalog_table.shop_items_catalog_modification_id = 0
				AND shop_items_catalog_table.shop_items_catalog_is_active = '1'
				AND shop_items_catalog_table.shop_items_catalog_shortcut_id = '0'";

				$rows = $DataBase->select($query_select_shop);

				while ($row = mysql_fetch_assoc($rows))
				{
					// Проверяем права доступа к товару
					if ($shop->GetAccessShopItem($site_user_id, $row['shop_items_catalog_item_id'], $row))
					{
						$shop_row = $shop->GetShop($row['shop_shops_id']);
							
						if ($shop_row)
						{
							$structure_path = '/'.$Structure->GetStructurePath($shop_row['structure_id'], 0);

							$structure_row = $Structure->GetStructureItem($shop_row['structure_id']);
								
							$current_path = $structure_path . $shop->GetPathItem($row['shop_items_catalog_item_id']) . rawurlencode($row['shop_items_catalog_path']).'/';

							// ----
							$loc = "http://{$alias}{$current_path}";
							$changefreq = $structure_row['structure_change_frequency'];
							$priority = $structure_row['structure_priority'];
								
							ShowXmlNode($loc, $changefreq, $priority);
								
							$shop->MasGroup = array();
							$shop->CacheGetItem = array();
						}
					}
				}

				mysql_free_result($rows);
			}
}
		}
	}

	echo "</urlset>\n";
}
else
{
	$xsl = to_str($GLOBALS['LA']['xsl']);

	// Формируем карту сайта GoogleSiteMap
	$Structure->ShowStructure(false, $xsl, $param);
}

exit();
?>