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

	$DateClass = new DateClass();

	$where = '';

	// Дата От
	if (to_str($_REQUEST['admin_form_filter_from_655']) == '')
	{
		if (isset($_SESSION['seo_date_from']))
		{
			// Берем из сессии
			$date_begin = quote_smart($DateClass->datetime_format_sql(to_str($_SESSION['seo_date_from'])));
		}
		else
		{
			$date_begin = date('Y-m-d H:i:s', time() - 60*60*24*31);
		}
	}
	else
	{
		$date_begin = quote_smart($DateClass->datetime_format_sql(to_str($_REQUEST['admin_form_filter_from_655'])));

		// Сохраним в сессию
		$_SESSION['seo_date_from'] = to_str($_REQUEST['admin_form_filter_from_655']);
	}

	$where .= " AND `seo_characteristic_date_time` >= '{$date_begin}' ";

	if (to_str($_REQUEST['admin_form_filter_to_655']) == '')
	{
		if (isset($_SESSION['seo_date_to']))
		{
			// Берем из сессии
			$date_end = quote_smart($DateClass->datetime_format_sql(to_str($_SESSION['seo_date_to'])));
		}
		else
		{
			$date_end = date('Y-m-d H:i:s', time() + 60*60*24*1);
		}
	}
	else
	{
		$date_end = quote_smart($DateClass->datetime_format_sql(to_str($_REQUEST['admin_form_filter_to_655'])));

		// Сохраним в сессию
		$_SESSION['seo_date_to'] = to_str($_REQUEST['admin_form_filter_to_655']);
	}

	$where .= " AND `seo_characteristic_date_time` <= '{$date_end}' ";

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

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

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

	// Характеристики
	$menu[$k = 0]['name'] = $GLOBALS['MSG_seo']['menu_characteristic'];
	$menu[$k]['link'] = '';

	// Добавить
	$sub_menu = array();
	$sub_menu[$p = 0]['name'] = $GLOBALS['MSG_seo']['menu_characteristic_add'];
	$sub_menu[$p]['link'] =  $admin_forms->GetHtmlCallTrigerSingleAction('edit_characteristic', 'check_0_0', 141, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_characteristic', 'check_0_0', 141, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/seo_add.gif';
	$p++;

	//Запросить для сайта
	$sub_menu[$p]['name'] = $GLOBALS['MSG_seo']['menu_characteristic_query_for_site'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('query_characteristic', 'check_0_0', 141, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('query_characteristic', 'check_0_0', 141, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/seo_go.gif';

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

	//Поисковые запросы
	$menu[++$k]['name'] = $GLOBALS['MSG_seo']['menu_search_query'];
	$menu[$k]['link'] = '';

	//Управление запросами
	$sub_menu = array();
	$sub_menu[$p = 0]['name'] = $GLOBALS['MSG_seo']['menu_search_query_manage'];
	$sub_menu[$p]['link'] =  $admin_forms->GetHtmlCallTrigerSingleAction('manage_query', '', 142, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('manage_query', '', 142, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/query.gif';
	$p++;

	//Определить позиции
	$sub_menu[$p]['name'] = $GLOBALS['MSG_seo']['menu_query_get_position'];
	$sub_menu[$p]['link'] =  $admin_forms->GetHtmlCallDoLoadAjax('/admin/seo/seo.php', '&calc_positions=1', 142, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/seo/seo.php', '&calc_positions=1', 142, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/query_go.gif';
	$p++;

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

	//Отчет
	$menu[++$k]['name'] = $GLOBALS['MSG_seo']['menu_report'];
	$menu[$k]['link'] = '';

	//Сформировать отчет
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_seo']['report_form'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/seo/seo.php', '&action=report', 0, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/seo/seo.php', '&action=report', 0, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/report.gif';

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

	$param['menus'] = array($menu);
	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;

	//Заголовок формы
	$param['title'] = $GLOBALS['MSG_seo']['search_optimize'];

	$param['filter_values'][655]['date_from'] = $DateClass->datetime_format($date_begin);
	$param['filter_values'][655]['date_to'] = $DateClass->datetime_format($date_end);

	return $param;
}

//Обработчик событий

/**
 * Обработчик события "Редактировать характеристику"
 *
 * @param array $param 
 * @return boolean
 */
function edit_characteristic(&$param)
{
	ob_start();

	//Установлен режим "только для чтения"
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');
		$kernel->ReadMode();
	}
	else
	{

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

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

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

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

						include(CMS_FOLDER . 'admin/seo/action/form_edit_add_characteristic.php');

						//Устанавливаем <title> для страницы
						$param['title'] = $edit_characteristic_id == 0
						? $GLOBALS['MSG_seo']['characteristic_add_form_title']
						: $GLOBALS['MSG_seo']['characteristic_edit_form_title'];

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

		return true;
	}
}

/**
 * Обработчик события "Удалить характеристику"
 *
 * @param array $param
 * @return boolean
 */
function delete_characteristic(&$param)
{
	ob_start();

	//Установлен режим "только для чтения"
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');
		$kernel->ReadMode();
	}
	else
	{
		$count_deleted_characteristic = 0;

		$seo = new seo();

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

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$seo->DeleteCharacteristic($key))
						{
							$flag_deleted_characteristic_access = false;
						}
						else
						{
							$count_deleted_characteristic++;

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

						$flag_deleted_characteristic_access = false;
					}
				}

				if ($flag_deleted_characteristic_access)
				{
					if ($count_deleted_characteristic == 1)
					{
						show_message($GLOBALS['MSG_seo']['delete_characteristic_success']);
					}
					else
					{
						show_message($GLOBALS['MSG_seo']['delete_characteristics_success']);
					}
				}
				else
				{
					show_error_message($GLOBALS['MSG_seo']['delete_characteristic_error']);
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}

/**
 * Обработчик события "Запросить для сайта"
 *
 * @param array $param
 * @return boolean
 */
function query_characteristic(&$param)
{
	ob_start();

	//Установлен режим "только для чтения"
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');
		$kernel->ReadMode();
	}
	else
	{
		$seo = new Seo();
		$param = array();
		$site = new site();

		$param['site_id'] = CURRENT_SITE;
		$site_alias = $site->GetCurrentAlias(CURRENT_SITE);

		if ($site_alias)
		{
			if ($info = $seo->GetYandexCatalog($site_alias))
			{
				$param['seo_characteristic_yc_rubric'] = to_str($info['topic']);
				$param['seo_characteristic_yc'] = to_int($info['tyc']);
			}
			else
			{
				$param['seo_characteristic_yc_rubric'] = '';
				$param['seo_characteristic_yc'] = 0;
			}

			if (trim($param['seo_characteristic_yc_rubric']) == '')
			{
				$param['seo_characteristic_catalog_yandex'] = 0;
			}
			else
			{
				$param['seo_characteristic_catalog_yandex'] = 1;
			}

			$param['seo_characteristic_date_time'] = date("d.m.Y H:i:s");
			$param['seo_characteristic_links_yandex'] = $seo->GetLinksYandex($site_alias);
			$param['seo_characteristic_pr'] = $seo->GetPageRank($site_alias);
			$param['seo_characteristic_links_google'] = $seo->GetLinksGoogle($site_alias);
			$param['seo_characteristic_links_yahoo'] = $seo->GetLinksYahoo($site_alias);
			$param['seo_characteristic_links_msn'] = $seo->GetLinksMsn($site_alias);

			// Если не запрещено определение позиций Апорта
			if (defined('SEO_APORT') && SEO_APORT)
			{
				$param['seo_characteristic_indexed_aport'] = $seo->GetIndexAport($site_alias);
				$param['seo_characteristic_catalog_aport'] = $seo->GetAportCatalog($site_alias);
			}

			$param['seo_characteristic_indexed_yandex'] = $seo->GetIndexYandex($site_alias);

			$param['seo_characteristic_indexed_msn'] = $seo->GetIndexMsn($site_alias);
			$param['seo_characteristic_indexed_rambler'] = $seo->GetIndexRambler($site_alias);
			$param['seo_characteristic_indexed_google'] = $seo->GetIndexGoogle($site_alias);
			$param['seo_characteristic_catalog_rambler'] = $seo->GetRamblerCatalog($site_alias);
			$param['seo_characteristic_catalog_mail'] = $seo->GetMailCatalog($site_alias);
			$param['seo_characteristic_catalog_dmoz'] = $seo->GetDmozCatalog($site_alias);

			if ($seo->GetCounterRambler($site_alias))
			{
				$param['seo_characteristic_counter_rambler'] = 1;
			}
			else
			{
				$param['seo_characteristic_counter_rambler'] = 0;
			}

			if ($seo->GetCounterSpyLog($site_alias))
			{
				$param['seo_characteristic_counter_spylog'] = 1;
			}
			else
			{
				$param['seo_characteristic_counter_spylog'] = 0;
			}

			if ($seo->GetCounterHotLog($site_alias))
			{
				$param['seo_characteristic_counter_hotlog'] = 1;
			}
			else
			{
				$param['seo_characteristic_counter_hotlog'] = 0;
			}

			if ($seo->GetCounterMail($site_alias))
			{
				$param['seo_characteristic_counter_mail'] = 1;
			}
			else
			{
				$param['seo_characteristic_counter_mail'] = 0;
			}

			if ($seo->GetCounterLiveInternet($site_alias))
			{
				$param['seo_characteristic_counter_liveinternet'] = 1;
			}
			else
			{
				$param['seo_characteristic_counter_liveinternet'] = 0;
			}

			/*
			$param['seo_characteristic_counter_rambler'] = $seo->GetCounterRambler($site_alias);
			$param['seo_characteristic_counter_spylog'] = $seo->GetCounterSpyLog($site_alias);
			$param['seo_characteristic_counter_hotlog'] = $seo->GetCounterHotLog($site_alias);
			$param['seo_characteristic_counter_mail'] = $seo->GetCounterMail($site_alias);
			$param['seo_characteristic_counter_liveinternet'] = $seo->GetCounterLiveInternet($site_alias);
			*/

			//usleep(500000);
			// Вынесено ниже для защиты от блокировки Yahoo запросов.
			$param['seo_characteristic_indexed_yahoo'] = $seo->GetIndexYahoo($site_alias);

			//Передаем характеристики методу для вставки в БД
			$seo->InsertCharacteristic($param);
			//Характеристика добавлена успешно
			show_message($GLOBALS['MSG_seo']['information_success']);
		}
		else
		{
			// Ошибка, основной домен сайта не найден
			show_error_message($GLOBALS['MSG_seo']['information_success_error']);
		}
	}
	$param['error'] = ob_get_clean();
}

?>