<?php

/**
 * Автоматическая генерация пакета установки макета для сайта
 *
 * @package HostCMS
 * @version 7.x
 * @author Hostmake LLC
 * @copyright © 2005-2024 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 * @version 2025-02-13
 */

require_once(dirname(__FILE__) . '/' . 'bootstrap.php');

// Экранирование апострофа
function addslashesapostrophe($str)
{
	return str_replace("'", "\'", (string) $str);
}

class Install {
	static public $aLngs = array();

	static public $i18n = array();

	static public $iSiteId = NULL;

	// Заполнение списка сайтов системы
	static public function setSites()
	{
		$oSites = Core_Entity::factory('Site');

		$oSites
			->queryBuilder()
			->where('sites.active', '=', 1)
			->clearOrderBy()
			->orderBy('sites.id', 'ASC');

		$aSites = $oSites->findAll();

		foreach ($aSites as $oSite)
		{
			?><option value="<?php echo $oSite->id?>" <?php echo Core_Array::getPost('site_id') == $oSite->id ? 'selected="selected"' : ''?>><?php echo $oSite->name?></option><?php
		}
	}

	// Получение групп XSL-шаблонов
	static public function getXslDirName(Xsl_Model $oXsl)
	{
		$aReturn = array();
		if ($oXsl->xsl_dir_id)
		{
			$oXsl_Dir = $oXsl->Xsl_Dir;

			do {
				$aReturn[] = $oXsl_Dir->name;
				$oXsl_Dir = $oXsl_Dir->getParent();
			} while ($oXsl_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп TPL-шаблонов
	static public function getTplDirName(Tpl_Model $oTpl)
	{
		$aReturn = array();
		if ($oTpl->tpl_dir_id)
		{
			$oTpl_Dir = $oTpl->Tpl_Dir;

			do {
				$aReturn[] = $oTpl_Dir->name;
				$oTpl_Dir = $oTpl_Dir->getParent();
			} while ($oTpl_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп констант
	static public function getConstantDirName(Constant_Model $oConstant)
	{
		$aReturn = array();
		if ($oConstant->constant_dir_id)
		{
			$oConstant_Dir = $oConstant->Constant_Dir;

			do {
				$aReturn[] = $oConstant_Dir->name;
				$oConstant_Dir = $oConstant_Dir->getParent();
			} while ($oConstant_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп XSL-шаблонов
	static public function getLibDirName(Lib_Model $oLib)
	{
		$aReturn = array();
		if ($oLib->lib_dir_id)
		{
			$oLib_Dir = $oLib->Lib_Dir;

			do {
				$aReturn[] = $oLib_Dir->name;
				$oLib_Dir = $oLib_Dir->getParent();
			} while ($oLib_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп макетов
	static public function getTemplateDirName(Template_Model $oTemplate)
	{
		$aReturn = array();
		if ($oTemplate->template_id)
		{
			$oTemplate_Dir = $oTemplate->Template_Dir;

			do {
				$aReturn[] = $oTemplate_Dir->name;
				$oTemplate_Dir = $oTemplate_Dir->getParent();
			} while ($oTemplate_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп документов
	static public function getDocumentDirName(Document_Model $oDocument)
	{
		$aReturn = array();
		if ($oDocument->document_dir_id)
		{
			$oDocument_Dir = $oDocument->Document_Dir;

			do {
				$aReturn[] = $oDocument_Dir->name;
				$oDocument_Dir = $oDocument_Dir->getParent();
			} while ($oDocument_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп списков
	static public function getListDirName(List_Model $oList)
	{
		$aReturn = array();
		if ($oList->list_dir_id)
		{
			$oList_Dir = $oList->List_Dir;

			do {
				$aReturn[] = $oList_Dir->name;
				$oList_Dir = $oList_Dir->getParent();
			} while ($oList_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп поля формы
	static public function getFormFieldDirName(Form_Field_Model $oForm_Field)
	{
		$aReturn = array();
		if ($oForm_Field->form_field_dir_id)
		{
			$oForm_Field_Dir = $oForm_Field->Form_Field_Dir;

			do {
				$aReturn[] = $oForm_Field_Dir->name;
				$oForm_Field_Dir = $oForm_Field_Dir->getParent();
			} while ($oForm_Field_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп табов
	static public function getShopTabDirName(Shop_Tab_Model $oShop_Tab)
	{
		$aReturn = array();
		if ($oShop_Tab->shop_tab_dir_id)
		{
			$oShop_Tab_Dir = $oShop_Tab->Shop_Tab_Dir;

			do {
				$aReturn[] = $oShop_Tab_Dir->name;
				$oShop_Tab_Dir = $oShop_Tab_Dir->getParent();
			} while ($oShop_Tab_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение групп пользовательских полей
	static public function getFieldDirName(Field_Model $oField)
	{
		$aReturn = array();
		if ($oField->field_dir_id)
		{
			$oField_Dir = $oField->Field_Dir;

			do {
				$aReturn[] = $oField_Dir->name;
				$oField_Dir = $oField_Dir->getParent();
			} while ($oField_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	// Получение меток ИС
	static public function getInformationsystemTags(Informationsystem_Item_Model $oInformationsystem_Item)
	{
		$aReturn = array();
		if ($oInformationsystem_Item->id)
		{
			$aTags = $oInformationsystem_Item->Tags->findAll(FALSE);

			foreach ($aTags as $oTag)
			{
				$aReturn[] = $oTag->name;
			}
		}

		return implode(',', $aReturn);
	}

	// Получение меток магазина
	static public function getShopTags(Shop_Item_Model $oShop_Item)
	{
		$aReturn = array();
		if ($oShop_Item->id)
		{
			$aTags = $oShop_Item->Tags->findAll(FALSE);

			foreach ($aTags as $oTag)
			{
				$aReturn[] = $oTag->name;
			}
		}

		return implode(',', $aReturn);
	}

	// Получение групп свойств товара
	static public function getPropertyDirName(Property_Model $oProperty)
	{
		$aReturn = array();
		if ($oProperty->property_dir_id)
		{
			$oProperty_Dir = $oProperty->Property_Dir;

			do {
				$aReturn[] = $oProperty_Dir->name;
				$oProperty_Dir = $oProperty_Dir->getParent();
			} while ($oProperty_Dir);

			$aReturn = array_reverse($aReturn);
		}

		return implode('/', $aReturn);
	}

	/**
	 * Массив id -> название XSL-шаблонов, используемых в макетах и ТДС
	 * @var array
	 */
	static public $_aXsls = array();

	/**
	 * Массив id -> название ТДС, используемых в структуре сайта
	 * @var array
	 */
	static protected $_aLibs = array();

	/**
	 * Массив внешних файлов
	 * @var array
	 */
	static protected $_aFiles = array();

	static public function getArrayOfFiles()
	{
		return self::$_aFiles;
	}

	/**
	 * Поиск использования JS/CSS файлов в переданном $content
	 * @param string $content
	 */
	static public function findFiles($content)
	{
		preg_match_all('/->(?:prependJs|js)\([\'\"](.*?)[\'\"]\)/mi', $content, $matches);
		if (isset($matches[1][0]))
		{
			foreach ($matches[1] as $sScript)
			{
				if (strpos($sScript, '/') === 0 && strpos($sScript, '//') === FALSE)
				{
					self::$_aFiles[] = Core_Str::ltrimUri($sScript);
				}
			}
		}

		preg_match_all('/\<script(?:.*?)src=\"(.*?)?(\?.*?)?\"\>\<\/script\>/mi', $content, $matches);
		if (isset($matches[1][0]))
		{
			foreach ($matches[1] as $sScript)
			{
				if (strpos($sScript, '/') === 0 && strpos($sScript, '//') === FALSE)
				{
					self::$_aFiles[] = Core_Str::ltrimUri($sScript);
				}
			}
		}

		preg_match_all('/->(?:prependCss|css)\([\'\"](.*?)[\'\"]\)/mi', $content, $matches);
		if (isset($matches[1][0]))
		{
			foreach ($matches[1] as $sCss)
			{
				if (strpos($sCss, '/') === 0 && strpos($sCss, '//') === FALSE)
				{
					self::$_aFiles[] = Core_Str::ltrimUri($sCss);
					self::findInCSS($sCss);
				}
			}
		}

		preg_match_all('/\<link(?:.*?)type=\"text\/css\"(?:.*?)href=\"(.*?)?(\?.*?)?\"(.*?)\/\>/mi', $content, $matches);
		if (isset($matches[1][0]))
		{
			foreach ($matches[1] as $sCss)
			{
				if (strpos($sCss, '/') === 0 && strpos($sCss, '//') === FALSE)
				{
					self::$_aFiles[] = Core_Str::ltrimUri($sCss);
					self::findInCSS($sCss);
				}
			}
		}
	}

	/**
	 * Поиск подключаемых файлов в коде самого CSS
	 */
	static public function findInCSS($sFileName)
	{
		if (is_file(CMS_FOLDER . $sFileName))
		{
			preg_match_all('/url\((.*?)?((\?|\#).*?)?\)/si', Core_File::read(CMS_FOLDER . $sFileName), $matches);
			if (isset($matches[1][0]))
			{
				foreach ($matches[1] as $sFile)
				{
					if (stripos($sFile, 'data:image') === FALSE)
					{
						$sFile = str_replace(array('"', "'"), array('', ''), $sFile);

						if (stripos($sFile, '/') !== 0)
						{
							$sFile = dirname($sFileName).DIRECTORY_SEPARATOR.$sFile;
						}
						self::$_aFiles[] = Core_Str::ltrimUri($sFile);
					}
				}
			}
		}
	}

	/**
	 * Поиск использования XSL-шаблонов в переданном $content
	 * @param string $content
	 */
	static protected function _findXsl($content)
	{
		preg_match_all('/Core_Entity\:\:factory\([\'\"]xsl[\'\"]\)\-\>getByName\([\'\"](.*?)[\'\"]\)/mi', $content, $matches);

		if (isset($matches[1]))
		{
			foreach ($matches[1] as $sXslName)
			{
				$oXsl = Core_Entity::factory('Xsl')->getByname($sXslName);

				if (!is_null($oXsl))
				{
					self::$_aXsls[$oXsl->id] = $sXslName;
				}
			}
		}
	}

	static public function setXsls()
	{
		$oSite = Core_Entity::factory('Site', Install::$iSiteId);

		$aTemplates = $oSite->Templates->findAll();
		foreach ($aTemplates as $oTemplate)
		{
			$sTemplate = $oTemplate->loadTemplateFile();
			self::_findXsl($sTemplate);

			$aSections = $oTemplate->Template_Sections->findAll(FALSE);
			foreach ($aSections as $oSection)
			{
				$aWidgets = $oSection->Template_Section_Libs->findAll(FALSE);
				foreach ($aWidgets as $oWidget)
				{
					$oLib = $oWidget->Lib;
					$aProperties = $oLib->Lib_Properties->getAllBytype(2);

					self::$_aLibs[$oLib->id] = $oLib->name;

					self::_findXsl($oLib->loadLibConfigFile());
					self::_findXsl($oLib->loadLibFile());

					$aOptions = strlen($oWidget->options)
						? json_decode($oWidget->options, TRUE)
						: array();

					foreach ($aProperties as $oProperty)
					{
						if (isset($aOptions[$oProperty->varible_name]) && trim($aOptions[$oProperty->varible_name]) != '')
						{
							$oXsl = Core_Entity::factory('xsl')->getByname($aOptions[$oProperty->varible_name]);
							if (!is_null($oXsl))
							{
								self::$_aXsls[$oXsl->id] = $oXsl->name;
							}
						}
					}
				}
			}
		}

		$aStructures = $oSite->Structures->getAllByType(2);
		foreach ($aStructures as $oStructure)
		{
			$oLib = $oStructure->Lib;

			self::$_aLibs[$oLib->id] = $oLib->name;

			self::_findXsl($oLib->loadLibConfigFile());
			self::_findXsl($oLib->loadLibFile());

			$aDat = $oLib->getDat($oStructure->id);

			$aProperties = $oLib->Lib_Properties->getAllBytype(2);
			foreach ($aProperties as $oProperty)
			{
				if (isset($aDat[$oProperty->varible_name]) && trim($aDat[$oProperty->varible_name]) != '')
				{
					$oXsl = Core_Entity::factory('xsl')->getByname($aDat[$oProperty->varible_name]);
					if (!is_null($oXsl))
					{
						self::$_aXsls[$oXsl->id] = $oXsl->name;
					}
				}
			}
		}

		self::_showXslDir($parent_id = 0);
	}

	static protected function _showXslDir($parent_id = 0)
	{
		self::_showXsls($parent_id);

		$oXsl_Dirs = Core_Entity::factory('Xsl_Dir');
		$oXsl_Dirs->queryBuilder()
			->where('xsl_dirs.parent_id', '=', $parent_id)
			->clearOrderBy()
			->orderBy('xsl_dirs.sorting', 'ASC')
			->orderBy('xsl_dirs.id', 'DESC');

		$aXsl_Dirs = $oXsl_Dirs->findAll(FALSE);
		foreach ($aXsl_Dirs as $oXsl_Dir)
		{
			?><div class="dir-block" id="xsl-dir-<?php echo $oXsl_Dir->id?>">
				<div class="pull-left margin-right-10"><?php echo htmlspecialchars($oXsl_Dir->name)?></div>
				<div class="checkbox">
					<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
				</div>
				<?php
				self::_showXslDir($oXsl_Dir->id);
			?></div><?php
		}
	}

	static protected function _showXsls($xsl_dir_id)
	{
		?><div><?php
		$oXsls = Core_Entity::factory('Xsl');
		$oXsls
			->queryBuilder()
			->where('xsls.xsl_dir_id', '=', $xsl_dir_id)
			->clearOrderBy()
			->orderBy('xsls.sorting', 'ASC')
			->orderBy('xsls.id', 'DESC');

		$aXsls = $oXsls->findAll(FALSE);
		foreach ($aXsls as $oXsl)
		{
			$checked = Core_Array::getPost('xsl_' . $oXsl->id) == $oXsl->id || isset(self::$_aXsls[$oXsl->id])
				? 'checked="checked"'
				: '';

			$translate = array_key_exists($oXsl->name, Install::$i18n)
				? '<span class="label label-success">Есть перевод</span>'
				: '<span class="label label-warning">Перевод осутствует</span>';
			?><div class="checkbox">
				<label>
					<input type="checkbox" name="xsl_<?php echo $oXsl->id?>" value="<?php echo $oXsl->id?>" <?php echo $checked?>/> <?php echo htmlspecialchars($oXsl->name)?> <span class="label label-default"><?php echo $oXsl->id?></span> <?php echo $translate?>
				</label>
			</div>
			<?php
		}
		?></div><?php
	}

	// Заполнение списка типовых динамических страниц
	static public function setLibs()
	{
		self::_showLibDir($parent_id = 0);
	}

	static protected function _showLibDir($parent_id = 0)
	{
		self::_showLibs($parent_id);

		$oLib_Dirs = Core_Entity::factory('Lib_Dir');
		$oLib_Dirs->queryBuilder()
			->where('lib_dirs.parent_id', '=', $parent_id)
			->clearOrderBy()
			->orderBy('lib_dirs.id', 'DESC');

		$aLib_Dirs = $oLib_Dirs->findAll(FALSE);
		foreach ($aLib_Dirs as $oLib_Dir)
		{
			?><div class="dir-block" id="lib-dir-<?php echo $oLib_Dir->id?>">
				<div class="pull-left margin-right-10"><?php echo htmlspecialchars($oLib_Dir->name)?></div>
				<div class="checkbox">
					<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
				</div>
				<?php
				self::_showLibDir($oLib_Dir->id);
			?></div><?php
		}
	}

	static protected function _showLibs($lib_dir_id)
	{
		?><div><?php
		$oLibs = Core_Entity::factory('Lib');
		$oLibs
			->queryBuilder()
			->where('libs.lib_dir_id', '=', $lib_dir_id)
			->clearOrderBy()
			->orderBy('libs.id', 'DESC');

		$_aLibs = $oLibs->findAll(FALSE);
		foreach ($_aLibs as $oLib)
		{
			$checked = Core_Array::getPost('lib_' . $oLib->id) == $oLib->id || isset(self::$_aLibs[$oLib->id])
				? 'checked="checked"'
				: '';

			$translate = array_key_exists($oLib->name, Install::$i18n)
				? '<span class="label label-success">Есть перевод</span>'
				: '<span class="label label-warning">Перевод осутствует</span>';
			?>

			<div class="checkbox">
				<label>
					<input type="checkbox" name="lib_<?php echo $oLib->id?>" value="<?php echo $oLib->id?>" <?php echo $checked?>/> <?php echo htmlspecialchars($oLib->name)?> <span class="label label-default"><?php echo $oLib->id?></span> <?php echo $translate?>
				</label>
			</div>
			<?php
		}
		?></div><?php
	}

	// Заполнение списка TPL-шаблонов
	static public function setTpls()
	{
		self::_showTplDir($parent_id = 0);
	}

	static protected function _showTplDir($parent_id = 0)
	{
		self::_showTpls($parent_id);

		$oTpl_Dirs = Core_Entity::factory('Tpl_Dir');
		$oTpl_Dirs->queryBuilder()
			->where('tpl_dirs.parent_id', '=', $parent_id)
			->clearOrderBy()
			->orderBy('tpl_dirs.sorting', 'ASC')
			->orderBy('tpl_dirs.id', 'DESC');

		$aTpl_Dirs = $oTpl_Dirs->findAll(FALSE);

		foreach ($aTpl_Dirs as $oTpl_Dir)
		{
			?><div class="dir-block" id="tpl-dir-<?php echo $oTpl_Dir->id?>">

				<div class="pull-left margin-right-10"><?php echo htmlspecialchars($oTpl_Dir->name)?></div>
				<div class="checkbox">
					<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
				</div>

				<?php
				self::_showTplDir($oTpl_Dir->id);
				?>
			</div><?php
		}
	}

	static protected function _showTpls($tpl_dir_id)
	{
		?><div><?php
		$oTpls = Core_Entity::factory('Tpl');
		$oTpls
			->queryBuilder()
			->where('tpls.tpl_dir_id', '=', $tpl_dir_id)
			->clearOrderBy()
			->orderBy('tpls.sorting', 'ASC')
			->orderBy('tpls.id', 'DESC');

		$aTpls = $oTpls->findAll(FALSE);
		foreach ($aTpls as $oTpl)
		{
			$checked = Core_Array::getPost('tpl_' . $oTpl->id) == $oTpl->id
				? 'checked="checked"'
				: '';

			$translate = array_key_exists($oTpl->name, Install::$i18n)
				? '<span class="label label-success">Есть перевод</span>'
				: '<span class="label label-warning">Перевод осутствует</span>';
			?>
			<div class="checkbox">
				<label>
					<input type="checkbox" name="tpl_<?php echo $oTpl->id?>" value="<?php echo $oTpl->id?>" <?php echo $checked?>/> <?php echo htmlspecialchars($oTpl->name)?> <span class="label label-default"><?php echo $oTpl->id?></span> <?php echo $translate?>
				</label>
			</div>
			<?php
		}
		?></div><?php
	}

	// Заполнение списка платежных систем
	static public function setPaymentSystems()
	{
		self::_showPaymentSystem();
	}

	static protected function _showPaymentSystem()
	{
		$aShops = Core_Entity::factory('Shop')->getAllBySite_id(Install::$iSiteId);

		foreach ($aShops as $oShop)
		{
			$aShop_Payment_Systems = $oShop->Shop_Payment_Systems->findAll(FALSE);

			if (count($aShop_Payment_Systems))
			{
				?><div class="dir-block" id="shop-<?php echo $oShop->id?>">
					<div class="pull-left margin-right-10"><?php echo htmlspecialchars($oShop->name)?></div>
					<div class="checkbox">
						<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
					</div>
					<div>
						<?php


						foreach ($aShop_Payment_Systems as $oShop_Payment_System)
						{
							$checked = Core_Array::getPost('payment_system_' . $oShop_Payment_System->id) == $oShop_Payment_System->id
								? 'checked="checked"'
								: '';
							?>
							<div class="checkbox">
								<label>
									<input type="checkbox" name="payment_system_<?php echo $oShop_Payment_System->id?>" value="<?php echo $oShop_Payment_System->id?>" <?php echo $checked?>/> <?php echo htmlspecialchars($oShop_Payment_System->name)?> <span class="label label-default"><?php echo $oShop_Payment_System->id?></span>
								</label>
							</div>
							<?php
						}
						?>
					</div>
				</div><?php
			}
		}
	}

	// Заполнение списка констант
	static public function setConstants()
	{
		self::_showConstantDir(0);
	}

	static protected function _showConstantDir($parent_id = 0)
	{
		self::_showConstants($parent_id);

		$oConstant_Dirs = Core_Entity::factory('Constant_Dir');
		$oConstant_Dirs->queryBuilder()
			->where('constant_dirs.parent_id', '=', $parent_id)
			->clearOrderBy()
			->orderBy('constant_dirs.id', 'DESC');

		$aConstant_Dirs = $oConstant_Dirs->findAll(FALSE);

		foreach ($aConstant_Dirs as $oConstant_Dir)
		{
			?><div class="dir-block" id="constant-dir-<?php echo $oConstant_Dir->id?>">

				<div class="pull-left margin-right-10"><?php echo htmlspecialchars($oConstant_Dir->name)?></div>
				<div class="checkbox">
					<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
				</div>

				<?php
				self::_showConstantDir($oConstant_Dir->id);
				?>
			</div><?php
		}
	}

	static protected function _showConstants($constant_dir_id)
	{
		?><div><?php
		$oConstants = Core_Entity::factory('Constant');
		$oConstants
			->queryBuilder()
			->where('constants.id', '>', 36)
			->where('constants.constant_dir_id', '=', $constant_dir_id)
			->clearOrderBy()
			->orderBy('constants.id', 'DESC');

		$aConstants = $oConstants->findAll(FALSE);
		foreach ($aConstants as $oConstant)
		{
			$checked = Core_Array::getPost('constant_' . $oConstant->id) == $oConstant->id
				? 'checked="checked"'
				: '';
			?>
			<div class="checkbox">
				<label>
					<input type="checkbox" name="constant_<?php echo $oConstant->id?>" value="<?php echo $oConstant->id?>" <?php echo $checked?>/> <?php echo htmlspecialchars($oConstant->name)?> <span class="label label-default"><?php echo $oConstant->id?></span>
				</label>
			</div>
			<?php
		}
		?></div><?php
	}

	static public function fillStructures($iSiteId, $tmpDir, $iParentId = 0)
	{
		$iSiteId = intval($iSiteId);
		$iParentId = intval($iParentId);

		$content = '';

		$oStructure = Core_Entity::factory('Structure', $iParentId);

		$aChildren = $oStructure->Structures->getBySiteId($iSiteId);

		if (count($aChildren))
		{
			foreach ($aChildren as $oStructure)
			{
				$content .= "		{$oStructure->id} => array(" . "\n" .
				"			'name' => '" . addslashesapostrophe($oStructure->name) . "'," . "\n" .
				"			'path' => '" . addslashesapostrophe($oStructure->path) . "'," . "\n" .
				"			'url' => '" . addslashesapostrophe($oStructure->url) . "'," . "\n" .
				"			'parent_id' => " . $oStructure->parent_id . ", " . "\n" .
				"			'site_id' => " . $oStructure->site_id . ", " . "\n" .
				"			'structure_menu_id' => " . $oStructure->structure_menu_id . ", " . "\n" .
				"			'template_id' => " . $oStructure->template_id . ", " . "\n" .
				"			'siteuser_group_id' => " . $oStructure->siteuser_group_id . ", " . "\n" .
				"			'show' => " . $oStructure->show . ", " . "\n" .
				"			'active' => " . $oStructure->active . ", " . "\n" .
				"			'indexing' => " . $oStructure->indexing . ", " . "\n" .
				"			'sorting' => " . $oStructure->sorting . ", " . "\n" .
				"			'type' => '" . $oStructure->type . "'," . "\n" .
				"			'seo_title' => '" . addslashesapostrophe($oStructure->seo_title) . "'," . "\n" .
				"			'seo_description' => '" . addslashesapostrophe($oStructure->seo_description) . "'," . "\n" .
				"			'options' => '" . addslashesapostrophe($oStructure->options) . "'," . "\n" .
				"			'seo_keywords' => '" . addslashesapostrophe($oStructure->seo_keywords) . "'," . "\n";

				if ($oStructure->document_id)
				{
					$content .= "			'document_id' => " . $oStructure->document_id . ", " . "\n";
				}

				if ($oStructure->lib_id)
				{
					$content .= "			'lib_id' => " . $oStructure->lib_id . ", " . "\n";
				}

				$content .= "			'property_values' => array(" . "\n";

				$aPropertyValues = $oStructure->getPropertyValues();
				foreach ($aPropertyValues as $oPropertyValue)
				{
					if ($oPropertyValue->Property->type != 2)
					{
						$content .= "				{$oPropertyValue->id} => array(" . "\n" .
						"					'property_id' => " . $oPropertyValue->Property->id . ", " . "\n" .
						"					'value' => '" . addslashesapostrophe($oPropertyValue->value) . "'," . "\n" .
						"				)," . "\n";
					}
					else
					{
						$content .= "				// File" . "\n" .
						"				{$oPropertyValue->id} => array(" . "\n" .
						"					'property_id' => " . $oPropertyValue->Property->id . ", " . "\n" .
						"					'file' => '" . addslashesapostrophe($oPropertyValue->file) . "', " . "\n" .
						"					'file_small' => '" . addslashesapostrophe($oPropertyValue->file_small) . "', " . "\n" .
						"				)," . "\n";

						if (strlen($oPropertyValue->file_small))
						{
							$sTmpPath = $oPropertyValue->getSmallFilePath();

							if (is_file($sTmpPath))
							{
								Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getSmallFileHref());
							}
						}

						if (strlen($oPropertyValue->file))
						{
							$sTmpPath = $oPropertyValue->getLargeFilePath();

							if (is_file($sTmpPath))
							{
								Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getLargeFileHref());
							}
						}
					}
				}

				$content .= "			)," . "\n";

				$content .= Install::exportFieldValues('structure', $oStructure, $tmpDir);

				$content .= "		),\n";

				if ($oStructure->type == 1)
				{
					if (is_file($oStructure->getStructureFilePath()))
					{
						Core_File::copy($oStructure->getStructureFilePath(), $tmpDir . 'hostcmsfiles/structure/Structure' . $oStructure->id . '.php');
					}
					if (is_file($oStructure->getStructureConfigFilePath()))
					{
						Core_File::copy($oStructure->getStructureConfigFilePath(), $tmpDir . 'hostcmsfiles/structure/StructureConfig' . $oStructure->id . '.php');
					}
				}

				$content .= self::fillStructures($iSiteId, $tmpDir, $oStructure->id);
			}
		}

		return $content;
	}

	static public function exportFields()
	{
		if (Core::moduleIsActive('field') && count(self::$aFieldIDs))
		{
			$content = '';

			foreach (self::$aFieldIDs as $id)
			{
				$oField = Core_Entity::factory('Field')->getById($id);

				if (!is_null($oField))
				{
					$content .= "	{$oField->id} => array(" . "\n" .
					"		'name' => '" . addslashesapostrophe($oField->name) . "'," . "\n" .
					"		'dirName' => '" . Install::getFieldDirName($oField) . "'," . "\n" .
					"		'model' => '" . addslashesapostrophe($oField->model) . "'," . "\n" .
					"		'site_id' => " . $oField->site_id . ", " . "\n" .
					"		'list_id' => " . $oField->list_id . ", " . "\n" .
					"		'informationsystem_id' => " . $oField->informationsystem_id . ", " . "\n" .
					"		'shop_id' => " . $oField->shop_id . ", " . "\n" .
					"		'default_value' => '" . addslashesapostrophe($oField->default_value) . "', " . "\n" .
					"		'tag_name' => '" . addslashesapostrophe($oField->tag_name) . "', " . "\n" .
					"		'description' => '" . addslashesapostrophe($oField->description) . "', " . "\n" .
					"		'type' => " . $oField->type . ", " . "\n" .
					"		'sorting' => " . $oField->sorting . ", " . "\n" .
					"		'visible' => " . $oField->visible . ", " . "\n" .
					"		'image_large_max_width' => " . $oField->image_large_max_width . ", " . "\n" .
					"		'image_large_max_height' => " . $oField->image_large_max_height . ", " . "\n" .
					"		'image_small_max_width' => " . $oField->image_small_max_width . ", " . "\n" .
					"		'image_small_max_height' => " . $oField->image_small_max_height . ", " . "\n" .
					"		'hide_small_image' => " . $oField->hide_small_image . ", " . "\n" .
					"		'preserve_aspect_ratio' => " . $oField->preserve_aspect_ratio . ", " . "\n" .
					"		'preserve_aspect_ratio_small' => " . $oField->preserve_aspect_ratio_small . ", " . "\n" .
					"		'change_filename' => " . $oField->change_filename . ", " . "\n" .
					"		'multiple' => " . $oField->multiple . ", " . "\n" .
					"		'obligatory' => " . $oField->obligatory . ", " . "\n" .
					"	)," . "\n";
				}
			}

			return $content;
		}

		return '';
	}

	static public $aFieldIDs = array();

	static public function exportFieldValues($model, $oObject, $tmpDir)
	{
		if (Core::moduleIsActive('field'))
		{
			// $tmpDir = Market_Controller::instance()->tmpDir . DIRECTORY_SEPARATOR;

			$content = '';

			$aFields = Core_Entity::factory('Field')->getAllByModel($model);
			foreach ($aFields as $oField)
			{
				!in_array($oField->id, self::$aFieldIDs) && self::$aFieldIDs[] = $oField->id;

				$aField_Values = $oField->getValues($oObject->id, FALSE);

				if (count($aField_Values))
				{
					$content .= "				'field_values' => array(" . "\n";

					foreach ($aField_Values as $oField_Value)
					{
						if ($oField->type != 2)
						{
							$content .= "					{$oField_Value->id} => array(" . "\n" .
							"						'type' => " . $oField->type . "," . "\n" .
							"						'field_id' => " . $oField_Value->field_id . "," . "\n" .
							"						'entity_id' => " . $oField_Value->entity_id . "," . "\n" .
							"						'value' => '" . addslashesapostrophe($oField_Value->value) . "'," . "\n" .
							"					)," . "\n";
						}
						else
						{
							$content .= "					// File" . "\n" .
							"					{$oField_Value->id} => array(" . "\n" .
							"						'type' => " . $oField->type . ", " . "\n" .
							"						'field_id' => " . $oField_Value->field_id . ", " . "\n" .
							"						'entity_id' => '" . $oField_Value->entity_id . "'," . "\n" .
							"						'file' => '" . addslashesapostrophe($oField_Value->file) . "'," . "\n" .
							"						'file_name' => '" . addslashesapostrophe($oField_Value->file_name) . "'," . "\n" .
							"						'file_description' => '" . addslashesapostrophe($oField_Value->file_description) . "'," . "\n" .
							"						'file_small' => '" . addslashesapostrophe($oField_Value->file_small) . "'," . "\n" .
							"						'file_small_name' => '" . addslashesapostrophe($oField_Value->file_small_name) . "'," . "\n" .
							"						'file_small_description' => '" . addslashesapostrophe($oField_Value->file_small_description) . "'," . "\n" .
							"					)," . "\n";

							$sPath = CMS_FOLDER . Field_Controller::getPath($oObject);
							$oField_Value->setDir($sPath);

							$dir = $tmpDir . 'upload/fields/';

							if (strlen($oField_Value->file_small))
							{
								$sTmpPath = $oField_Value->getSmallFilePath();

								if (is_file($sTmpPath))
								{
									Core_File::mkdir($dir, CHMOD, TRUE);
									Core_File::copy($sTmpPath, $dir . $oField_Value->getSmallFileHref());
								}
							}

							if (strlen($oField_Value->file))
							{
								$sTmpPath = $oField_Value->getLargeFilePath();

								if (is_file($sTmpPath))
								{
									Core_File::mkdir($dir, CHMOD, TRUE);
									Core_File::copy($sTmpPath, $dir . $oField_Value->getLargeFileHref());
								}
							}
						}
					}

					$content .= "				)," . "\n";
				}
			}

			return $content;
		}

		return '';
	}
}

Install::$aLngs = array('ru', 'en');

Install::$i18n = array(
	'Сайт%d' => 'Site%d',

	// XSL-шаблоны
	'ВерхнееМеню' => 'TopMenu',
	'НижнееМеню' => 'BottomMenu',
	'ПравоеМеню' => 'RightMenu',
	'ВтороеВерхнееМеню' => 'SecondTopMenu',
	'СписокЭлементовИнфосистемы' => 'InformationsystemItemsList',
	'ВыводЕдиницыИнформационнойСистемы' => 'InformationsystemItem',
	'УведомлениеДобавлениеКомментария' => 'AddCommentNotification',
	'ОтправкаПисьмаАдминистраторуДобавлениеКомментария' => 'AddCommentAdminSendMail',
	'ОблакоТэговИнформационнойСистемы' => 'InformationsystemTagsCloud',
	'СписокНовостейНаГлавной' => 'NewsListMainPage',
	'ОтображениеВопроса' => 'ShowQuestion',
	'СписокВопросов' => 'QuestionsList',
	'УведомлениеДобавленияОтвета' => 'AddQuestionNotification',
	'СписокЗаписейГостевойКниги' => 'GuestbookItemsList',
	'СписокКартинок' => 'PicturesList',
	'ОтображениеПодробнойИнформацииОФотографии' => 'PictureItem',
	'СписокУслугНаГлавной' => 'ServicesListMainPage',
	'СписокУслуг' => 'ServicesList',
	'ВыводУслуги' => 'ShowService',
	'СписокСсылок' => 'LinksList',
	'ВыводПодробнойИнформацииОСсылке' => 'ShowLink',
	'СписокФайлов' => 'FilesList',
	'ПодробнаяИнформацияОФайле' => 'ShowFile',
	'Поиск' => 'Search',
	'ОтобразитьФорму' => 'ShowForm',
	'ПисьмоКураторуФормы' => 'FormAdminMail',
	'ПисьмоКураторуФормыВФорматеHTML' => 'FormAdminMailHTML',
	'СписокРассылок' => 'MaillistsList',
	'ПополнениеЛицевогоСчетаРеквизиты' => 'DepositAccountProps',
	'ПополнениеЛицевогоСчетаПлатежныеСистемы' => 'DepositAccountPaymentsystems',
	'СписокЛицевыхСчетов' => 'AccountsList',
	'ДвиженияПоЛицевомуСчету' => 'AccountTransactionsList',
	'ЛичныеСообщения' => 'Messages',
	'ЛентаЛичныхСообщений' => 'MessagesList',
	'ЛичныйКабинетПользователя' => 'UserAccount',
	'РегистрацияПользователя' => 'UserRegistration',
	'ПисьмоВосстановлениеПароля' => 'RestorePasswordMail',
	'ПисьмоПодтверждениеРегистрации' => 'AcceptRegistrationMail',
	'АнкетныеДанные' => 'UserInfo',
	'ПарнерскиеПрограммы' => 'UserAffiliates',
	'ВыводСпискаОбъявленийПользователя' => 'BoardItemShowList',
	'ФормаРедактированияОбъявленияПользователя' => 'BoardItemEditForm',
	'ВыводБонусов' => 'ShowBonuses',
	'КодПриглашения' => 'InvitationCode',
	'ПочтовыеРассылки' => 'Maillists',
	'ОтображениеОпросаБезРезультатов' => 'ShowPollsWithoutResults',
	'ОтображениеРезультатовОпроса' => 'ShowPollResults',
	'СписокОбъявлений' => 'BoardItemList',
	'ПодробнаяИнформацияОбОбъявлении' => 'BoardItemPage',
	'ПисьмоОДобавленииСообщения' => 'MailAddMessage',
	'ПисьмоОДобавленииТемы' => 'MailAddTheme',
	'ПисьмоРедактированияСообщенияПользователю' => 'MailEditMessageToUser',
	'ПисьмоДобавленияСообщенияПользователю' => 'MailAddMessageToUser',
	'ПисьмоРедактированияСообщенияКуратору' => 'MailEditMessageToAdmin',
	'КартаСайта' => 'Sitemap',
	'ЭлементПортфолио' => 'PortfolioItem',
	'СписокЭлементовПортфолио' => 'PortfolioItemsList',
	'СписокЭлементовГлоссарий' => 'GlossaryItemsList',
	'СписокВакансий' => 'VacancyItemsList',
	'ОтображениеБаннера' => 'ShowBanner',
	'ХлебныеКрошки' => 'Breadcrumbs',
	'GoogleSiteMap' => 'GoogleSitemap',
	'ВыводСпискаТикетов' => 'ShowTicketsList',
	'ВыводСпискаСообщенийТикета' => 'ShowTicketMessagesList',
	'ВыводРежимаРаботыСлужбыТехподдержки' => 'HelpdeskWorktime',
	'ОплатаПриПолучении' => 'PayCash',
	'КвитанцияПД4' => 'RusPD4',
	'ОплатаПоФормеПД4' => 'RusPD4Form',
	'ОплатаБезналичнаяОтЮрЛица' => 'BankPayment',
	'БанковскийСчет' => 'Invoice',
	'ОплатаПочтовымПереводом' => 'PostalTransfer',
	'Форма112ф' => 'Rus112fForm',
	'ПисьмоАдминистраторуОДобавленииКомментарияВТекстовомФормате' => 'AddCommentAdminSendMailTXT',
	'ПисьмоАдминистраторуОДобавленииКомментарияВФорматеHTML' => 'AddCommentAdminSendMailHTML',
	'МагазинКаталогТоваров' => 'ShopItemsList',
	'МагазинТовар' => 'ShopItem',
	'МагазинКорзина' => 'ShopCart',
	'МагазинБыстраяРегистрация' => 'ShopFastRegistration',
	'МагазинАдресДоставки' => 'ShopAddress',
	'МагазинДоставки' => 'ShopDelivery',
	'МагазинПлатежнаяСистема' => 'ShopPaymentsystem',
	'ОформлениеЗаказа' => 'ProcessOrder',
	'МагазинСписокПродавцов' => 'ShopSellersList',
	'МагазинПродавец' => 'ShopSeller',
	'СравнениеТоваров' => 'CompareItems',
	'СписокЗаказов' => 'OrdersList',
	'ПисьмоАдминистратору' => 'AdminMail',
	'ПисьмоПользователю' => 'UserMail',
	'МагазинКорзинаКраткая' => 'ShortShopCart',
	'МагазинПрайс' => 'ShopPrice',
	'МагазинКаталогТоваровНаГлавнойСпецПред' => 'ShopItemsMainPageDiscount',
	'ОблакоТэговМагазин' => 'ShopTagsCloud',
	'МагазинГруппыТоваровНаГлавной' => 'ShopGroupsMainPage',
	'МагазинСписокПроизводителей' => 'ShopProducersList',
	'МагазинПроизводитель' => 'ShopProducer',
	'ИзбранноеНаГлавной' => 'FavoriteMainPage',
	'МагазинФильтр' => 'ShopFilter',
	'МагазинПоследнийЗаказ' => 'ShopLastOrder',
	'МагазинКарточкаЗаказа' => 'ShopOrder',
	'МагазинИзбранное' => 'ShopFavorite',
	'МагазинИзбранноеКраткое' => 'ShopFavoriteShort',
	'НижнееМенюОсновное' => 'BottomMenuMain',
	'ВерхнееМенюОсновное' => 'TopMenuMain',
	'ЛевоеМенюКабинет' => 'LeftMenuSiteuserAccount',
	'ИнформацияОПользователе' => 'SiteuserInfo',
	'МагазинСписокПроизводителейНаГлавной' => 'ShopProducersListMainPage',
	'МагазинКаталогТоваровГлавная' => 'ShopItemsMain',
	'МагазинГруппыТоваровМеню' => 'ShopGroupsMenu',
	'МагазинТоварыНаГлавнойНовинки' => 'ShopItemsMainNew',
	'МагазинТоварыНаГлавнойСкидки' => 'ShopItemsMainDiscount',
	'МагазинКраткаяКорзина' => 'ShopShortCart',
	'МагазинГруппыТоваровФильтр' => 'ShopItemsFilter',
	'МагазинСписокПроизводителейФильтр' => 'ShopProducersListFilter',
	'КаталогТоваров' => 'Shop',
	'МагазинКупитьВОдинШаг' => 'ShopOnestep',
	'Товар' => 'ShopItem',
	'БрошеннаяКорзина' => 'AbandonedCart',
	'МагазинНовинки' => 'ShopNewItems',
	'СообщенияПользователя' => 'SiteuserMessages',
	'АнкетныеДанныеПользователя' => 'SiteuserInfoData',
	'РедактированиеСообщения' => 'EditMessage',
	'СозданиеТемы' => 'AddTheme',
	'СообщенияТемы' => 'ThemeMessages',
	'ТемыФорума' => 'ForumThemes',
	'Форумы' => 'Forums',
	'МенюПроизводители' => 'ShopProducersMenu',

	// ТДС
	'Google SiteMap' => 'Google SiteMap',
	'Доска объявлений' => 'Board',
	'Почтовые рассылки' => 'Maillists',
	'Форум' => 'Forum',
	'Опросы' => 'Polls',
	'Личные сообщения' => 'Private Messages',
	'Бонусы' => 'Bonuses',
	'Структура приглашенных' => 'Affiliate structure',
	'Партнерские программы' => 'Partnership programs',
	'Мои объявления' => 'My advertisements',
	'Аффилиаты' => 'Affiliates',
	'Пополнение лицевого счета пользователя' => 'Refill siteuser account',
	'Лицевой счет' => 'Siteuser account',
	'Информация о пользователе' => 'Siteuser info',
	'Почтовые рассылки' => 'Siteuser maillists',
	'Восстановление пароля' => 'Restore password',
	'Заказы' => 'Siteuser orders',
	'Регистрация' => 'Registration',
	'Пользователи сайта' => 'Siteusers',
	'Информационная система для глоссария' => 'Glossary information system',
	'Информационная система для Вопросы-ответы, Гостевая книга и т.п.' => 'FAQ information system',
	'Информационная система' => 'Information system',
	'Отображение формы' => 'Show form',
	'Импорт RSS-каналов' => 'RSS import',
	'RSS канал для информационной системы' => 'Information system RSS',
	'Поиск' => 'Search',
	'Переход по ссылке баннера (JavaScript)' => 'Following a banner link (JavaScript)',
	'Переход по ссылке баннера' => 'Following a banner link',
	'Карта сайта' => 'Map',
	'Интернет-магазин избранное' => 'Shop favorite',
	'Экспорт в VendorYML' => 'Yandex.VendorYML export',
	'Экспорт в Яндекс.Недвижимость' => 'Yandex.Realty export',
	'Производители' => 'Producers',
	'Обмен с 1С:Управление торговлей' => '1C exchange',
	'Экспорт в Яндекс.Маркет' => 'Yandex.Market export',
	'Прайс' => 'Price',
	'Сравнение товаров' => 'Compare Goods',
	'Продавцы' => 'Sellers',
	'Версия для печати' => 'Print version',
	'Интернет-магазин корзина' => 'Shop cart',
	'Интернет-магазин' => 'Shop',
	'Комментарии магазина' => 'Shop comments',
	'Служба техподдержки' => 'Helpdesk',
	'Интернет-магазин Избранное' => 'Shop Favorite',

	// ТДС виджеты
	'Виджет::Блок социальных сетей' => 'Widget::Social networks block',
	'Виджет::Нижнее меню' => 'Widget::Bottom menu',
	'Виджет::Контактная информация' => 'Widget::Contacts',
	'Виджет::Копирайт' => 'Widget::Copyright',
	'Виджет::Счетчик' => 'Widget::Counter',
	'Виджет::Меню групп товаров на главной' => 'Widget::Shop groups om main page',
	'Виджет::Фильтр товаров' => 'Widget::Shop items filter',
	'Виджет::Производители' => 'Widget::Producers',
	'Виджет::Последний заказ' => 'Widget::Last order',
	'Виджет::Облако меток магазина' => 'Widget::Shop tags cloud',
	'Виджет::Баннер' => 'Widget::Banner',
	'Виджет::Опрос' => 'Widget::Poll',
	'Виджет::HTML-код' => 'Widget::Html',
	'Виджет::Облако меток ИС' => 'Widget::Information system tags cloud',
	'Виджет::Слайдер Slippry' => 'Widget::Slippry slider',
	'Виджет::Контент страницы' => 'Widget::Page contents',
	'Виджет::Горячие предложения (товары со скидкой)' => 'Widget::Shop items with discount',
	'Виджет::Показ информационной системы' => 'Widget::Show information system',
	'Виджет::Новинки' => 'Widget::New',
	'Виджет::Быстрый доступ' => 'Widget::Quick access',
	'Виджет:: Основное меню' => 'Widget::Main menu',
	'Виджет::Логотип' => 'Widget::Logo',
	'Виджет::Поиск' => 'Widget::Search',
	'Виджет::Краткая корзина' => 'Widget::Shop short cart',
	'Виджет::Хлебные крошки' => 'Widget::Breadcrumbs',

	// Структура сайта
	'Главная' => 'Main page',
	'Услуги' => 'Services',
	'Интернет-магазин' => 'Shop',
	'Обмен с 1C' => '1C',
	'Корзина' => 'Shop cart',
	'Версия для печати' => 'Print',
	'Прайс-лист' => 'Price',
	'Сравнение товаров' => 'Compare',
	'Производители' => 'Producers',
	'Продавцы' => 'Sellers',
	'Статьи' => 'Articles',
	'RSS' => 'RSS',
	'Новости' => 'News',
	'Импорт новостей' => 'News import',
	'Форум' => 'Forum',
	'Фотогалерея' => 'Photogallery',
	'Гостевая книга' => 'Guestbook',
	'Доска объявлений' => 'Board',
	'Обратная связь' => 'Feedback',
	'Опросы' => 'Polls',
	'Почтовые рассылки' => 'Maillists',
	'Контактные данные' => 'Contacts',
	'Карта сайта' => 'Sitemap',
	'Поиск' => 'Search',
	'Google SiteMap' => 'Google SiteMap',
	'Личный кабинет' => 'Account',
	'Служба поддержки' => 'Helpdesk',
	'Заказы' => 'Orders',
	'Ошибка 403' => 'Error 403',
	'Ошибка 404' => 'Error 404',
	'Сайт временно недоступен' => 'Error 503',
	'Демонстрационный магазин' => 'Demo Shop',
	'Демонстрационная служба' => 'Demo Helpdesk',
	'Конференция' => 'Conference',
	'Верхнее Меню' => 'Top Menu',
	'Левое Меню' => 'Left Menu',
	'Нижнее Меню' => 'Bottom Menu',

	// TPL-шаблоны
	'ПоказИнформационнойСистемы' => 'ShowInformationsystem',
	'ПоказЭлементаИнформационнойСистемы' => 'ShowInformationsystemItem',
	'КаталогТоваров' => 'ShopItems',
	'Товар' => 'ShopItem',
	'КраткаяКорзина' => 'ShopLittleCart',
);


// Создание шаблона
if (Core_Array::getPost('apply') && Core_Array::getPost('step_2'))
{
	// Массив сообщений
	$aMessages = array();

	// Константа для результата
	$isReady = 0;

	// Выбран сайт из списка
	$iSiteId = intval(Core_Array::getPost('site_id'));
	if ($iSiteId)
	{
		$oOldSite = Core_Entity::factory('Site', $iSiteId);

		if (!strlen($oOldSite->lng))
		{
			$aMessages[] = array('type' => 'danger', 'text' => "Отредактируйте сайт и укажите язык, для русского указывается ru!");
		}

		Core::initConstants($oOldSite);

		$templateDir = CMS_FOLDER . 'create_template/site_' . $oOldSite->id . '/';

		// Создаем директорию для файла
		Core_File::mkdir($templateDir, CHMOD, TRUE);

		// Создаем директорию files
		$filesDir = $templateDir . 'files/';
		Core_File::mkdir($filesDir, CHMOD, TRUE);

		// Создаем директорию tmp
		$tmpDir = $templateDir . 'tmp/';
		Core_File::mkdir($tmpDir, CHMOD, TRUE);

		$aSubdirs = array(
			'hostcmsfiles/xsl/',
			'hostcmsfiles/lib/',
			'hostcmsfiles/documents/',
			'templates/',
			'upload/',
		);

		foreach ($aSubdirs as $sSubdir)
		{
			Core_File::mkdir($tmpDir . $sSubdir, CHMOD, TRUE);
		}

		$filename = 'module.php';
		$filename_xml = 'module.xml';

		$sTmpLng = implode("','", Install::$aLngs);

		$content = '<?php
$tmpDir = Market_Controller::instance()->tmpDir . DIRECTORY_SEPARATOR;

$aOptions = Market_Controller::instance()->options;

$aLngs = array(';

$content .= "'{$sTmpLng}'";

$content .= ');

class CT {
	static public $aReplace = array();

	// Массив соответствий типовых динамических страниц загружаемого и созданного макетов
	static public $aAssosiatedLibs = array();

	// Массив соответствий параметров типовых динамических страниц загружаемого и созданного макетов
	static public $aAssosiatedLibFields = array();

	// Массив соответствий макетов сайта
	static public $aAssosiatedTemplates = array();

	// Массив соответствий узлов структуры
	static public $aAssosiatedStructures = array();

	// Массив соответствий списков
	static public $aAssosiatedLists = array();

	// Массив соответствий меню
	static public $aAssosiatedStructureMenus = array();

	// Массив соответствий документов
	static public $aAssosiatedDocuments = array();

	// Массив соответствий элементов списков
	static public $aAssosiatedListValues = array();

	// Массив соответствий форм
	static public $aAssosiatedForms = array();

	// Массив соответствий опросов
	static public $aAssosiatedPollGroups = array();

	// Массив соответствий ИС
	static public $aAssosiatedInformationsystems = array();

	// Массив соответствий групп ИС
	static public $aAssosiatedInformationsystemGroups = array();

	// Массив соответствий свойств
	static public $aAssosiatedProperties = array();

	// Массив соответствий табов групп и товаров
	static public $aAssosiatedShopTabs = array();

	// Массив соответствий платежных систем
	static public $aAssosiatedShopPaymentSystems = array();

	// Массив соответствий валют
	static public $aAssosiatedShopCurrencies = array();

	// Массив соответствий компаний
	static public $aAssosiatedCompanies = array();

	// Массив соответствий складов
	static public $aAssosiatedShopWarehouses = array();

	// Массив соответствий производителей
	static public $aAssosiatedShopProducers = array();

	// Массив соответствий магазинов
	static public $aAssosiatedShops = array();

	// Массив соответствий товаров магазина
	static public $aAssosiatedShopItems = array();

	// Массив соответствий групп магазина
	static public $aAssosiatedShopGroups = array();

	// Массив соответствий названий XSL-шаблонов
	static public $aAssosiatedXslNames = array();

	// Массив соответствий названий XSL-шаблонов
	static public $aAssosiatedTplNames = array();

	// Массив соответствий форумов
	static public $aAssosiatedForums = array();

	// Массив соответствий служб поддержки
	static public $aAssosiatedHelpdesks = array();

	// Массив соответствий скидок
	static public $aAssosiatedShopDiscounts = array();

	// Массив соответствий бонусов
	static public $aAssosiatedShopBonuses = array();

	// Массив соответствий пользователей сайта
	static public $aAssosiatedSiteusers = array();

	//Массив соответствий групп пользователей сайта
	static public $aAssosiatedSiteuserGroups = array();

	//Массив соответствий групп баннеров
	static public $aAssosiatedAdvertisementGroups = array();

	// Массив соответствий пользовательских полей
	static public $aAssosiatedFields = array();

	static public function replaceOptions($aTmpDat)
	{
		if (is_array($aTmpDat))
		{
			foreach ($aTmpDat as $key => &$value)
			{
				if (is_array($value))
				{
					$value = self::replaceOptions($value);
				}
				elseif (strlen((string) $value))
				{
					switch ($key)
					{
						case \'informationsystemId\':
							$value = Core_Array::get(CT::$aAssosiatedInformationsystems, $value, $value);
						break;
						case \'shopId\':
						case \'shop_id\':
							$value = Core_Array::get(CT::$aAssosiatedShops, $value, $value);
						break;
						case \'formId\':
							if (Core::moduleIsActive(\'form\'))
							{
								$value = Core_Array::get(CT::$aAssosiatedForms, $value, $value);
							}
						break;
						case \'helpdeskId\':
							if (Core::moduleIsActive(\'helpdesk\'))
							{
								$value = Core_Array::get(CT::$aAssosiatedHelpdesks, $value, $value);
							}
						break;
						case \'forum_id\':
							if (Core::moduleIsActive(\'forum\'))
							{
								$value = Core_Array::get(CT::$aAssosiatedForums, $value, $value);
							}
						break;
						case \'pollGroupId\':
							if (Core::moduleIsActive(\'poll\'))
							{
								$value = Core_Array::get(CT::$aAssosiatedPollGroups, $value, $value);
							}
						break;
						case \'advertisementGroupId\':
							if (Core::moduleIsActive(\'advertisement\'))
							{
								$value = Core_Array::get(CT::$aAssosiatedAdvertisementGroups, $value, $value);
							}
						break;
						case \'menuId\':
							$value = Core_Array::get(CT::$aAssosiatedStructureMenus, $value, $value);
						break;
						default:
							if (stripos($key, \'Xsl\') !== FALSE)
							{
								$value = Core_Array::get(CT::$aAssosiatedXslNames, $value, $value);
							}
							elseif (stripos($key, \'Tpl\') !== FALSE)
							{
								$value = Core_Array::get(CT::$aAssosiatedTplNames, $value, $value);
							}
							elseif (is_string($value))
							{
								foreach (self::$aReplace as $replaceKey => $replaceValue)
								{
									$value = str_replace($replaceKey, $replaceValue, $value);
								}
							}
						break;
					}
				}
			}

			unset($value);
		}

		return $aTmpDat;
	}

	// Язык, в котором был создан шаблон
	static public $templateLng = NULL;

	// Язык, в котором должен быть установлен шаблон
	static public $installLng = NULL;

	static public $i18n = array();

	static public function translate($text)
	{
		$name = self::$templateLng . "-" . self::$installLng;

		return isset(self::$i18n[$name][$text])
			? self::$i18n[$name][$text]
			: $text;
	}

	static public function importFields($aFields, $oObject)
	{
		$Install_Controller = Install_Controller::instance();

		foreach ($aFields as $aFieldValue)
		{
			$oField = isset(CT::$aAssosiatedFields[$aFieldValue[\'field_id\']])
				? Core_Entity::factory(\'Field\')->getById(CT::$aAssosiatedFields[$aFieldValue[\'field_id\']], FALSE)
				: NULL;

			if (!is_null($oField))
			{
				$oField_Value = $oField->createNewValue($oObject->id);

				switch ($oField->type)
				{
					case 0: // Int
					case 1: // String
					case 4: // Textarea
					case 6: // Wysiwyg
					case 7: // Checkbox
					case 8: // Date
					case 9: // Datetime
						$oField_Value
							->value($aFieldValue[\'value\'])
							->save();
					break;

					case 2: //File
						$sPath = CMS_FOLDER . Field_Controller::getPath($oObject);
						$oField_Value->setDir($sPath);
						$oField_Value->save();

						if ($aFieldValue[\'file\'] != \'\' || $aFieldValue[\'file_small\'] != \'\')
						{
							Core_File::mkdir($sPath, CHMOD, TRUE);

							$largeFromPath = $Install_Controller->getTemplatePath() . "tmp/upload/fields/" . $aFieldValue[\'file\'];

							if ($aFieldValue[\'file\'] != \'\' && is_file($largeFromPath))
							{
								$ext = Core_File::getExtension($aFieldValue[\'file\']);

								$field_large = "field_large_" . $oObject->id . "_" .  $oField_Value->id . "." . $ext;
								Core_File::copy($largeFromPath, $sPath . $field_large);

								$oField_Value->file = $field_large;
								$oField_Value->file_name = $aFieldValue[\'file_name\'];
								$oField_Value->file_description = $aFieldValue[\'file_description\'];
								$oField_Value->save();
							}

							$smallFromPath = $Install_Controller->getTemplatePath() . "tmp/upload/fields/" . $aFieldValue[\'file_small\'];

							if ($aFieldValue[\'file_small\'] != \'\' && is_file($smallFromPath))
							{
								$ext = Core_File::getExtension($aFieldValue[\'file_small\']);

								$field_small = "field_small_" . $oObject->id . "_" .  $oField_Value->id . "." . $ext;
								Core_File::copy($smallFromPath, $sPath . $field_small);

								$oField_Value->file_small = $field_small;
								$oField_Value->file_small_name = $aFieldValue[\'file_small_name\'];
								$oField_Value->file_small_description = $aFieldValue[\'file_small_description\'];
								$oField_Value->save();
							}
						}
					break;

					case 3: //List
						if (Core::moduleIsActive(\'list\')
							&& isset(CT::$aAssosiatedListValues[$aFieldValue[\'value\']]))
						{
							$oField_Value
								->value(CT::$aAssosiatedListValues[$aFieldValue[\'value\']])
								->save();
						}
					break;
				}
			}
		}
	}
}

if (is_array($aOptions))
{
	foreach ($aOptions as $optionName => $optionValue)
	{
		CT::$aReplace["%" . $optionName . "%"] = $optionValue;
	}
}

// Язык, в котором был создан шаблон
CT::$templateLng = "' . $oOldSite->lng . '";

// Язык, в котором должен быть установлен шаблон
// CT::$installLng = "en";
CT::$installLng = isset($_SESSION[\'current_lng\']) ? $_SESSION[\'current_lng\'] : DEFAULT_LNG;
';

function prepareLng(&$value, $key)
{
	$value = "'{$key}' => '{$value}'";
}

$aRuEn = Install::$i18n;
array_walk($aRuEn, 'prepareLng');

$aEnRu = array_flip(Install::$i18n);
array_walk($aEnRu, 'prepareLng');

$content .= '
CT::$i18n["ru-en"] = array(' . implode(",", $aRuEn) . ');

CT::$i18n["en-ru"] = array(' . implode(",", $aEnRu) . ');

$Install_Controller = Install_Controller::instance();
$Install_Controller->setTemplatePath($tmpDir);

$sCurrentDate = date("d.m.Y H:i:s");

$sCompanyEmail = Core_Array::get($aOptions, "company_email", "undefined@undefined.com");

$aTpli18n = array();

// Модули коммерческих редакций
$aPollGroupi18n = $aListi18n = $aFormi18n = $aForumi18n = $aHelpdeski18n = $aAdvertisementGroupi18n = $aSiteuserGroupsi18n = $aSiteuseri18n = array();

// Массив сайтов
$aSitei18n = array(
		\'name\' => "' . addslashesapostrophe($oOldSite->name) . '",
		\'sitePostfix\' => CT::translate("Сайт%d"),' . "\n";

		$content .= "		'error404' => " . $oOldSite->error404 . ", " . "\n" .
			"		'error403' => " . $oOldSite->error403 . ", " . "\n" .
			"		'closed' => " . $oOldSite->closed . ", " . "\n";
			//"		'favicon' => '" . $oOldSite->favicon . "', " . "\n";

		$content .= "		'favicons' => array(" . "\n";

		$aSite_Favicons = $oOldSite->Site_Favicons->findAll();
		foreach ($aSite_Favicons as $oSite_Favicon)
		{
			$content .= "			{$oSite_Favicon->id} => array(" . "\n" .
			"				'filename' => '" . addslashesapostrophe($oSite_Favicon->filename) . "'," . "\n" .
			"				'rel' => '" . addslashesapostrophe($oSite_Favicon->rel) . "'," . "\n" .
			"				'type' => '" . addslashesapostrophe($oSite_Favicon->type) . "'," . "\n" .
			"				'sizes' => '" . addslashesapostrophe($oSite_Favicon->sizes) . "'," . "\n" .
			"			)," . "\n";

			$sTmpPath = $oSite_Favicon->getFaviconPath();

			if (is_file($sTmpPath))
			{
				Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oSite_Favicon->getFaviconHref());
			}
		}

		$content .= "		)," . "\n";

		// Свойства узлов
		$content .= "		'properties' => array(" . "\n";

		$aStructure_Properties = $oOldSite->Structure_Properties->findAll();
		foreach ($aStructure_Properties as $oStructure_Property)
		{
			$oProperty = $oStructure_Property->Property;

			if ($oProperty->id)
			{
				$content .= "			{$oProperty->id} => array(" . "\n" .
				"				'name' => '" . addslashesapostrophe($oProperty->name) . "'," . "\n" .
				"				'dirName' => ''," . "\n" .
				"				'type' => '" . $oProperty->type . "'," . "\n" .
				"				'description' => '" . addslashesapostrophe($oProperty->description) . "'," . "\n" .
				"				'default_value' => '" . addslashesapostrophe($oProperty->default_value) . "'," . "\n" .
				"				'tag_name' => '" . addslashesapostrophe($oProperty->tag_name) . "'," . "\n" .
				"				'sorting' => " . $oProperty->sorting . ", " . "\n" .
				"				'multiple' => " . $oProperty->multiple . ", " . "\n" .
				"				'image_large_max_width' => " . $oProperty->image_large_max_width . ", " . "\n" .
				"				'image_large_max_height' => " . $oProperty->image_large_max_height . ", " . "\n" .
				"				'image_small_max_width' => " . $oProperty->image_small_max_width . ", " . "\n" .
				"				'image_small_max_height' => " . $oProperty->image_small_max_height . ", " . "\n" .
				"				'hide_small_image' => " . $oProperty->hide_small_image . ", " . "\n" .
				"			)," . "\n";
			}
		}

		$content .= "		)," . "\n";

		$content .= Install::exportFieldValues('site', $oOldSite, $tmpDir);

		/*if (strlen($oOldSite->favicon))
		{
			$sTmpPath = $oOldSite->getFaviconPath();

			if (is_file($sTmpPath))
			{
				Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oOldSite->getFaviconHref());
			}
		}*/

	$content .= '
);

// Константы
$aConstants = array(' . "\n";

	$oConstants = Core_Entity::factory('Constant');
	$oConstants->queryBuilder()
		->where('constants.name', 'NOT LIKE', '%HOSTCMS%')
		->where('constants.name', 'NOT LIKE', '%YANDEX%')
		->where('constants.name', 'NOT LIKE', '%BETA%')
		->where('constants.name', 'NOT LIKE', '%BENCHMARK%')
		->where('constants.id', '>', 36)
		->clearOrderBy()
		->orderBy('constants.id', 'ASC');

	$aConstants = $oConstants->findAll(FALSE);

	foreach ($aConstants as $oConstant)
	{
		if (!is_null(Core_Array::getPost('constant_' . $oConstant->id)))
		{
			$content .= "		{$oConstant->id} => array(" . "\n" .
			"			'dirName' => '" . Install::getConstantDirName($oConstant) . "'," . "\n" .
			"			'name' => '" . addslashesapostrophe($oConstant->name) . "'," . "\n" .
			"			'value' => '" . addslashesapostrophe($oConstant->value) . "'," . "\n" .
			"			'description' => '" . addslashesapostrophe($oConstant->description) . "'," . "\n" .
			"			'active' => " . $oConstant->active . ", " . "\n";

			$content .= Install::exportFieldValues('constant', $oConstant, $tmpDir);

			$content .= "		),\n";
		}
	}

$content .= ');

// Массив XSL-шаблонов
$aXsli18n = array(' . "\n";

	$oXsls = Core_Entity::factory('Xsl');
	$oXsls->queryBuilder()
		->clearOrderBy()
		->orderBy('xsls.id', 'ASC');

	$aXsls = $oXsls->findAll(FALSE);

	foreach ($aXsls as $oXsl)
	{
		// Указано включать в файл
		if (!is_null(Core_Array::getPost('xsl_' . $oXsl->id)))
		{
			$content .= "		'{$oXsl->id}.xsl' => array('id' => " . $oXsl->id . ", 'name' => '" . addslashesapostrophe($oXsl->name) . "', 'dirName' => '" . Install::getXslDirName($oXsl) ."'),\n";

			$content .= Install::exportFieldValues('xsl', $oXsl, $tmpDir);

			if (is_file($oXsl->getXslFilePath()))
			{
				Core_File::copy($oXsl->getXslFilePath(), $tmpDir . 'hostcmsfiles/xsl/' . $oXsl->id . '.xsl');

				foreach (Install::$aLngs as $sTmpLng)
				{
					if (is_file($oXsl->getLngDtdPath($sTmpLng)))
					{
						Core_File::copy($oXsl->getLngDtdPath($sTmpLng), $tmpDir . 'hostcmsfiles/xsl/' . $oXsl->id . '.' . $sTmpLng . '.dtd');
					}
				}
			}
			else
			{
				$aMessages[] = array('type' => 'warning', 'text' => "Предупреждение: Для XSL-шаблона '{$oXsl->name}' (id {$oXsl->id}) отсутствует .xsl-файл");
			}
		}
	}

	$content .= '
);';

if (Core::moduleIsActive('tpl'))
{
$content .= '

// Массив TPL-шаблонов
$aTpli18n = array(' . "\n";

	$oTpls = Core_Entity::factory('Tpl');
	$oTpls->queryBuilder()
		->clearOrderBy()
		->orderBy('tpls.id', 'ASC');

	$aTpls = $oTpls->findAll(FALSE);

	foreach ($aTpls as $oTpl)
	{
		// Указано включать в файл
		if (!is_null(Core_Array::getPost('tpl_' . $oTpl->id)))
		{
			$content .= "		'{$oTpl->id}.tpl' => array('id' => " . $oTpl->id . ", 'name' => '" . addslashesapostrophe($oTpl->name) . "', 'dirName' => '" . Install::getTplDirName($oTpl) ."'),\n";

			$content .= Install::exportFieldValues('tpl', $oTpl, $tmpDir);

			if (is_file($oTpl->getTplFilePath()))
			{
				Core_File::copy($oTpl->getTplFilePath(), $tmpDir . 'hostcmsfiles/tpl/' . $oTpl->id . '.tpl');

				foreach (Install::$aLngs as $sTmpLng)
				{
					if (is_file($oTpl->getLngConfigPath($sTmpLng)))
					{
						Core_File::copy($oTpl->getLngConfigPath($sTmpLng), $tmpDir . 'hostcmsfiles/tpl/' . $oTpl->id . '.' . $sTmpLng . '.config');
					}
				}
			}
			else
			{
				$aMessages[] = array('type' => 'warning', 'text' => "Предупреждение: Для TPL-шаблона '{$oTpl->name}' (id {$oTpl->id}) отсутствует .tpl-файл");
			}
		}
	}

	$content .= '
);';
}

$content .= '

// Массив типовых динамических страниц
$aLibi18n = array(' . "\n";

	$oLibs = Core_Entity::factory('Lib');
	$oLibs->queryBuilder()
		->clearOrderBy()
		->orderBy('libs.id', 'ASC');

	$_aLibs = $oLibs->findAll(FALSE);

	foreach ($_aLibs as $oLib)
	{
		Install::findFiles($oLib->loadLibConfigFile());
		Install::findFiles($oLib->loadLibFile());

		// Указано включать в файл
		if (!is_null(Core_Array::getPost('lib_' . $oLib->id)))
		{
			$content .= "		{$oLib->id} => array(" . "\n" .
			"			'name' => '" . addslashesapostrophe($oLib->name) . "'," . "\n" .
			"			'dirName' => '" . Install::getLibDirName($oLib) ."'," . "\n" .
			"			'code' => 'lib_" . $oLib->id . ".php'," . "\n" .
			"			'config' => 'lib_config_" . $oLib->id . ".php'," . "\n" .
			"			'params' => array(" . "\n";

			// Параметры ТДС
			$aLib_Properties = $oLib->Lib_Properties->findAll();
			foreach ($aLib_Properties as $oLib_Property)
			{
				$content .= "				{$oLib_Property->id} => array(" . "\n" .
				"					'name' => '" . addslashesapostrophe($oLib_Property->name) . "'," . "\n" .
				"					'varible_name' => '" . $oLib_Property->varible_name . "'," . "\n" .
				"					'type' => '" . $oLib_Property->type . "'," . "\n" .
				"					'default_value' => '" . $oLib_Property->default_value . "'," . "\n" .
				"					'multivalue' => " . $oLib_Property->multivalue . "," . "\n" .
				"					'sorting' => " . $oLib_Property->sorting . "," . "\n";

				if ($oLib_Property->type == 4)
				{
					$content .= "					'sql_request' => '" . addslashesapostrophe($oLib_Property->sql_request) . "'," . "\n" .
					"					'sql_caption_field' => '" . addslashesapostrophe($oLib_Property->sql_caption_field) . "'," . "\n" .
					"					'sql_value_field' => '" . addslashesapostrophe($oLib_Property->sql_value_field) . "'," . "\n";
				}

				// Значения параметров ТДС
				$aLib_Property_List_Values = $oLib_Property->Lib_Property_List_Values->findAll();

				if ($aLib_Property_List_Values)
				{
					$content .="		 			'values' => array(" . "\n";

					foreach ($aLib_Property_List_Values as $oLib_Property_List_Value)
					{
						$content .= "						'" . addslashesapostrophe($oLib_Property_List_Value->value) . "' => '" . addslashesapostrophe($oLib_Property_List_Value->name) . "'," . "\n";

						$content .= Install::exportFieldValues('lib_property_list_value', $oLib_Property_List_Value, $tmpDir);
					}

					$content .= "					)," . "\n";
				}

				$content .= Install::exportFieldValues('lib_property', $oLib_Property, $tmpDir);

				$content .= "				)," . "\n";
			}

			$content .= Install::exportFieldValues('lib', $oLib, $tmpDir);

			$content .= "			)" . "\n" . "		),\n";

			Core_File::copy($oLib->getLibFilePath(), $tmpDir . 'hostcmsfiles/lib/lib_' . $oLib->id . '/lib_' . $oLib->id . '.php');
			Core_File::copy($oLib->getLibConfigFilePath(), $tmpDir . 'hostcmsfiles/lib/lib_' . $oLib->id . '/lib_config_' . $oLib->id . '.php');
		}
	}

	$content .= '
);

// Массив макетов шаблона
$aTemplatei18n = array(' . "\n";

	$oTemplates = $oOldSite->Templates;
	$oTemplates->queryBuilder()
		->clearOrderBy()
		->orderBy('templates.id', 'ASC');

	$aTemplates = $oTemplates->findAll(FALSE);

	foreach ($aTemplates as $oTemplate)
	{
		Install::findFiles($oTemplate->loadTemplateFile());
		Install::findInCSS($oTemplate->getTemplateCssFileHref());

		$content .= "		{$oTemplate->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oTemplate->name) . "'," . "\n" .
		"			'dirName' => '" . Install::getTemplateDirName($oTemplate) ."'," . "\n" .
		"			'type' => " . $oTemplate->type . "," . "\n" .
		"			'parent_template_id' => {$oTemplate->template_id}," . "\n";

		$oTemplate_Sections = $oTemplate->Template_Sections;
		$oTemplate_Sections->queryBuilder()
			->clearOrderBy()
			->orderBy('template_sections.id', 'ASC');

		$aTemplate_Sections = $oTemplate_Sections->findAll(FALSE);

		if (count($aTemplate_Sections))
		{
			$content .= "			'template_sections' => array(" . "\n";

			foreach ($aTemplate_Sections as $oTemplate_Section)
			{
				$content .= "				{$oTemplate_Section->id} => array(" . "\n" .
				"					'template_id' => {$oTemplate_Section->template_id}," . "\n" .
				"					'name' => '" . addslashesapostrophe($oTemplate_Section->name) . "'," . "\n" .
				"					'alias' => '" . addslashesapostrophe($oTemplate_Section->alias) . "'," . "\n" .
				"					'prefix' => '" . addslashesapostrophe($oTemplate_Section->prefix) . "'," . "\n" .
				"					'suffix' => '" . addslashesapostrophe($oTemplate_Section->suffix) . "'," . "\n" .
				"					'color' => '" . $oTemplate_Section->color . "'," . "\n" .
				"					'sorting' => " . $oTemplate_Section->sorting . "," . "\n";

				$oTemplate_Section_Libs = $oTemplate_Section->Template_Section_Libs;
				$oTemplate_Section_Libs->queryBuilder()
					->clearOrderBy()
					->orderBy('template_section_libs.id', 'ASC');

				$aTemplate_Section_Libs = $oTemplate_Section_Libs->findAll(FALSE);

				if (count($aTemplate_Section_Libs))
				{
					$content .= "					'template_section_libs' => array(" . "\n";

					foreach ($aTemplate_Section_Libs as $oTemplate_Section_Lib)
					{
						$content .= "						{$oTemplate_Section_Lib->id} => array(" . "\n" .
						"							'template_section_id' => {$oTemplate_Section_Lib->template_section_id}," . "\n" .
						"							'lib_id' => {$oTemplate_Section_Lib->lib_id}," . "\n" .
						"							'options' => '" . addslashesapostrophe($oTemplate_Section_Lib->options) . "'," . "\n" .
						"							'class' => '" . addslashesapostrophe($oTemplate_Section_Lib->class) . "'," . "\n" .
						"							'style' => '" . addslashesapostrophe($oTemplate_Section_Lib->style) . "'," . "\n" .
						"							'active' => {$oTemplate_Section_Lib->active}," . "\n" .
						"							'sorting' => " . $oTemplate_Section_Lib->sorting . "," . "\n";

						$content .= Install::exportFieldValues('template_section_lib', $oTemplate_Section_Lib, $tmpDir);

						$content .= "						)," . "\n";

						if (is_dir($oTemplate_Section_Lib->getLibFilePath()))
						{
							Core_File::copyDir($oTemplate_Section_Lib->getLibFilePath(), $tmpDir . "upload/libs/lib_{$oTemplate_Section_Lib->lib_id}/widget_{$oTemplate_Section_Lib->id}/");
						}
					}

					$content .= "					)" . "\n";
				}

				$content .= Install::exportFieldValues('template_section', $oTemplate_Section, $tmpDir);

				$content .= "				)," . "\n";
			}

			$content .= "			)" . "\n";
		}

		$content .= Install::exportFieldValues('template', $oTemplate, $tmpDir);

		$content .= "		),\n";

		if (is_file($oTemplate->getTemplateFilePath()))
		{
			Core_File::copy($oTemplate->getTemplateFilePath(), $tmpDir . 'templates/template' . $oTemplate->id . '/template.htm');
		}

		if (is_file($oTemplate->getTemplateCssFilePath()))
		{
			Core_File::copy($oTemplate->getTemplateCssFilePath(), $tmpDir . 'templates/template' . $oTemplate->id . '/style.css');
		}

		if (is_file($oTemplate->getTemplateLessFilePath()))
		{
			Core_File::copy($oTemplate->getTemplateLessFilePath(), $tmpDir . 'templates/template' . $oTemplate->id . '/style.less');
		}

		if (is_file($oTemplate->getTemplateScssFilePath()))
		{
			Core_File::copy($oTemplate->getTemplateScssFilePath(), $tmpDir . 'templates/template' . $oTemplate->id . '/style.scss');
		}

		if (is_file($oTemplate->getTemplateJsFilePath()))
		{
			Core_File::copy($oTemplate->getTemplateJsFilePath(), $tmpDir . 'templates/template' . $oTemplate->id . '/script.js');
		}

		if (is_file($oTemplate->getManifestPath()))
		{
			Core_File::copy($oTemplate->getManifestPath(), $tmpDir . 'templates/template' . $oTemplate->id . '/manifest.xml');
		}

		foreach (Install::$aLngs as $sTmpLng)
		{
			if (is_file($oTemplate->getLngPath($sTmpLng)))
			{
				Core_File::copy($oTemplate->getLngPath($sTmpLng), $tmpDir . 'templates/template' . $oTemplate->id . '/i18n/' . $sTmpLng . '.php');
			}
		}
	}

	$content .= '
);

// Массив документов
$aDoci18n = array(' . "\n";

	$oDocuments = $oOldSite->Documents;
	$oDocuments->queryBuilder()
		->clearOrderBy()
		->orderBy('documents.id', 'ASC');

	$aDocuments = $oDocuments->findAll();

	foreach ($aDocuments as $oDocument)
	{
		$content .= "		{$oDocument->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oDocument->name) . "'," . "\n" .
		"			'dirName' => '" . Install::getDocumentDirName($oDocument) ."'," . "\n" .
		"			'text' => '" . addslashesapostrophe($oDocument->text) ."'," . "\n" .
		"			'datetime' => '" . $oDocument->datetime ."'," . "\n" .
		"			'template_id' => " . $oDocument->template_id . "" . "\n";

		$content .= Install::exportFieldValues('document', $oDocument, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);

// Массив меню
$aMenui18n = array(' . "\n";

	$aStructure_Menus = $oOldSite->Structure_Menus->findAll();

	foreach ($aStructure_Menus as $oStructure_Menu)
	{
		$content .= "		{$oStructure_Menu->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oStructure_Menu->name) . "'," . "\n" .
		"			'color' => '" . addslashesapostrophe($oStructure_Menu->color) . "'," . "\n" .
		"			'sorting' => " . $oStructure_Menu->sorting . "" . "\n";

		$content .= Install::exportFieldValues('structure_menu', $oStructure_Menu, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);';

if (Core::moduleIsActive('list'))
{
$content .= '

// Массив списков
$aListi18n = array(' . "\n";

	$aLists = $oOldSite->Lists->findAll();

	foreach ($aLists as $oList)
	{
		$content .= "		{$oList->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oList->name) . "'," . "\n" .
		"			'dirName' => '" . Install::getListDirName($oList) ."'," . "\n" .
		"			'list_items' => array(" . "\n";

		$aList_Items = $oList->List_Items->findAll();
		foreach ($aList_Items as $oList_Item)
		{
			$content .= "				{$oList_Item->id} => array(" . "\n" .
			"					'value' => '" . addslashesapostrophe($oList_Item->value) . "'," . "\n" .
			"					'sorting' => " . $oList_Item->sorting ."," . "\n" .
			"					'description' => '" . addslashesapostrophe($oList_Item->description) . "'," . "\n" .
			"					'color' => '" . addslashesapostrophe(isset($oList_Item->color) ? $oList_Item->color : '') . "'," . "\n" .
			"					'icon' => '" . addslashesapostrophe($oList_Item->icon) . "'," . "\n" .
			"					'active' => " . $oList_Item->active . ", " . "\n";

			$content .= Install::exportFieldValues('list_item', $oList_Item, $tmpDir);

			$content .= "				)," . "\n";
		}

		$content .= "			)," . "\n";

		$content .= Install::exportFieldValues('list', $oList, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);';
}

if (Core::moduleIsActive('form'))
{
$content .= '

// Массив форм
$aFormi18n = array(' . "\n";

	$aForms = $oOldSite->Forms->findAll();

	foreach ($aForms as $oForm)
	{
		$content .= "		{$oForm->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oForm->name) . "'," . "\n" .
		"			'email' => '" . addslashesapostrophe($oForm->email) . "'," . "\n" .
		"			'button_name' => '" . addslashesapostrophe($oForm->button_name) . "'," . "\n" .
		"			'button_value' => '" . addslashesapostrophe($oForm->button_value) . "'," . "\n" .
		"			'email_subject' => '" . addslashesapostrophe($oForm->email_subject) . "'," . "\n" .
		"			'success_text' => '" . addslashesapostrophe($oForm->success_text) . "'," . "\n" .
		"			'use_captcha' => " . $oForm->use_captcha . ", " . "\n" .
		"			'form_fields' => array(" . "\n";

		$aForm_Fields = $oForm->Form_Fields->findAll();
		foreach ($aForm_Fields as $oForm_Field)
		{
			$content .= "				{$oForm_Field->id} => array(" . "\n" .
			"					'caption' => '" . addslashesapostrophe($oForm_Field->caption) . "'," . "\n" .
			"					'dirName' => '" . Install::getFormFieldDirName($oForm_Field) ."'," . "\n" .
			"					'type' => '" . $oForm_Field->type . "'," . "\n" .
			"					'name' => '" . addslashesapostrophe($oForm_Field->name) . "'," . "\n" .
			"					'size' => " . $oForm_Field->size . ", " . "\n" .
			"					'default_value' => '" . addslashesapostrophe($oForm_Field->default_value) . "'," . "\n" .
			"					'sorting' => " . $oForm_Field->sorting . ", " . "\n" .
			"					'obligatory' => " . $oForm_Field->obligatory . ", " . "\n";

			$content .= Install::exportFieldValues('form_field', $oForm_Field, $tmpDir);

			$content .= "				)," . "\n";
		}

		$content .= "			)," . "\n";

		$content .= Install::exportFieldValues('form', $oForm, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);';
}

if (Core::moduleIsActive('poll'))
{
$content .= '

// Массив опросов
$aPollGroupi18n = array(' . "\n";

	$aPoll_Groups = $oOldSite->Poll_Groups->findAll();

	foreach ($aPoll_Groups as $oPoll_Group)
	{
		$content .= "		{$oPoll_Group->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oPoll_Group->name) . "'," . "\n" .
		"			'structure_id' => " . $oPoll_Group->structure_id . ", " . "\n" .
		"			'polls' => array(" . "\n";

		$aPolls = $oPoll_Group->Polls->findAll();
		foreach ($aPolls as $oPoll)
		{
			$content .= "				{$oPoll->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oPoll->name) . "'," . "\n" .
			"					'type' => " . $oPoll->type . ", " . "\n" .
			"					'show_results' => " . $oPoll->show_results . ", " . "\n" .
			"					'active' => " . $oPoll->active . ", " . "\n" .
			"					'start_date' => '" . $oPoll->start_date . "'," . "\n" .
			"					'end_date' => '" . $oPoll->end_date . "'," . "\n" .
			"					'poll_responses' => array(" . "\n";

			$aPoll_Responses = $oPoll->Poll_Responses->findAll();
			foreach ($aPoll_Responses as $oPoll_Response)
			{
				$content .= "						{$oPoll_Response->id} => array(" . "\n" .
				"							'name' => '" . addslashesapostrophe($oPoll_Response->name) . "'," . "\n" .
				"							'grade' => " . $oPoll_Response->grade . ", " . "\n" .
				"							'sorting' => " . $oPoll_Response->sorting . ", " . "\n";

				$content .= Install::exportFieldValues('poll_response', $oPoll_Response, $tmpDir);

				$content .= "						)," . "\n";
			}

			$content .= "					)," . "\n";

			$content .= Install::exportFieldValues('poll', $oPoll, $tmpDir);

			$content .= "				),\n";
		}

		$content .= "			)," . "\n";

		$content .= Install::exportFieldValues('poll_group', $oPoll_Group, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);';
}

$content .= '

// Массив информационных систем
$aInformationsystemi18n = array(' . "\n";

	$aInformationsystems = $oOldSite->Informationsystems->findAll();
	foreach ($aInformationsystems as $oInformationsystem)
	{
		$content .= "		{$oInformationsystem->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oInformationsystem->name) . "'," . "\n" .
		"			'description' => '" . addslashesapostrophe($oInformationsystem->description) . "'," . "\n" .
		"			'dirName' => ''," . "\n" .
		"			'structure_id' => " . $oInformationsystem->structure_id . ", " . "\n" .
		"			'items_on_page' => " . $oInformationsystem->items_on_page . ", " . "\n" .
		"			'items_sorting_field' => " . $oInformationsystem->items_sorting_field . ", " . "\n" .
		"			'items_sorting_direction' => " . $oInformationsystem->items_sorting_direction . ", " . "\n" .
		"			'groups_sorting_field' => " . $oInformationsystem->groups_sorting_field . ", " . "\n" .
		"			'groups_sorting_direction' => " . $oInformationsystem->groups_sorting_direction . ", " . "\n" .
		"			'image_large_max_width' => " . $oInformationsystem->image_large_max_width . ", " . "\n" .
		"			'image_large_max_height' => " . $oInformationsystem->image_large_max_height . ", " . "\n" .
		"			'image_small_max_width' => " . $oInformationsystem->image_small_max_width . ", " . "\n" .
		"			'image_small_max_height' => " . $oInformationsystem->image_small_max_height . ", " . "\n" .
		"			'group_image_large_max_width' => " . $oInformationsystem->group_image_large_max_width . ", " . "\n" .
		"			'group_image_large_max_height' => " . $oInformationsystem->group_image_large_max_height . ", " . "\n" .
		"			'group_image_small_max_width' => " . $oInformationsystem->group_image_small_max_width . ", " . "\n" .
		"			'group_image_small_max_height' => " . $oInformationsystem->group_image_small_max_height . ", " . "\n" .
		"			'siteuser_group_id' => " . $oInformationsystem->siteuser_group_id . ", " . "\n" .
		"			'typograph_default_items' => " . $oInformationsystem->typograph_default_items . ", " . "\n" .
		"			'typograph_default_groups' => " . $oInformationsystem->typograph_default_groups . ", " . "\n" .
		"			'use_captcha' => " . $oInformationsystem->use_captcha . ", " . "\n" .
		"			'informationsystem_groups' => array(" . "\n";

		// Группы
		$aInformationsystem_Groups = $oInformationsystem->Informationsystem_Groups->findAll();
		foreach ($aInformationsystem_Groups as $oInformationsystem_Group)
		{
			$content .= "				{$oInformationsystem_Group->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oInformationsystem_Group->name) . "'," . "\n" .
			"					'parent_id' => " . $oInformationsystem_Group->parent_id . ", " . "\n" .
			"					'description' => '" . addslashesapostrophe($oInformationsystem_Group->description) . "'," . "\n" .
			"					'path' => '" . addslashesapostrophe($oInformationsystem_Group->path) . "'," . "\n" .
			"					'sorting' => " . $oInformationsystem_Group->sorting . ", " . "\n" .
			"					'active' => " . $oInformationsystem_Group->active . ", " . "\n" .
			"					'indexing' => " . $oInformationsystem_Group->indexing . ", " . "\n" .
			"					'image_large' => '" . $oInformationsystem_Group->image_large . "', " . "\n" .
			"					'image_small' => '" . $oInformationsystem_Group->image_small . "', " . "\n" .
			"					'property_values' => array(" . "\n";

			$aPropertyValues = $oInformationsystem_Group->getPropertyValues();
			foreach ($aPropertyValues as $oPropertyValue)
			{
				$oProperty = $oPropertyValue->Property;

				if ($oProperty->type != 2)
				{
					$content .= "						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oProperty->id . ", " . "\n" .
					"							'value' => '" . addslashesapostrophe($oPropertyValue->value) . "'," . "\n" .
					"						)," . "\n";
				}
				else
				{
					$content .= "						// File" . "\n" .
					"						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oProperty->id . ", " . "\n" .
					"							'file' => '" . addslashesapostrophe($oPropertyValue->file) . "', " . "\n" .
					"							'file_small' => '" . addslashesapostrophe($oPropertyValue->file_small) . "', " . "\n" .
					"						)," . "\n";

					if (strlen($oPropertyValue->file_small))
					{
						$sTmpPath = $oPropertyValue->getSmallFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getSmallFileHref());
						}
					}

					if (strlen($oPropertyValue->file))
					{
						$sTmpPath = $oPropertyValue->getLargeFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getLargeFileHref());
						}
					}
				}
			}

			$content .= "					)," . "\n";

			$content .= Install::exportFieldValues('informationsystem_group', $oInformationsystem_Group, $tmpDir);

			$content .= "				)," . "\n";

			if (strlen($oInformationsystem_Group->image_small))
			{
				$sTmpPath = $oInformationsystem_Group->getSmallFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oInformationsystem_Group->getSmallFileHref());
				}
			}

			if (strlen($oInformationsystem_Group->image_large))
			{
				$sTmpPath = $oInformationsystem_Group->getLargeFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oInformationsystem_Group->getLargeFileHref());
				}
			}
		}

		$content .= "			)," . "\n";

		// Элементы
		$content .= "			'informationsystem_items' => array(" . "\n";

		$aInformationsystem_Items = $oInformationsystem->Informationsystem_Items->findAll();
		foreach ($aInformationsystem_Items as $oInformationsystem_Item)
		{
			$content .= "				{$oInformationsystem_Item->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oInformationsystem_Item->name) . "'," . "\n" .
			"					'informationsystem_group_id' => " . $oInformationsystem_Item->informationsystem_group_id . ", " . "\n" .
			"					'shortcut_id' => " . $oInformationsystem_Item->shortcut_id . ", " . "\n" .
			"					'path' => '" . addslashesapostrophe($oInformationsystem_Item->path) . "'," . "\n" .
			"					'active' => " . $oInformationsystem_Item->active . ", " . "\n" .
			"					'indexing' => " . $oInformationsystem_Item->indexing . ", " . "\n" .
			"					'image_large' => '" . $oInformationsystem_Item->image_large . "', " . "\n" .
			"					'image_small' => '" . $oInformationsystem_Item->image_small . "', " . "\n" .
			"					'sorting' => " . $oInformationsystem_Item->sorting . ", " . "\n" .
			"					'description' => '" . addslashesapostrophe($oInformationsystem_Item->description) . "'," . "\n" .
			"					'text' => '" . addslashesapostrophe($oInformationsystem_Item->text) . "'," . "\n" .
			"					'seo_title' => '" . addslashesapostrophe($oInformationsystem_Item->seo_title) . "'," . "\n" .
			"					'seo_description' => '" . addslashesapostrophe($oInformationsystem_Item->seo_description) . "'," . "\n" .
			"					'seo_keywords' => '" . addslashesapostrophe($oInformationsystem_Item->seo_keywords) . "'," . "\n" .
			"					'tags' => '" . Install::getInformationsystemTags($oInformationsystem_Item) . "'," . "\n" .
			"					'property_values' => array(" . "\n";

			$aPropertyValues = $oInformationsystem_Item->getPropertyValues();
			foreach ($aPropertyValues as $oPropertyValue)
			{
				$oProperty = $oPropertyValue->Property;

				if ($oProperty->type != 2)
				{
					$content .= "						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oProperty->id . ", " . "\n" .
					"							'value' => '" . addslashesapostrophe($oPropertyValue->value) . "'," . "\n" .
					"						)," . "\n";
				}
				else
				{
					$content .= "						// File" . "\n" .
					"						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oProperty->id . ", " . "\n" .
					"							'file' => '" . addslashesapostrophe($oPropertyValue->file) . "', " . "\n" .
					"							'file_small' => '" . addslashesapostrophe($oPropertyValue->file_small) . "', " . "\n" .
					"						)," . "\n";

					if (strlen($oPropertyValue->file_small))
					{
						$sTmpPath = $oPropertyValue->getSmallFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getSmallFileHref());
						}
					}

					if (strlen($oPropertyValue->file))
					{
						$sTmpPath = $oPropertyValue->getLargeFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getLargeFileHref());
						}
					}
				}
			}

			$content .= "					)," . "\n";

			$content .= Install::exportFieldValues('informationsystem_item', $oInformationsystem_Item, $tmpDir);

			$content .= "				)," . "\n";

			if (strlen($oInformationsystem_Item->image_small))
			{
				$sTmpPath = $oInformationsystem_Item->getSmallFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oInformationsystem_Item->getSmallFileHref());
				}
			}

			if (strlen($oInformationsystem_Item->image_large))
			{
				$sTmpPath = $oInformationsystem_Item->getLargeFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oInformationsystem_Item->getLargeFileHref());
				}
			}
		}

		$content .= "			)," . "\n";

		// Свойства элементов
		$content .= "			'properties' => array(" . "\n";

		$aInformationsystem_Item_Properties = $oInformationsystem->Informationsystem_Item_Properties->findAll();
		foreach ($aInformationsystem_Item_Properties as $oInformationsystem_Item_Property)
		{
			$oProperty = $oInformationsystem_Item_Property->Property;

			if ($oProperty->id)
			{
				$content .= "				{$oProperty->id} => array(" . "\n" .
				"					'name' => '" . addslashesapostrophe($oProperty->name) . "'," . "\n" .
				"					'dirName' => '" . Install::getPropertyDirName($oProperty) ."'," . "\n" .
				"					'type' => '" . $oProperty->type . "'," . "\n" .
				"					'description' => '" . addslashesapostrophe($oProperty->description) . "'," . "\n" .
				"					'default_value' => '" . addslashesapostrophe($oProperty->default_value) . "'," . "\n" .
				"					'tag_name' => '" . addslashesapostrophe($oProperty->tag_name) . "'," . "\n" .
				"					'sorting' => " . $oProperty->sorting . ", " . "\n" .
				"					'multiple' => " . $oProperty->multiple . ", " . "\n" .
				"					'image_large_max_width' => " . $oProperty->image_large_max_width . ", " . "\n" .
				"					'image_large_max_height' => " . $oProperty->image_large_max_height . ", " . "\n" .
				"					'image_small_max_width' => " . $oProperty->image_small_max_width . ", " . "\n" .
				"					'image_small_max_height' => " . $oProperty->image_small_max_height . ", " . "\n" .
				"					'hide_small_image' => " . $oProperty->hide_small_image . ", " . "\n" .
				"				)," . "\n";
			}
		}

		$content .= "			)," . "\n";

		// Свойства групп
		$content .= "			'group_properties' => array(" . "\n";

		$aInformationsystem_Group_Properties = $oInformationsystem->Informationsystem_Group_Properties->findAll();
		foreach ($aInformationsystem_Group_Properties as $oInformationsystem_Group_Property)
		{
			$oProperty = $oInformationsystem_Group_Property->Property;

			if ($oProperty->id)
			{
				$content .= "				{$oProperty->id} => array(" . "\n" .
				"					'name' => '" . addslashesapostrophe($oProperty->name) . "'," . "\n" .
				"					'dirName' => '" . Install::getPropertyDirName($oProperty) ."'," . "\n" .
				"					'type' => '" . $oProperty->type . "'," . "\n" .
				"					'description' => '" . addslashesapostrophe($oProperty->description) . "'," . "\n" .
				"					'default_value' => '" . addslashesapostrophe($oProperty->default_value) . "'," . "\n" .
				"					'tag_name' => '" . addslashesapostrophe($oProperty->tag_name) . "'," . "\n" .
				"					'sorting' => " . $oProperty->sorting . ", " . "\n" .
				"					'multiple' => " . $oProperty->multiple . ", " . "\n" .
				"					'image_large_max_width' => " . $oProperty->image_large_max_width . ", " . "\n" .
				"					'image_large_max_height' => " . $oProperty->image_large_max_height . ", " . "\n" .
				"					'image_small_max_width' => " . $oProperty->image_small_max_width . ", " . "\n" .
				"					'image_small_max_height' => " . $oProperty->image_small_max_height . ", " . "\n" .
				"					'hide_small_image' => " . $oProperty->hide_small_image . ", " . "\n" .
				"				)," . "\n";
			}
		}

		$content .= "			)," . "\n";

		$content .= Install::exportFieldValues('informationsystem', $oInformationsystem, $tmpDir);

		$content .= "		)," . "\n";
	}

	$content .= '
);';

$content .= '
// Массив компаний
$aCompaniesi18n = array(' . "\n";

	$aCompanies = $oOldSite->Companies->findAll();
	foreach ($aCompanies as $oCompany)
	{
		$content .= "		{$oCompany->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oCompany->name) . "'," . "\n" .
		"			'description' => '" . addslashesapostrophe($oCompany->description) . "'," . "\n" .
		"			'legal_name' => '" . addslashesapostrophe($oCompany->legal_name) . "'," . "\n" .
		"			'accountant_legal_name' => '" . addslashesapostrophe($oCompany->accountant_legal_name) . "'," . "\n" .
		"			'tin' => '" . addslashesapostrophe($oCompany->tin) . "'," . "\n" .
		"			'kpp' => '" . addslashesapostrophe($oCompany->kpp) . "'," . "\n" .
		"			'psrn' => '" . addslashesapostrophe($oCompany->psrn) . "'," . "\n" .
		"			'okpo' => '" . addslashesapostrophe($oCompany->okpo) . "'," . "\n" .
		"			'okved' => '" . addslashesapostrophe($oCompany->okved) . "'," . "\n";
		// "			'bic' => '" . addslashesapostrophe($oCompany->bic) . "'," . "\n" .
		// "			'current_account' => '" . addslashesapostrophe($oCompany->current_account) . "'," . "\n" .
		// "			'correspondent_account' => '" . addslashesapostrophe($oCompany->correspondent_account) . "'," . "\n" .
		// "			'bank_name' => '" . addslashesapostrophe($oCompany->bank_name) . "'," . "\n" .
		// "			'bank_address' => '" . addslashesapostrophe($oCompany->bank_address) . "'," . "\n";

		$content .= Install::exportFieldValues('company', $oCompany, $tmpDir);

		$content .= "		)," . "\n";
	}

$content .= ');';

$content .= '
// Массив магазинов
$aShopi18n = array(' . "\n";

	$aShops = $oOldSite->Shops->findAll();
	foreach ($aShops as $oShop)
	{
		$content .= "		{$oShop->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oShop->name) . "'," . "\n" .
		"			'dirName' => ''," . "\n" .
		"			'structure_id' => " . $oShop->structure_id . ", " . "\n" .
		"			'shop_company_id' => " . $oShop->shop_company_id . ", " . "\n" .
		"			'shop_currency_id' => " . $oShop->shop_currency_id . ", " . "\n" .
		"			'shop_country_id' => " . $oShop->shop_country_id . ", " . "\n" .
		"			'shop_measure_id' => " . $oShop->shop_measure_id . ", " . "\n" .
		"			'email' => '" . addslashesapostrophe($oShop->email) . "'," . "\n" .
		"			'items_on_page' => " . $oShop->items_on_page . ", " . "\n" .
		"			'items_sorting_field' => " . $oShop->items_sorting_field . ", " . "\n" .
		"			'items_sorting_direction' => " . $oShop->items_sorting_direction . ", " . "\n" .
		"			'groups_sorting_field' => " . $oShop->groups_sorting_field . ", " . "\n" .
		"			'groups_sorting_direction' => " . $oShop->groups_sorting_direction . ", " . "\n" .
		"			'image_large_max_width' => " . $oShop->image_large_max_width . ", " . "\n" .
		"			'image_large_max_height' => " . $oShop->image_large_max_height . ", " . "\n" .
		"			'image_small_max_width' => " . $oShop->image_small_max_width . ", " . "\n" .
		"			'image_small_max_height' => " . $oShop->image_small_max_height . ", " . "\n" .
		"			'group_image_small_max_width' => " . $oShop->group_image_small_max_width . ", " . "\n" .
		"			'group_image_small_max_height' => " . $oShop->group_image_small_max_height . ", " . "\n" .
		"			'group_image_large_max_width' => " . $oShop->group_image_large_max_width . ", " . "\n" .
		"			'group_image_large_max_height' => " . $oShop->group_image_large_max_height . ", " . "\n" .
		"			'producer_image_small_max_width' => " . $oShop->producer_image_small_max_width . ", " . "\n" .
		"			'producer_image_small_max_height' => " . $oShop->producer_image_small_max_height . ", " . "\n" .
		"			'producer_image_large_max_width' => " . $oShop->producer_image_large_max_width . ", " . "\n" .
		"			'producer_image_large_max_height' => " . $oShop->producer_image_large_max_height . ", " . "\n" .
		"			'siteuser_group_id' => " . $oShop->siteuser_group_id . ", " . "\n" .
		"			'typograph_default_items' => " . $oShop->typograph_default_items . ", " . "\n" .
		"			'typograph_default_groups' => " . $oShop->typograph_default_groups . ", " . "\n" .
		"			'send_order_email_admin' => " . $oShop->send_order_email_admin . ", " . "\n" .
		"			'send_order_email_user' => " . $oShop->send_order_email_user . ", " . "\n" .
		"			'comment_active' => " . $oShop->comment_active . ", " . "\n" .
		"			'apply_tags_automatically' => " . $oShop->apply_tags_automatically . ", " . "\n" .
		"			'write_off_paid_items' => " . $oShop->write_off_paid_items . ", " . "\n" .
		"			'change_filename' => " . $oShop->change_filename . ", " . "\n" .
		"			'attach_digital_items' => " . $oShop->attach_digital_items . ", " . "\n" .
		"			'use_captcha' => " . $oShop->use_captcha . ", " . "\n" .
		"			'filter' => " . $oShop->filter . ", " . "\n" .
		"			'filter_mode' => " . $oShop->filter_mode . ", " . "\n" .
		"			'order_admin_subject' => '" . addslashesapostrophe($oShop->order_admin_subject) . "'," . "\n" .
		"			'order_user_subject' => '" . addslashesapostrophe($oShop->order_user_subject) . "'," . "\n" .
		"			'confirm_admin_subject' => '" . addslashesapostrophe($oShop->confirm_admin_subject) . "'," . "\n" .
		"			'confirm_user_subject' => '" . addslashesapostrophe($oShop->confirm_user_subject) . "'," . "\n" .
		"			'cancel_admin_subject' => '" . addslashesapostrophe($oShop->cancel_admin_subject) . "'," . "\n" .
		"			'cancel_user_subject' => '" . addslashesapostrophe($oShop->cancel_user_subject) . "'," . "\n" .
		"			'shop_groups' => array(" . "\n";

		// Группы
		$aShop_Groups = $oShop->Shop_Groups->findAll();
		foreach ($aShop_Groups as $oShop_Group)
		{
			$content .= "				{$oShop_Group->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oShop_Group->name) . "'," . "\n" .
			"					'parent_id' => " . $oShop_Group->parent_id . ", " . "\n" .
			"					'description' => '" . addslashesapostrophe($oShop_Group->description) . "'," . "\n" .
			"					'path' => '" . addslashesapostrophe($oShop_Group->path) . "'," . "\n" .
			"					'sorting' => " . $oShop_Group->sorting . ", " . "\n" .
			"					'active' => " . $oShop_Group->active . ", " . "\n" .
			"					'indexing' => " . $oShop_Group->indexing . ", " . "\n" .
			"					'image_large' => '" . $oShop_Group->image_large . "', " . "\n" .
			"					'image_small' => '" . $oShop_Group->image_small . "', " . "\n" .
			"					'property_values' => array(" . "\n";

			$aPropertyValues = $oShop_Group->getPropertyValues();
			foreach ($aPropertyValues as $oPropertyValue)
			{
				if ($oPropertyValue->Property->type != 2)
				{
					$content .= "						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oPropertyValue->Property->id . ", " . "\n" .
					"							'value' => '" . addslashesapostrophe($oPropertyValue->value) . "'," . "\n" .
					"						)," . "\n";
				}
				else
				{
					$content .= "						// File" . "\n" .
					"						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oPropertyValue->Property->id . ", " . "\n" .
					"							'file' => '" . addslashesapostrophe($oPropertyValue->file) . "', " . "\n" .
					"							'file_small' => '" . addslashesapostrophe($oPropertyValue->file_small) . "', " . "\n" .
					"						)," . "\n";

					if (strlen($oPropertyValue->file_small))
					{
						$sTmpPath = $oPropertyValue->getSmallFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getSmallFileHref());
						}
					}

					if (strlen($oPropertyValue->file))
					{
						$sTmpPath = $oPropertyValue->getLargeFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getLargeFileHref());
						}
					}
				}
			}

			$content .= "					)," . "\n";

			// Вкладки
			$aShop_Tab_Groups = $oShop_Group->Shop_Tab_Groups->findAll(FALSE);
			if (count($aShop_Tab_Groups))
			{
				$content .= "					'shop_tab_groups' => array(" . "\n";

				foreach ($aShop_Tab_Groups as $oShop_Tab_Group)
				{
					if ($oShop_Tab_Group->shop_tab_id)
					{
						$content .= "						{$oShop_Tab_Group->id} => array(" . "\n" .
							"							'shop_tab_id' => " . $oShop_Tab_Group->shop_tab_id . ", " . "\n" .
							"						)," . "\n";

						$content .= Install::exportFieldValues('shop_tab_group', $oShop_Tab_Group, $tmpDir);
					}
				}

				$content .= "					)," . "\n";
			}

			$content .= Install::exportFieldValues('shop_group', $oShop_Group, $tmpDir);

			$content .= "				)," . "\n";

			if (strlen($oShop_Group->image_small))
			{
				$sTmpPath = $oShop_Group->getSmallFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oShop_Group->getSmallFileHref());
				}
			}

			if (strlen($oShop_Group->image_large))
			{
				$sTmpPath = $oShop_Group->getLargeFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oShop_Group->getLargeFileHref());
				}
			}
		}

		$content .= "			)," . "\n";

		//Элементы
		$content .= "			'shop_items' => array(" . "\n";

		$oShop_Items = $oShop->Shop_Items;
		$oShop_Items->queryBuilder()
			->clearOrderBy()
			->orderBy('shop_items.id', 'ASC');

		$aShop_Items = $oShop_Items->findAll(FALSE);
		foreach ($aShop_Items as $oShop_Item)
		{
			$content .= "				{$oShop_Item->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oShop_Item->name) . "'," . "\n" .
			"					'shortcut_id' => " . $oShop_Item->shortcut_id . ", " . "\n" .
			"					'shop_tax_id' => " . $oShop_Item->shop_tax_id . ", " . "\n" .
			"					'shop_seller_id' => " . $oShop_Item->shop_seller_id . ", " . "\n" .
			"					'shop_currency_id' => " . $oShop_Item->shop_currency_id . ", " . "\n" .
			"					'shop_producer_id' => " . $oShop_Item->shop_producer_id . ", " . "\n" .
			"					'shop_measure_id' => " . $oShop_Item->shop_measure_id . ", " . "\n" .
			"					'shop_group_id' => " . $oShop_Item->shop_group_id . ", " . "\n" .
			"					'type' => '" . $oShop_Item->type . "'," . "\n" .
			"					'marking' => '" . addslashesapostrophe($oShop_Item->marking) . "'," . "\n" .
			"					'description' => '" . addslashesapostrophe($oShop_Item->description) . "'," . "\n" .
			"					'text' => '" . addslashesapostrophe($oShop_Item->text) . "'," . "\n" .
			"					'price' => '" . addslashesapostrophe($oShop_Item->price) . "'," . "\n" .
			"					'path' => '" . addslashesapostrophe($oShop_Item->path) . "'," . "\n" .
			"					'weight' => '" . $oShop_Item->weight . "'," . "\n" .
			"					'length' => '" . $oShop_Item->length . "'," . "\n" .
			"					'width' => '" . $oShop_Item->width . "'," . "\n" .
			"					'height' => '" . $oShop_Item->height . "'," . "\n" .
			"					'sorting' => " . $oShop_Item->sorting . ", " . "\n" .
			"					'active' => " . $oShop_Item->active . ", " . "\n" .
			"					'indexing' => " . $oShop_Item->indexing . ", " . "\n" .
			"					'image_large' => '" . $oShop_Item->image_large . "', " . "\n" .
			"					'image_small' => '" . $oShop_Item->image_small . "', " . "\n" .
			"					'modification_id' => " . $oShop_Item->modification_id . ", " . "\n" .
			"					'tags' => '" . Install::getShopTags($oShop_Item) . "'," . "\n" .
			"					'property_values' => array(" . "\n";

			$aPropertyValues = $oShop_Item->getPropertyValues();
			foreach ($aPropertyValues as $oPropertyValue)
			{
				if ($oPropertyValue->Property->type != 2)
				{
					$content .= "						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oPropertyValue->Property->id . ", " . "\n" .
					"							'value' => '" . addslashesapostrophe($oPropertyValue->value) . "'," . "\n" .
					"						)," . "\n";
				}
				else
				{
					$content .= "						// File" . "\n" .
					"						{$oPropertyValue->id} => array(" . "\n" .
					"							'property_id' => " . $oPropertyValue->Property->id . ", " . "\n" .
					"							'file' => '" . addslashesapostrophe($oPropertyValue->file) . "', " . "\n" .
					"							'file_small' => '" . addslashesapostrophe($oPropertyValue->file_small) . "', " . "\n" .
					"						)," . "\n";

					if (strlen($oPropertyValue->file_small))
					{
						$sTmpPath = $oPropertyValue->getSmallFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getSmallFileHref());
						}
					}

					if (strlen($oPropertyValue->file))
					{
						$sTmpPath = $oPropertyValue->getLargeFilePath();

						if (is_file($sTmpPath))
						{
							Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oPropertyValue->getLargeFileHref());
						}
					}
				}
			}

			$content .= "					)," . "\n";

			// Комментарии
			$content .= "					'comments' => array(" . "\n";

			$aComments = $oShop_Item->Comments->findAll(FALSE);
			foreach ($aComments as $oComment)
			{
					$content .= "						array(" . "\n" .
					"							'parent_id' => " . $oComment->parent_id . ", " . "\n" .
					"							'subject' => '" . addslashesapostrophe($oComment->subject) . "'," . "\n" .
					"							'text' => '" . addslashesapostrophe($oComment->text) . "'," . "\n" .
					"							'author' => '" . addslashesapostrophe($oComment->author) . "'," . "\n" .
					"							'email' => '" . addslashesapostrophe($oComment->email) . "'," . "\n" .
					"							'phone' => '" . addslashesapostrophe($oComment->phone) . "'," . "\n" .
					"							'active' => " . $oComment->active . ", " . "\n" .
					"							'grade' => " . $oComment->grade . ", " . "\n";

					$content .= Install::exportFieldValues('comment', $oComment, $tmpDir);

					$content .= "						)," . "\n";
			}

			$content .= "					)," . "\n";

			// Скидки товаров
			$content .= "					'discounts' => array(" . "\n";

			$aShop_Item_Discounts = $oShop_Item->Shop_Item_Discounts->findAll(FALSE);
			foreach ($aShop_Item_Discounts as $oShop_Item_Discount)
			{
				$content .= "						{$oShop_Item_Discount->id} => array(" . "\n" .
					"							'shop_discount_id' => " . $oShop_Item_Discount->shop_discount_id . ", " . "\n" .
					"						)," . "\n";
			}

			$content .= "					)," . "\n";

			// Бонусы
			$content .= "					'bonuses' => array(" . "\n";

			$aShop_Item_Bonuses = $oShop_Item->Shop_Item_Bonuses->findAll(FALSE);
			foreach ($aShop_Item_Bonuses as $oShop_Item_Bonus)
			{
				$content .= "						{$oShop_Item_Bonus->id} => array(" . "\n" .
					"							'shop_bonus_id' => " . $oShop_Item_Bonus->shop_bonus_id . ", " . "\n" .
					"						)," . "\n";
			}

			$content .= "					)," . "\n";

			$content .= "					'warehouses' => array(" . "\n";

			// Склады
			$aShop_Warehouse_Items = $oShop_Item->Shop_Warehouse_Items->findAll(FALSE);
			foreach ($aShop_Warehouse_Items as $oShop_Warehouse_Item)
			{
				$content .= "						{$oShop_Warehouse_Item->id} => array(" . "\n" .
					"							'shop_warehouse_id' => " . $oShop_Warehouse_Item->shop_warehouse_id . ", " . "\n" .
					"							'count' => " . $oShop_Warehouse_Item->count . ", " . "\n" .
					"						)," . "\n";
			}

			$content .= "					)," . "\n";

			$content .= "					'associateds' => array(" . "\n";

			// Сопутствующие товары
			$aShop_Item_Associateds = $oShop_Item->Shop_Item_Associateds->findAll(FALSE);
			foreach ($aShop_Item_Associateds as $oShop_Item_Associated)
			{
				$content .= "						{$oShop_Item_Associated->id} => array(" . "\n" .
					"							'shop_item_associated_id' => " . $oShop_Item_Associated->shop_item_associated_id . ", " . "\n" .
					"							'count' => " . $oShop_Item_Associated->count . ", " . "\n" .
					"						)," . "\n";
			}

			$content .= "					)," . "\n";

			// Комплекты
			if ($oShop_Item->type == 3)
			{
				$content .= "					'sets' => array(" . "\n";

				$aShop_Item_Sets = $oShop_Item->Shop_Item_Sets->findAll(FALSE);
				foreach ($aShop_Item_Sets as $oShop_Item_Set)
				{
					$content .= "						{$oShop_Item_Set->id} => array(" . "\n" .
						"							'shop_item_set_id' => " . $oShop_Item_Set->shop_item_set_id . ", " . "\n" .
						"							'count' => " . $oShop_Item_Set->count . ", " . "\n" .
						"						)," . "\n";
				}

				$content .= "					)," . "\n";
			}

			// Вкладки
			$aShop_Tab_Items = $oShop_Item->Shop_Tab_Items->findAll(FALSE);
			if (count($aShop_Tab_Items))
			{
				$content .= "					'shop_tab_items' => array(" . "\n";

				foreach ($aShop_Tab_Items as $oShop_Tab_Item)
				{
					if ($oShop_Tab_Item->shop_tab_id)
					{
						$content .= "						{$oShop_Tab_Item->id} => array(" . "\n" .
							"							'shop_tab_id' => " . $oShop_Tab_Item->shop_tab_id . ", " . "\n" .
							"						)," . "\n";
					}
				}

				$content .= "					)," . "\n";
			}

			$content .= "				)," . "\n";

			if (strlen($oShop_Item->image_small))
			{
				$sTmpPath = $oShop_Item->getSmallFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oShop_Item->getSmallFileHref());
				}
			}

			if (strlen($oShop_Item->image_large))
			{
				$sTmpPath = $oShop_Item->getLargeFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oShop_Item->getLargeFileHref());
				}
			}
		}

		$content .= "			)," . "\n";

		//Элементы
		$content .= "			'shop_tabs' => array(" . "\n";

		$oShop_Tabs = $oShop->Shop_Tabs;
		$oShop_Tabs->queryBuilder()
			->clearOrderBy()
			->orderBy('shop_tabs.id', 'ASC');

		$aShop_Tabs = $oShop_Tabs->findAll(FALSE);
		foreach ($aShop_Tabs as $oShop_Tab)
		{
			$content .= "				{$oShop_Tab->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oShop_Tab->name) . "'," . "\n" .
			"					'dirName' => '" . Install::getShopTabDirName($oShop_Tab) ."'," . "\n" .
			"					'caption' => '" . addslashesapostrophe($oShop_Tab->caption) . "'," . "\n" .
			"					'text' => '" . addslashesapostrophe($oShop_Tab->text) . "'," . "\n" .
			"					'icon' => '" . addslashesapostrophe($oShop_Tab->icon) . "'," . "\n" .
			"					'color' => '" . addslashesapostrophe($oShop_Tab->color) . "'," . "\n" .
			"					'sorting' => '" . $oShop_Tab->sorting . "'," . "\n";

			$content .= Install::exportFieldValues('shop_tab', $oShop_Tab, $tmpDir);

			$content .= "				)," . "\n";
		}

		$content .= "			)," . "\n";

		// Свойства
		$content .= "			'properties' => array(" . "\n";

		$aShop_Item_Properties = $oShop->Shop_Item_Properties->findAll();
		foreach ($aShop_Item_Properties as $oShop_Item_Property)
		{
			$oProperty = $oShop_Item_Property->Property;

			if ($oProperty->id)
			{
				$content .= "				{$oProperty->id} => array(" . "\n" .
				"					'name' => '" . addslashesapostrophe($oProperty->name) . "'," . "\n" .
				"					'dirName' => '" . Install::getPropertyDirName($oProperty) ."'," . "\n" .
				"					'type' => '" . $oProperty->type . "'," . "\n" .
				"					'description' => '" . addslashesapostrophe($oProperty->description) . "'," . "\n" .
				"					'default_value' => '" . addslashesapostrophe($oProperty->default_value) . "'," . "\n" .
				"					'tag_name' => '" . addslashesapostrophe($oProperty->tag_name) . "'," . "\n" .
				"					'sorting' => " . $oProperty->sorting . ", " . "\n" .
				"					'list_id' => " . $oProperty->list_id . ", " . "\n" .
				"					'multiple' => " . $oProperty->multiple . ", " . "\n" .
				"					'prefix' => '" . addslashesapostrophe($oShop_Item_Property->prefix) . "', " . "\n" .
				"					'filter' => " . $oShop_Item_Property->filter . ", " . "\n" .
				"					'image_large_max_width' => " . $oProperty->image_large_max_width . ", " . "\n" .
				"					'image_large_max_height' => " . $oProperty->image_large_max_height . ", " . "\n" .
				"					'image_small_max_width' => " . $oProperty->image_small_max_width . ", " . "\n" .
				"					'image_small_max_height' => " . $oProperty->image_small_max_height . ", " . "\n" .
				"					'hide_small_image' => " . $oProperty->hide_small_image . ", " . "\n" .
				"					'show_in_group' => " . $oShop_Item_Property->show_in_group . ", " . "\n" .
				"					'show_in_item' => " . $oShop_Item_Property->show_in_item . ", " . "\n" .
				"					'shop_group_id' => array(";

				$aShop_Item_Property_For_Groups = $oShop_Item_Property->Shop_Item_Property_For_Groups->findAll(FALSE);

				$aTmp = array();
				foreach ($aShop_Item_Property_For_Groups as $oShop_Item_Property_For_Group)
				{
					$aTmp[] = $oShop_Item_Property_For_Group->shop_group_id;
				}

				$content .= implode(', ', $aTmp) . "), " . "\n" .
				"				)," . "\n";
			}
		}

		$content .= "			)," . "\n";

		// Свойства групп
		$content .= "			'group_properties' => array(" . "\n";

		$aShop_Group_Properties = $oShop->Shop_Group_Properties->findAll();
		foreach ($aShop_Group_Properties as $oShop_Group_Property)
		{
			$oProperty = $oShop_Group_Property->Property;

			if ($oProperty->id)
			{
				$content .= "				{$oProperty->id} => array(" . "\n" .
				"					'name' => '" . addslashesapostrophe($oProperty->name) . "'," . "\n" .
				"					'dirName' => '" . Install::getPropertyDirName($oProperty) ."'," . "\n" .
				"					'type' => '" . $oProperty->type . "'," . "\n" .
				"					'description' => '" . addslashesapostrophe($oProperty->description) . "'," . "\n" .
				"					'default_value' => '" . addslashesapostrophe($oProperty->default_value) . "'," . "\n" .
				"					'tag_name' => '" . addslashesapostrophe($oProperty->tag_name) . "'," . "\n" .
				"					'sorting' => " . $oProperty->sorting . ", " . "\n" .
				"					'multiple' => " . $oProperty->multiple . ", " . "\n" .
				"					'image_large_max_width' => " . $oProperty->image_large_max_width . ", " . "\n" .
				"					'image_large_max_height' => " . $oProperty->image_large_max_height . ", " . "\n" .
				"					'image_small_max_width' => " . $oProperty->image_small_max_width . ", " . "\n" .
				"					'image_small_max_height' => " . $oProperty->image_small_max_height . ", " . "\n" .
				"					'hide_small_image' => " . $oProperty->hide_small_image . ", " . "\n" .
				"				)," . "\n";
			}
		}

		$content .= "			)," . "\n";

		// Склады
		$content .= "			'shop_warehouses' => array(" . "\n";

		$aShop_Warehouses = $oShop->Shop_Warehouses->findAll();
		foreach ($aShop_Warehouses as $oShop_Warehouse)
		{
			$content .= "				{$oShop_Warehouse->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oShop_Warehouse->name) . "'," . "\n" .
			"					'sorting' => " . $oShop_Warehouse->sorting . ", " . "\n" .
			"					'active' => " . $oShop_Warehouse->active . ", " . "\n" .
			"					'default' => " . $oShop_Warehouse->default . ", " . "\n";

			$content .= Install::exportFieldValues('shop_warehouse', $oShop_Warehouse, $tmpDir);

			$content .= "				)," . "\n";
		}

		$content .= "			)," . "\n";

		// Производители
		$content .= "			'shop_producers' => array(" . "\n";

		$aShop_Producers = $oShop->Shop_Producers->findAll();
		foreach ($aShop_Producers as $oShop_Producer)
		{
			$content .= "				{$oShop_Producer->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oShop_Producer->name) . "'," . "\n" .
			"					'sorting' => " . $oShop_Producer->sorting . ", " . "\n" .
			"					'active' => " . $oShop_Producer->active . ", " . "\n" .
			"					'default' => " . $oShop_Producer->default . ", " . "\n";

			$content .= Install::exportFieldValues('shop_producer', $oShop_Producer, $tmpDir);

			$content .= "				)," . "\n";

			if (strlen($oShop_Producer->image_small))
			{
				$sTmpPath = $oShop_Producer->getSmallFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oShop_Producer->getSmallFileHref());
				}
			}

			if (strlen($oShop_Producer->image_large))
			{
				$sTmpPath = $oShop_Producer->getLargeFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oShop_Producer->getLargeFileHref());
				}
			}
		}

		$content .= "			)," . "\n";

		// Скидки
		$content .= "			'shop_discounts' => array(" . "\n";

		$aShop_Discounts = $oShop->Shop_Discounts->findAll();
		foreach ($aShop_Discounts as $oShop_Discount)
		{
			$content .= "				{$oShop_Discount->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oShop_Discount->name) . "'," . "\n" .
			"					'start_datetime' => '" . $oShop_Discount->start_datetime . "'," . "\n" .
			"					'end_datetime' => '" . $oShop_Discount->end_datetime . "'," . "\n" .
			"					'active' => " . $oShop_Discount->active . ", " . "\n" .
			"					'value' => " . $oShop_Discount->value . ", " . "\n" .
			"					'type' => " . $oShop_Discount->type . ", " . "\n";

			$aShop_Discount_Siteuser_Groups = $oShop_Discount->Shop_Discount_Siteuser_Groups->findAll();

			if (count($aShop_Discount_Siteuser_Groups))
			{
				$aTmp = array();
				foreach ($aShop_Discount_Siteuser_Groups as $oShop_Discount_Siteuser_Group)
				{
					$aTmp[] = $oShop_Discount_Siteuser_Group->siteuser_group_id;
				}

				$content .= "					'siteuser_groups' => array(" . implode(',', $aTmp) . ")," . "\n";
			}

			$content .= Install::exportFieldValues('shop_discount', $oShop_Discount, $tmpDir);

			$content .= "				)," . "\n";
		}

		$content .= "			)," . "\n";

		// Бонусы
		$content .= "			'shop_bonuses' => array(" . "\n";

		$aShop_Bonuses = $oShop->Shop_Bonuses->findAll();
		foreach ($aShop_Bonuses as $oShop_Bonus)
		{
			$content .= "				{$oShop_Bonus->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oShop_Bonus->name) . "'," . "\n" .
			"					'start_datetime' => '" . $oShop_Bonus->start_datetime . "'," . "\n" .
			"					'end_datetime' => '" . $oShop_Bonus->end_datetime . "'," . "\n" .
			"					'active' => " . $oShop_Bonus->active . ", " . "\n" .
			"					'value' => " . $oShop_Bonus->value . ", " . "\n" .
			"					'type' => " . $oShop_Bonus->type . ", " . "\n";

			$content .= Install::exportFieldValues('shop_bonus', $oShop_Bonus, $tmpDir);

			$content .= "				)," . "\n";
		}

		$content .= "			)," . "\n";

		// Платежные системы
		$content .= "			'shop_payment_systems' => array(" . "\n";

		$aShop_Payment_Systems = $oShop->Shop_Payment_Systems->findAll();
		foreach ($aShop_Payment_Systems as $oShop_Payment_System)
		{
			// Указано включать в файл
			if (!is_null(Core_Array::getPost('payment_system_' . $oShop_Payment_System->id)))
			{
				$content .= "				{$oShop_Payment_System->id} => array(" . "\n" .
				"					'shop_currency_id' => " . $oShop_Payment_System->shop_currency_id . ", " . "\n" .
				"					'name' => '" . addslashesapostrophe($oShop_Payment_System->name) . "'," . "\n" .
				"					'sorting' => " . $oShop_Payment_System->sorting . ", " . "\n" .
				"					'description' => '" . addslashesapostrophe($oShop_Payment_System->description) . "'," . "\n" .
				"					'image' => '" . $oShop_Payment_System->image . "', " . "\n" .
				"					'image_height' => " . $oShop_Payment_System->image_height . ", " . "\n" .
				"					'image_width' => " . $oShop_Payment_System->image_width . ", " . "\n" .
				"					'active' => " . $oShop_Payment_System->active . ", " . "\n";

				$content .= Install::exportFieldValues('shop_payment_system', $oShop_Payment_System, $tmpDir);

				$content .= "				)," . "\n";

				if (is_file($oShop_Payment_System->getPaymentSystemFilePath()))
				{
					Core_File::copy($oShop_Payment_System->getPaymentSystemFilePath(), $tmpDir . 'hostcmsfiles/shop/pay/handler' . $oShop_Payment_System->id . '.php');
				}
				else
				{
					$aMessages[] = array('type' => 'warning', 'text' => "Предупреждение: Для платежной системы '{$oShop_Payment_System->name}' (id {$oShop_Payment_System->id}) отсутствует .php-файл");
				}

				if (strlen($oShop_Payment_System->image))
				{
					$sTmpPath = $oShop_Payment_System->getPaymentSystemImageFilePath();

					if (is_file($sTmpPath))
					{
						Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oShop_Payment_System->getPaymentSystemImageFileHref());
					}
				}
			}
		}

		$content .= "			),\n		),\n";
	}

	$content .= '
);

// Валюты
$aShopCurrencies = array(' . "\n";
	$aShop_Currencies = Core_Entity::factory('Shop_Currency')->findAll();
	foreach ($aShop_Currencies as $oShop_Currency)
	{
		$content .= "	{$oShop_Currency->id} => array(" . "\n" .
		"		'name' => '" . addslashesapostrophe($oShop_Currency->name) . "'," . "\n" .
		"		'code' => '" . addslashesapostrophe($oShop_Currency->code) . "'," . "\n" .
		"		'exchange_rate' => '" . $oShop_Currency->exchange_rate . "'," . "\n" .
		"		'default' => " . $oShop_Currency->default . ", " . "\n" .
		"		'sorting' => " . $oShop_Currency->sorting . ", " . "\n";

		$content .= Install::exportFieldValues('shop_currency', $oShop_Currency, $tmpDir);

		$content .= "	),\n";
	}

$content .= ');' . "\n";

$content .= '
// Массив узлов структуры
$aStructurei18n = array(' . "\n";

$content .= Install::fillStructures($oOldSite->id, $tmpDir);

$content .= ');';

if (Core::moduleIsActive('forum'))
{
$content .= '

// Массив форумов
$aForumi18n = array(' . "\n";

	$aForums = $oOldSite->Forums->findAll();

	foreach ($aForums as $oForum)
	{
		$content .= "		{$oForum->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oForum->name) . "'," . "\n" .
		"			'structure_id' => " . $oForum->structure_id . ", " . "\n" .
		"			'description' => '" . addslashesapostrophe($oForum->description) . "'," . "\n" .
		"			'topics_on_page' => " . $oForum->topics_on_page . ", " . "\n" .
		"			'posts_on_page' => " . $oForum->posts_on_page . ", " . "\n" .
		"			'flood_protection_time' => " . $oForum->flood_protection_time . ", " . "\n" .
		"			'allow_edit_time' => " . $oForum->allow_edit_time . ", " . "\n" .
		"			'allow_delete_time' => " . $oForum->allow_delete_time . ", " . "\n" .
		"			'forum_groups' => array(" . "\n";

		$aForum_Groups = $oForum->Forum_Groups->findAll();
		foreach ($aForum_Groups as $oForum_Group)
		{
			$content .= "				{$oForum_Group->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oForum_Group->name) . "'," . "\n" .
			"					'description' => '" . addslashesapostrophe($oForum_Group->description) . "'," . "\n" .
			"					'sorting' => " . $oForum_Group->sorting . ", " . "\n" .
			"					'forum_categories' => array(" . "\n";

			$aForum_Categories = $oForum_Group->Forum_Categories->findAll();
			foreach ($aForum_Categories as $oForum_Category)
			{
				$content .= "						{$oForum_Category->id} => array(" . "\n" .
				"							'name' => '" . addslashesapostrophe($oForum_Category->name) . "'," . "\n" .
				"							'description' => '" . addslashesapostrophe($oForum_Category->description) . "'," . "\n" .
				"							'closed' => " . $oForum_Category->closed . ", " . "\n" .
				"							'sorting' => " . $oForum_Category->sorting . ", " . "\n" .
				"							'email' => '" . addslashesapostrophe($oForum_Category->email) . "'," . "\n" .
				"							'postmoderation' => " . $oForum_Category->postmoderation . ", " . "\n" .
				"							'visible' => " . $oForum_Category->visible . ", " . "\n" .
				"							'use_captcha' => " . $oForum_Category->use_captcha . ", " . "\n" .
				"							'allow_guest_posting' => " . $oForum_Category->allow_guest_posting . ", " . "\n" .
				"							'forum_topics' => array(" . "\n";

				$aForum_Topics = $oForum_Category->Forum_Topics->findAll();
				foreach ($aForum_Topics as $oForum_Topic)
				{
					$content .= "								{$oForum_Topic->id} => array(" . "\n" .
					"									'visible' => " . $oForum_Topic->visible . ", " . "\n" .
					"									'announcement' => " . $oForum_Topic->announcement . ", " . "\n" .
					"									'closed' => " . $oForum_Topic->closed . ", " . "\n";

					$content .= Install::exportFieldValues('forum_topic', $oForum_Topic, $tmpDir);

					$content .= "								)," . "\n";
				}

				$content .= "							)," . "\n";

				$content .= Install::exportFieldValues('forum_category', $oForum_Category, $tmpDir);

				$content .= "						),\n";
			}

			$content .= "					)," . "\n";

			$content .= Install::exportFieldValues('forum_group', $oForum_Group, $tmpDir);

			$content .= "				),\n";
		}

		$content .= "			)," . "\n";

		$content .= Install::exportFieldValues('forum', $oForum, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);';
}

if (Core::moduleIsActive('helpdesk'))
{
	$content .= '

// Массив служб поддержки
$aHelpdeski18n = array(' . "\n";

	$aHelpdesks = $oOldSite->Helpdesks->findAll();
	foreach ($aHelpdesks as $oHelpdesk)
	{
		$content .= "		{$oHelpdesk->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oHelpdesk->name) . "'," . "\n" .
		"			'structure_id' => " . $oHelpdesk->structure_id . ", " . "\n" .
		"			'notify_change_criticality_level' => " . $oHelpdesk->notify_change_criticality_level . ", " . "\n" .
		"			'notify' => " . $oHelpdesk->notify . ", " . "\n" .
		"			'delete_attach_in_days' => " . $oHelpdesk->delete_attach_in_days . ", " . "\n";

		$content .= Install::exportFieldValues('helpdesk', $oHelpdesk, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);
';
}

if (Core::moduleIsActive('advertisement'))
{
	$content .= '
// Массив групп баннеров
$aAdvertisementGroupi18n = array(' . "\n";

	$aAdvertisement_Groups = $oOldSite->Advertisement_Groups->findAll();
	foreach ($aAdvertisement_Groups as $oAdvertisement_Group)
	{
		$content .= "		{$oAdvertisement_Group->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oAdvertisement_Group->name) . "'," . "\n" .
		"			'description' => '" . addslashesapostrophe($oAdvertisement_Group->description) . "'," . "\n" .
		"			'advertisement' => array(" . "\n";

		$aAdvertisements = $oAdvertisement_Group->Advertisements->findAll();
		foreach ($aAdvertisements as $oAdvertisement)
		{
			$content .= "				{$oAdvertisement->id} => array(" . "\n" .
			"					'name' => '" . addslashesapostrophe($oAdvertisement->name) . "'," . "\n" .
			"					'description' => '" . addslashesapostrophe($oAdvertisement->description) . "'," . "\n" .
			"					'type' => " . $oAdvertisement->type . ", " . "\n" .
			"					'file_name' => '" . addslashesapostrophe($oAdvertisement->source) . "'," . "\n" .
			"					'href' => '" . addslashesapostrophe($oAdvertisement->href) . "'," . "\n";

			$content .= Install::exportFieldValues('advertisement', $oAdvertisement, $tmpDir);

			$content .= "				)," . "\n";

			if (strlen($oAdvertisement->source))
			{
				$sTmpPath = $oAdvertisement->getFilePath();

				if (is_file($sTmpPath))
				{
					Core_File::copy($sTmpPath, rtrim($tmpDir, '/') . $oAdvertisement->getFileHref());
				}
			}
		}

		$content .= "			)," . "\n";

		$content .= Install::exportFieldValues('advertisement_group', $oAdvertisement_Group, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);
';
}

if (Core::moduleIsActive('siteuser'))
{
	$content .= '

// Группы пользователей сайта
$aSiteuserGroupsi18n = array(' . "\n";

	$aSiteuser_Groups = $oOldSite->Siteuser_Groups->findAll();
	foreach ($aSiteuser_Groups as $oSiteuser_Group)
	{
		$content .= "		{$oSiteuser_Group->id} => array(" . "\n" .
		"			'name' => '" . addslashesapostrophe($oSiteuser_Group->name) . "'," . "\n" .
		"			'description' => '" . addslashesapostrophe($oSiteuser_Group->description) . "'," . "\n" .
		"			'default' => " . $oSiteuser_Group->default . ", " . "\n";

		$content .= Install::exportFieldValues('siteuser_group', $oSiteuser_Group, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);
';

	$content .= '

//Пользователи сайта
$aSiteuseri18n = array(' . "\n";

	$aSiteusers = $oOldSite->Siteusers->findAll();
	foreach ($aSiteusers as $oSiteuser)
	{
		$aSiteuser_GroupIDs = array();
		$aSiteuser_Groups = $oSiteuser->Siteuser_Groups->findAll(FALSE);
		foreach ($aSiteuser_Groups as $oSiteuser_Group)
		{
			$aSiteuser_GroupIDs[] = $oSiteuser_Group->id;
		}

		$content .= "		{$oSiteuser->id} => array(" . "\n" .
		"			'login' => '" . addslashesapostrophe($oSiteuser->login) . "'," . "\n" .
		"			'password' => '" . addslashesapostrophe($oSiteuser->password) . "'," . "\n" .
		"			'email' => '" . addslashesapostrophe($oSiteuser->email) . "'," . "\n" .
		"			'active' => " . $oSiteuser->active . ", " . "\n" .
		"			'name' => '" . addslashesapostrophe($oSiteuser->name) . "'," . "\n" .
		"			'surname' => '" . addslashesapostrophe($oSiteuser->surname) . "'," . "\n" .
		"			'patronymic' => '" . addslashesapostrophe($oSiteuser->patronymic) . "'," . "\n" .
		"			'company' => '" . addslashesapostrophe($oSiteuser->company) . "'," . "\n" .
		"			'phone' => '" . addslashesapostrophe($oSiteuser->phone) . "'," . "\n" .
		"			'website' => '" . addslashesapostrophe($oSiteuser->website) . "'," . "\n" .
		"			'country' => '" . addslashesapostrophe($oSiteuser->country) . "'," . "\n" .
		"			'city' => '" . addslashesapostrophe($oSiteuser->city) . "'," . "\n" .
		"			'address' => '" . addslashesapostrophe($oSiteuser->address) . "'," . "\n" .
		"			'siteuser_group_id' => array(" . implode(', ', $aSiteuser_GroupIDs) . ")," . "\n";

		$content .= Install::exportFieldValues('siteuser', $oSiteuser, $tmpDir);

		$content .= "		),\n";
	}

	$content .= '
);
';
}

if (count(Install::$aFieldIDs))
{
	$content .= '
$aFieldsi18n = array(' . "\n";

	$content .= Install::exportFields();

	$content .= '
);
';
}

$aFiles = Install::getArrayOfFiles();
if (count($aFiles))
{
	foreach ($aFiles as $sFile)
	{
		try {
			if (is_file(CMS_FOLDER . $sFile))
			{
				Core_File::mkdir($filesDir . dirname($sFile), CHMOD, TRUE);
				Core_File::copy(CMS_FOLDER . $sFile, $filesDir . $sFile);
			}
		} catch (Exception $ex) {}
	}
}

if (count(Install::$aFieldIDs))
{
	$content .= '
	// Пользовательские поля
	foreach ($aFieldsi18n as $iFieldId => $aField)
	{
		if (isset($aField[\'tag_name\']) && $aField[\'tag_name\'] != \'\')
		{
			$oField = Core_Entity::factory(\'Field\')->getByTag_name($aField[\'tag_name\'], FALSE);

			if (is_null($oField))
			{
				$aExplodeDir = explode(\'/\', $aField[\'dirName\']);
				// array_unshift($aExplodeDir, $sSitePostfix);

				$iParent_Id = 0;
				foreach ($aExplodeDir as $sDirName)
				{
					if ($sDirName != \'\')
					{
						$oField_Dir = Core_Entity::factory(\'Field_Dir\');
						$oField_Dir
							->queryBuilder()
							->where(\'field_dirs.parent_id\', \'=\', $iParent_Id);

						$oField_Dir = $oField_Dir->getByName($sDirName, FALSE);

						if (is_null($oField_Dir))
						{
							$oField_Dir = Core_Entity::factory(\'Field_Dir\');
							$oField_Dir
								->parent_id($iParent_Id)
								->model(Core_Array::get($aField, \'model\', \'\'))
								->name($sDirName)
								->sorting(0)
								->save();
						}

						$iParent_Id = $oField_Dir->id;
					}
				}

				$oField = Core_Entity::factory(\'Field\');
				$oField
					->name(Core_Array::get($aField, \'name\', Core_Guid::get()))
					->field_dir_id($iParent_Id)
					->model(Core_Array::get($aField, \'model\', \'\'))
					->site_id(0)
					->list_id(Core_Array::get($aField, \'list_id\', 0))
					->informationsystem_id(Core_Array::get($aField, \'informationsystem_id\', 0))
					->shop_id(Core_Array::get($aField, \'shop_id\', 0))
					->default_value(Core_Array::get($aField, \'default_value\', \'\'))
					->tag_name(Core_Array::get($aField, \'tag_name\', Core_Guid::get()))
					->description(Core_Array::get($aField, \'description\', \'\'))
					->type(Core_Array::get($aField, \'type\', 0))
					->sorting(Core_Array::get($aField, \'sorting\', 0))
					->visible(Core_Array::get($aField, \'visible\', 1))
					->image_large_max_width(Core_Array::get($aField, \'image_large_max_width\', 300))
					->image_large_max_height(Core_Array::get($aField, \'image_large_max_height\', 300))
					->image_small_max_width(Core_Array::get($aField, \'image_small_max_width\', 70))
					->image_small_max_height(Core_Array::get($aField, \'image_small_max_height\', 70))
					->hide_small_image(Core_Array::get($aField, \'hide_small_image\', 0))
					->preserve_aspect_ratio(Core_Array::get($aField, \'preserve_aspect_ratio\', 1))
					->preserve_aspect_ratio_small(Core_Array::get($aField, \'preserve_aspect_ratio_small\', 1))
					->change_filename(Core_Array::get($aField, \'change_filename\', 0))
					->multiple(Core_Array::get($aField, \'multiple\', 0))
					->obligatory(Core_Array::get($aField, \'obligatory\', 0))
					->save();
			}

			CT::$aAssosiatedFields[$iFieldId] = $oField->id;
		}
	}
	unset($aFieldsi18n);';
}

$content .= '
// Создаем сайт
$oSite = Core_Entity::factory(\'Site\');
$oSite
	->name("{$aSitei18n[\'name\']} {$sCurrentDate}")
	->admin_email($sCompanyEmail)
	->lng(CT::$installLng)
	->error403($aSitei18n[\'error403\'])
	->error404($aSitei18n[\'error404\'])
	->closed($aSitei18n[\'closed\'])
	->save();

if (isset($aSitei18n[\'favicons\']))
{
	foreach ($aSitei18n[\'favicons\'] as $iFaviconId => $aFavicon)
	{
		try {
			$oSite_Favicon = Core_Entity::factory(\'Site_Favicon\');
			$oSite_Favicon->site_id = $oSite->id;
			$oSite_Favicon->rel = $aFavicon[\'rel\'];
			$oSite_Favicon->sizes = $aFavicon[\'sizes\'];
			$oSite_Favicon->save();

			$oSite_Favicon->saveFavicon($aFavicon[\'filename\'], $tmpDir . "tmp/upload/favicon/" . $aFavicon[\'filename\']);
		}
		catch (Exception $e) {
			Core_Message::show($e->getMessage(), "error");
		}
	}
}

$sSitePostfix = sprintf($aSitei18n[\'sitePostfix\'], $oSite->id);

if (isset($aSitei18n[\'properties\']))
{
	foreach ($aSitei18n[\'properties\'] as $iPropertyId => $aStructureProperty)
	{
		$aExplodeDir = explode(\'/\', $aStructureProperty[\'dirName\']);
		array_unshift($aExplodeDir, $sSitePostfix);

		$iParent_Property_Id = 0;

		foreach ($aExplodeDir as $sDirName)
		{
			if ($sDirName != \'\')
			{
				$oProperty_Dirs = Core_Entity::factory(\'Structure_Property_List\', $oSite->id)
					->Property_Dirs;

				$oProperty_Dirs
					->queryBuilder()
					->where(\'property_dirs.parent_id\', \'=\', $iParent_Property_Id);

				$oProperty_Dir = $oProperty_Dirs->getByName($sDirName, FALSE);

				if (is_null($oProperty_Dir))
				{
					$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
					$oProperty_Dir
						->parent_id($iParent_Property_Id)
						->name($sDirName)
						->save();

					$oStructure_Property_Dir = Core_Entity::factory(\'Structure_Property_Dir\');
					$oStructure_Property_Dir
						->site_id($oSite->id)
						->property_dir_id($oProperty_Dir->id)
						->save();
				}

				$iParent_Property_Id = $oProperty_Dir->id;
			}
		}

		$oProperty = Core_Entity::factory(\'Property\');
		$oProperty
			->property_dir_id($iParent_Property_Id)
			->list_id(Core_Array::get($aStructureProperty, \'list_id\', 0))
			->informationsystem_id(isset($aStructureProperty[\'informationsystem_id\']) ? $aStructureProperty[\'informationsystem_id\'] : 0)
			->shop_id(0)
			->name(Core_Array::get($aStructureProperty, \'name\', Core_Guid::get()))
			->description(Core_Array::get($aStructureProperty, \'description\', \'\'))
			->type($aStructureProperty[\'type\'])
			->default_value(Core_Array::get($aStructureProperty, \'default_value\', \'\'))
			->tag_name(Core_Array::get($aStructureProperty, \'tag_name\', Core_Guid::get()))
			->sorting(Core_Array::get($aStructureProperty, \'sorting\', 0))
			->multiple(Core_Array::get($aStructureProperty, \'multiple\', 0))
			->image_large_max_width(Core_Array::get($aStructureProperty, \'image_large_max_width\', 300))
			->image_large_max_height(Core_Array::get($aStructureProperty, \'image_large_max_height\', 300))
			->image_small_max_width(Core_Array::get($aStructureProperty, \'image_small_max_width\', 70))
			->image_small_max_height(Core_Array::get($aStructureProperty, \'image_small_max_height\', 70))
			->hide_small_image(Core_Array::get($aStructureProperty, \'hide_small_image\', 0))
			->save();

		$oStructure_Property = Core_Entity::factory(\'Structure_Property\');
		$oStructure_Property
			->site_id($oSite->id)
			->property_id($oProperty->id)
			->save();

		CT::$aAssosiatedProperties[$iPropertyId] = $oProperty->id;

		CT::$aReplace["property_id\', \'=\', {$iPropertyId})"]
			=  $aSecondReplace["property_id\', \'=\', {$iPropertyId})"] = "property_id\', \'=\', {$oProperty->id})";

		CT::$aReplace["\'Property\', {$iPropertyId})"] = "\'Property\', " . $oProperty->id . ")";
		CT::$aReplace[\'$property_id = \' . $iPropertyId . \';\']
			= $aSecondReplace[\'$property_id = \' . $iPropertyId . \';\'] = \'$property_id = \' . $oProperty->id . \';\';
	}
}

unset($aSitei18n);

// Constants
foreach ($aConstants as $iConstantId => $aConstant)
{
	$oConstant = Core_Entity::factory(\'Constant\');

	$oConstant = $oConstant->getByName($aConstant[\'name\'], FALSE);

	if (is_null($oConstant))
	{
		$aExplodeDir = explode(\'/\', $aConstant[\'dirName\']);

		$iParent_Id = 0;

		foreach ($aExplodeDir as $sDirName)
		{
			if ($sDirName != \'\')
			{
				$oConstant_Dir = Core_Entity::factory(\'Constant_Dir\');
				$oConstant_Dir
					->queryBuilder()
					->where(\'constant_dirs.parent_id\', \'=\', $iParent_Id);

				$oConstant_Dir = $oConstant_Dir->getByName($sDirName, FALSE);

				if (is_null($oConstant_Dir))
				{
					$oConstant_Dir = Core_Entity::factory(\'Constant_Dir\');
					$oConstant_Dir
						->parent_id($iParent_Id)
						->name($sDirName)
						->save();
				}

				$iParent_Id = $oConstant_Dir->id;
			}
		}

		$oConstant = Core_Entity::factory(\'Constant\');
		$oConstant
			->constant_dir_id($iParent_Id)
			->name($aConstant[\'name\'])
			->value($aConstant[\'value\'])
			->description($aConstant[\'description\'])
			->active($aConstant[\'active\'])
			->save();
	}
}

unset($aConstants);

$aSecondReplace = array();

// Menus
foreach ($aMenui18n as $iMenuId => $aMenu)
{
	$sMenuName = CT::translate($aMenu[\'name\']);

	$oStructure_Menu = Core_Entity::factory(\'Structure_Menu\')->getByName($sMenuName . $sSitePostfix, FALSE);

	if (is_null($oStructure_Menu))
	{
		$oStructure_Menu = Core_Entity::factory(\'Structure_Menu\');
		$oStructure_Menu
			->site_id($oSite->id)
			->name($sMenuName . $sSitePostfix)
			->color($aMenu[\'color\'])
			->sorting($aMenu[\'sorting\'])
			->save();
	}

	CT::$aAssosiatedStructureMenus[$iMenuId] = $oStructure_Menu->id;

	CT::$aReplace["->menu({$iMenuId})"] = "->menu({$oStructure_Menu->id})";
}

unset($aMenui18n);

// Lists
if (Core::moduleIsActive(\'list\'))
{
	foreach ($aListi18n as $iListId => $aList)
	{
		$sListName = CT::translate($aList[\'name\']);

		$aExplodeDir = explode(\'/\', $aList[\'dirName\']);
		// array_unshift($aExplodeDir, $sSitePostfix);

		$iParent_Id = 0;
		foreach ($aExplodeDir as $sDirName)
		{
			if ($sDirName != \'\')
			{
				$oList_Dir = Core_Entity::factory(\'List_Dir\');
				$oList_Dir
					->queryBuilder()
					->where(\'list_dirs.site_id\', \'=\', $oSite->id)
					->where(\'list_dirs.parent_id\', \'=\', $iParent_Id);

				$oList_Dir = $oList_Dir->getByName($sDirName, FALSE);

				if (is_null($oList_Dir))
				{
					$oList_Dir = Core_Entity::factory(\'List_Dir\');
					$oList_Dir
						->parent_id($iParent_Id)
						->site_id($oSite->id)
						->name($sDirName)
						->save();
				}

				$iParent_Id = $oList_Dir->id;
			}
		}

		$oList = Core_Entity::factory(\'List\');
		$oList
			->name($sListName)
			->list_dir_id($iParent_Id)
			->site_id($oSite->id)
			->save();

		if (isset($aList[\'list_items\']))
		{
			foreach ($aList[\'list_items\'] as $iListItemId => $aListItem)
			{
				$oListItem = Core_Entity::factory(\'List_Item\');
				$oListItem
					->list_id($oList->id)
					->value($aListItem[\'value\'])
					->sorting($aListItem[\'sorting\'])
					->description($aListItem[\'description\'])
					->icon($aListItem[\'icon\'])
					->active($aListItem[\'active\']);

				isset($oListItem->color)
					&& $oListItem->color = $aListItem[\'color\'];

				$oListItem->save();

				CT::$aAssosiatedListValues[$iListItemId] = $oListItem->id;
			}
		}

		CT::$aAssosiatedLists[$iListId] = $oList->id;
	}

	unset($aListi18n);
}

//Forms
if (Core::moduleIsActive(\'form\'))
{
	foreach ($aFormi18n as $iFormId => $aForm)
	{
		$sFormName = CT::translate($aForm[\'name\']);

		$oForm = Core_Entity::factory(\'Form\');
		$oForm
			->name($sFormName)
			->email($aForm[\'email\'])
			->button_name($aForm[\'button_name\'])
			->button_value($aForm[\'button_value\'])
			->use_captcha($aForm[\'use_captcha\'])
			->email_subject($aForm[\'email_subject\'])
			->success_text($aForm[\'success_text\'])
			->site_id($oSite->id)
			->save();

		$iForm_Id = $oForm->id;

		CT::$aAssosiatedForms[$iFormId] = $iForm_Id;

		CT::$aReplace["(\'Form\', {$iFormId})"] = "(\'Form\', {$oForm->id})";

		if (isset($aForm[\'form_fields\']))
		{
			foreach ($aForm[\'form_fields\'] as $iFormFieldId => $aFormField)
			{
				$iParent_Id = 0;

				$aExplodeDir = explode(\'/\', $aFormField[\'dirName\']);

				foreach ($aExplodeDir as $sDirName)
				{
					if ($sDirName != \'\')
					{
						$oForm_Field_Dir = Core_Entity::factory(\'Form_Field_Dir\');
						$oForm_Field_Dir
							->queryBuilder()
							->where(\'form_field_dirs.form_id\', \'=\', $iForm_Id)
							->where(\'form_field_dirs.parent_id\', \'=\', $iParent_Id);

						$oForm_Field_Dir = $oForm_Field_Dir->getByName($sDirName, FALSE);

						if (is_null($oForm_Field_Dir))
						{
							$oForm_Field_Dir = Core_Entity::factory(\'Form_Field_Dir\');
							$oForm_Field_Dir
								->form_id($iForm_Id)
								->parent_id($iParent_Id)
								->name($sDirName)
								->save();
						}

						$iParent_Id = $oForm_Field_Dir->id;
					}
				}

				$oForm_Field = Core_Entity::factory(\'Form_Field\');
				$oForm_Field
					->form_id($iForm_Id)
					->form_field_dir_id($iParent_Id)
					//->list_id(isset($aFormField[\'list_id\']) ? $aFormField[\'list_id\'] : 0)
					->list_id(Core_Array::get($aFormField, \'list_id\', 0))
					->type($aFormField[\'type\'])
					->size(isset($aFormField[\'size\']) ? $aFormField[\'size\'] : 0)
					->rows(isset($aFormField[\'rows\']) ? $aFormField[\'rows\'] : 0)
					->cols(isset($aFormField[\'cols\']) ? $aFormField[\'cols\'] : 0)
					->checked(isset($aFormField[\'checked\']) ? $aFormField[\'checked\'] : 0)
					->name(CT::translate($aFormField[\'name\']))
					->caption($aFormField[\'caption\'])
					->default_value(isset($aFormField[\'default_value\']) ? $aFormField[\'default_value\'] : \'\')
					->sorting($aFormField[\'sorting\'])
					->obligatory($aFormField[\'obligatory\'])
					->save();
			}
		}
	}

	unset($aFormi18n);
}

//Xsls
foreach ($aXsli18n as $sFileName => $aXsl)
{
	$sXslName = CT::translate($aXsl[\'name\']);

	$oXsl = Core_Entity::factory(\'Xsl\')->getByName($sXslName . $sSitePostfix, FALSE);

	if (is_null($oXsl))
	{
		$iParent_Id = 0;

		if ($aXsl[\'dirName\'] != \'\')
		{
			$aExplodeDir = explode(\'/\', $aXsl[\'dirName\']);
			array_unshift($aExplodeDir, $sSitePostfix);

			foreach ($aExplodeDir as $sDirName)
			{
				$sDirName = CT::translate($sDirName);

				$oXsl_Dir = Core_Entity::factory(\'Xsl_Dir\');
				$oXsl_Dir
					->queryBuilder()
					->where(\'xsl_dirs.parent_id\', \'=\', $iParent_Id);

				$oXsl_Dir = $oXsl_Dir->getByName($sDirName, FALSE);

				if (is_null($oXsl_Dir))
				{
					$oXsl_Dir = Core_Entity::factory(\'Xsl_Dir\');
					$oXsl_Dir
						->parent_id($iParent_Id)
						->name($sDirName)
						->save();
				}

				$iParent_Id = $oXsl_Dir->id;
			}
		}

		$oXsl = Core_Entity::factory(\'Xsl\');
		$oXsl
			->name($sXslName . $sSitePostfix)
			->xsl_dir_id($iParent_Id)
			->save();

		// Замену lang и import делаем после обработки всех XSL
		$aSecondReplace[\'"lang://\' . $aXsl[\'id\'] . \'"\'] = \'"lang://\' . $oXsl->id . \'"\';
		$aSecondReplace[\'"import://\' . $aXsl[\'id\'] . \'"\'] = \'"import://\' . $oXsl->id . \'"\';

		$oXsl->saveXslFile($Install_Controller->loadFile($tmpDir . "tmp/hostcmsfiles/xsl/" . $sFileName, CT::$aReplace));

		foreach ($aLngs as $sTmpLng)
		{
			$dtdPath = $tmpDir . "tmp/hostcmsfiles/xsl/{$aXsl[\'id\']}.{$sTmpLng}.dtd";

			if (is_file($dtdPath))
			{
				$oXsl->saveLngDtdFile($sTmpLng, $Install_Controller->loadFile($dtdPath, CT::$aReplace));
			}
		}
	}

	CT::$aReplace["\'{$aXsl[\'name\']}\'"] = "\'" . $oXsl->name . "\'";
	CT::$aReplace["\"{$aXsl[\'name\']}\""] = "\"" . $oXsl->name . "\"";

	CT::$aAssosiatedXslNames[$aXsl[\'name\']] = $oXsl->name;
}

// unset($aXsli18n);

//Tpls
if (Core::moduleIsActive(\'tpl\'))
{
	foreach ($aTpli18n as $sFileName => $aTpl)
	{
		$sTplName = CT::translate($aTpl[\'name\']);

		$oTpl = Core_Entity::factory(\'Tpl\')->getByName($sTplName . $sSitePostfix, FALSE);

		if (is_null($oTpl))
		{
			$iParent_Id = 0;

			if ($aTpl[\'dirName\'] != \'\')
			{
				$aExplodeDir = explode(\'/\', $aTpl[\'dirName\']);
				array_unshift($aExplodeDir, $sSitePostfix);

				foreach ($aExplodeDir as $sDirName)
				{
					$sDirName = CT::translate($sDirName);

					$oTpl_Dir = Core_Entity::factory(\'Tpl_Dir\');
					$oTpl_Dir
						->queryBuilder()
						->where(\'tpl_dirs.parent_id\', \'=\', $iParent_Id);

					$oTpl_Dir = $oTpl_Dir->getByName($sDirName, FALSE);

					if (is_null($oTpl_Dir))
					{
						$oTpl_Dir = Core_Entity::factory(\'Tpl_Dir\');
						$oTpl_Dir
							->parent_id($iParent_Id)
							->name($sDirName)
							->save();
					}

					$iParent_Id = $oTpl_Dir->id;
				}
			}

			$oTpl = Core_Entity::factory(\'Tpl\');
			$oTpl
				->name($sTplName . $sSitePostfix)
				->tpl_dir_id($iParent_Id)
				->save();

			CT::$aReplace["\'{$aTpl[\'name\']}\'"] = "\'" . $oTpl->name . "\'";

			$oTpl->saveTplFile($Install_Controller->loadFile($tmpDir . "tmp/hostcmsfiles/tpl/" . $sFileName, CT::$aReplace));

			foreach ($aLngs as $sTmpLng)
			{
				$configPath = $tmpDir . "tmp/hostcmsfiles/tpl/{$aTpl[\'id\']}.{$sTmpLng}.config";

				if (is_file($configPath))
				{
					$oTpl->saveLngConfigFile($sTmpLng, $Install_Controller->loadFile($configPath, CT::$aReplace));
				}
			}
		}
		else
		{
			CT::$aReplace["\'{$aTpl[\'name\']}\'"] = "\'" . $oTpl->name . "\'";
		}

		CT::$aAssosiatedTplNames[$aTpl[\'name\']] = $oTpl->name;
	}

	unset($aTpli18n);
}

//Libs
foreach ($aLibi18n as $iLibId => $aLib)
{
	$sLibName = CT::translate($aLib[\'name\']);

	$oLib = Core_Entity::factory(\'Lib\')->getByName($sLibName . $sSitePostfix, FALSE);

	if (is_null($oLib))
	{
		$iParent_Id = 0;
		$iLib_Property_Id = 0;

		if ($aLib[\'dirName\'] != \'\')
		{
			$aExplodeDir = explode(\'/\', $aLib[\'dirName\']);
			array_unshift($aExplodeDir, $sSitePostfix);

			foreach ($aExplodeDir as $sDirName)
			{
				$sDirName = CT::translate($sDirName);

				$oLib_Dir = Core_Entity::factory(\'Lib_Dir\');
				$oLib_Dir
					->queryBuilder()
					->where(\'lib_dirs.parent_id\', \'=\', $iParent_Id);

				$oLib_Dir = $oLib_Dir->getByName($sDirName, FALSE);

				if (is_null($oLib_Dir))
				{
					$oLib_Dir = Core_Entity::factory(\'Lib_Dir\');
					$oLib_Dir
						->parent_id($iParent_Id)
						->name($sDirName)
						->save();
				}

				$iParent_Id = $oLib_Dir->id;
			}
		}

		$oLib = Core_Entity::factory(\'Lib\');
		$oLib
			->name(strval($sLibName . $sSitePostfix))
			->lib_dir_id($iParent_Id)
			->save();

		$oLib->saveLibFile($Install_Controller->loadFile($tmpDir . "tmp/hostcmsfiles/lib/lib_" . $iLibId . \'/\' . $aLib[\'code\'], CT::$aReplace));
		$oLib->saveLibConfigFile($Install_Controller->loadFile($tmpDir . "tmp/hostcmsfiles/lib/lib_" . $iLibId . \'/\' . $aLib[\'config\'], CT::$aReplace));

		if (isset($aLib[\'params\']))
		{
			foreach ($aLib[\'params\'] as $iParamId => $aParams)
			{
				$oLib_Property = Core_Entity::factory(\'Lib_Property\');
				$oLib_Property
					->lib_id($oLib->id)
					->name(strval(CT::translate($aParams[\'name\'])))
					->varible_name(strval($aParams[\'varible_name\']))
					->type($aParams[\'type\'])
					->default_value(isset($aParams[\'default_value\']) ? $aParams[\'default_value\'] : \'\')
					->multivalue(intval($aParams[\'multivalue\']))
					->sorting(strval($aParams[\'sorting\']))
					->sql_request(isset($aParams[\'sql_request\']) ? $aParams[\'sql_request\'] : \'\')
					->sql_caption_field(isset($aParams[\'sql_caption_field\']) ? $aParams[\'sql_caption_field\'] : \'\')
					->sql_value_field(isset($aParams[\'sql_value_field\']) ? $aParams[\'sql_value_field\'] : \'\')
					->save();

				$iLib_Property_Id = $oLib_Property->id;

				CT::$aAssosiatedLibFields[$iParamId] = $iLib_Property_Id;

				if (isset($aParams[\'values\']))
				{
					foreach ($aParams[\'values\'] as $value => $name)
					{
						$oLib_Property_List_Value = Core_Entity::factory(\'Lib_Property_List_Value\');
						$oLib_Property_List_Value
							->lib_property_id($iLib_Property_Id)
							->name($name)
							->value($value)
							->save();
					}
				}
			}
		}
	}

	CT::$aAssosiatedLibs[$iLibId] = $oLib->id;
}

// Polls
if (Core::moduleIsActive(\'poll\'))
{
	foreach ($aPollGroupi18n as $iPollGroupId => $aPollGroup)
	{
		$sPollGroupName = CT::translate($aPollGroup[\'name\']);

		$oPoll_Group = Core_Entity::factory(\'Poll_Group\')->getByName($sPollGroupName . $sSitePostfix, FALSE);

		if (is_null($oPoll_Group))
		{
			$oPoll_Group = Core_Entity::factory(\'Poll_Group\');
			$oPoll_Group
				->structure_id($aPollGroup[\'structure_id\'])
				->site_id($oSite->id)
				->name($sPollGroupName . $sSitePostfix)
				->save();

			$iPollGroup_Id = $oPoll_Group->id;

			if (isset($aPollGroup[\'polls\']))
			{
				foreach ($aPollGroup[\'polls\'] as $iPollId => $aPoll)
				{
					$oPoll = Core_Entity::factory(\'Poll\');
					$oPoll
						->name(CT::translate($aPoll[\'name\']))
						->type($aPoll[\'type\'])
						->show_results($aPoll[\'show_results\'])
						->active($aPoll[\'active\'])
						->start_date($aPoll[\'start_date\'])
						->end_date($aPoll[\'end_date\'])
						->poll_group_id($iPollGroup_Id)
						->save();

					$iPoll_Id = $oPoll->id;

					if (isset($aPoll[\'poll_responses\']))
					{
						foreach ($aPoll[\'poll_responses\'] as $iPollResponseId => $aPollResponse)
						{
							$oPoll_Response = Core_Entity::factory(\'Poll_Response\');
							$oPoll_Response
								->poll_id($iPoll_Id)
								->name(CT::translate($aPollResponse[\'name\']))
								->grade($aPollResponse[\'grade\'])
								->sorting($aPollResponse[\'sorting\'])
								->save();
						}
					}
				}
			}

			CT::$aAssosiatedPollGroups[$iPollGroupId] = $iPollGroup_Id;

			CT::$aReplace["\'Poll_Group\', {$iPollGroupId})"] = "\'Poll_Group\', " . $iPollGroup_Id . ")";
		}
	}

	unset($aPollGroupi18n);
}

if (Core::moduleIsActive(\'siteuser\'))
{
	// Siteuser groups
	foreach ($aSiteuserGroupsi18n as $iSiteuserGroupId => $aSiteuser_Group)
	{
		$oSiteuser_Group = Core_Entity::factory(\'Siteuser_Group\');
		$oSiteuser_Group
			->queryBuilder()
			->where(\'siteuser_groups.site_id\', \'=\', $oSite->id);

		$oSiteuser_Group = $oSiteuser_Group->getByName($aSiteuser_Group[\'name\'], FALSE);

		if (is_null($oSiteuser_Group))
		{
			$oSiteuser_Group = Core_Entity::factory(\'Siteuser_Group\');
			$oSiteuser_Group
				->site_id($oSite->id)
				->name(Core_Array::get($aSiteuser_Group, \'name\'))
				->description(Core_Array::get($aSiteuser_Group, \'description\'))
				->default(Core_Array::get($aSiteuser_Group, \'default\'))
				->save();

			CT::$aAssosiatedSiteuserGroups[$iSiteuserGroupId] = $oSiteuser_Group->id;
		}
	}
	unset($aSiteuserGroupsi18n);

	//Siteusers
	foreach ($aSiteuseri18n as $iSiteuserId => $aSiteuser)
	{
		$oSiteuser = Core_Entity::factory(\'Siteuser\');
		$oSiteuser
			->queryBuilder()
			->where(\'siteusers.site_id\', \'=\', $oSite->id);

		$oSiteuser = $oSiteuser->getByLogin($aSiteuser[\'login\'], FALSE);

		if (is_null($oSiteuser))
		{
			$oSiteuser = Core_Entity::factory(\'Siteuser\');
			$oSiteuser
				->site_id($oSite->id)
				->login(Core_Array::get($aSiteuser, \'login\', \'test\'))
				->password(Core_Hash::instance()->hash(Core_Array::get($aSiteuser, \'password\', \'test\')))
				->email(Core_Array::get($aSiteuser, \'email\', \'admin@localhost\'))
				->name(Core_Array::get($aSiteuser, \'name\', \'\'))
				->surname(Core_Array::get($aSiteuser, \'surname\', \'\'))
				->patronymic(Core_Array::get($aSiteuser, \'patronymic\', \'\'))
				->company(Core_Array::get($aSiteuser, \'company\', \'\'))
				->phone(Core_Array::get($aSiteuser, \'phone\', \'\'))
				->website(Core_Array::get($aSiteuser, \'website\', \'\'))
				->country(Core_Array::get($aSiteuser, \'country\', \'\'))
				->city(Core_Array::get($aSiteuser, \'city\', \'\'))
				->address(Core_Array::get($aSiteuser, \'address\', \'\'))
				->active(Core_Array::get($aSiteuser, \'active\', 1))
				->datetime(Core_Date::timestamp2sql(time()))
				->save();

			CT::$aAssosiatedSiteusers[$iSiteuserId] = $oSiteuser->id;

			/** @var array $aSiteuser */
			foreach ($aSiteuser[\'siteuser_group_id\'] as $iSiteuserGroupId)
			{
				$oSiteuser_Group_List = Core_Entity::factory(\'Siteuser_Group_List\');
				// $oSiteuser_Group_List->siteuser_group_id = $iSiteuserGroupId;
				$oSiteuser_Group_List->siteuser_group_id = Core_Array::get(CT::$aAssosiatedSiteuserGroups, $iSiteuserGroupId, 0);
				$oSiteuser_Group_List->siteuser_id = $oSiteuser->id;
				$oSiteuser_Group_List->save();
			}
		}
	}
	unset($aSiteuseri18n);
}

//Informationsystems
foreach ($aInformationsystemi18n as $iInformationsystemId => $aInformationsystem)
{
	$oInformationsystem = Core_Entity::factory(\'Informationsystem\');
	$oInformationsystem
		->queryBuilder()
		->where(\'informationsystems.site_id\', \'=\', $oSite->id);

	$sInformationsystemName = CT::translate($aInformationsystem[\'name\']);

	$oInformationsystem = $oInformationsystem->getByName($sInformationsystemName, FALSE);

	if (is_null($oInformationsystem))
	{
		$aExplodeDir = explode(\'/\', $aInformationsystem[\'dirName\']);

		$iParent_Id = 0;
		$iParent_Property_Id = 0;

		foreach ($aExplodeDir as $sDirName)
		{
			if ($sDirName != \'\')
			{
				$oInformationsystem_Dir = Core_Entity::factory(\'Informationsystem_Dir\');
				$oInformationsystem_Dir
					->queryBuilder()
					->where(\'informationsystem_dirs.parent_id\', \'=\', $iParent_Id);

				$oInformationsystem_Dir = $oInformationsystem_Dir->getByName($sDirName, FALSE);

				if (is_null($oInformationsystem_Dir))
				{
					$oInformationsystem_Dir = Core_Entity::factory(\'Informationsystem_Dir\');
					$oInformationsystem_Dir
						->parent_id($iParent_Id)
						->site_id($oSite->id)
						->name($sDirName)
						->save();
				}

				$iParent_Id = $oInformationsystem_Dir->id;
			}
		}

		$oInformationsystem = Core_Entity::factory(\'Informationsystem\');
		$oInformationsystem
			->informationsystem_dir_id($iParent_Id)
			->structure_id($aInformationsystem[\'structure_id\'])
			->site_id($oSite->id)
			->name($sInformationsystemName)
			->description($aInformationsystem[\'description\'])
			->items_on_page($aInformationsystem[\'items_on_page\'])
			->items_sorting_field($aInformationsystem[\'items_sorting_field\'])
			->items_sorting_direction($aInformationsystem[\'items_sorting_direction\'])
			->groups_sorting_field($aInformationsystem[\'groups_sorting_field\'])
			->groups_sorting_direction($aInformationsystem[\'groups_sorting_direction\'])
			->image_large_max_width($aInformationsystem[\'image_large_max_width\'])
			->image_large_max_height($aInformationsystem[\'image_large_max_height\'])
			->image_small_max_width($aInformationsystem[\'image_small_max_width\'])
			->image_small_max_height($aInformationsystem[\'image_small_max_height\'])
			->group_image_large_max_width($aInformationsystem[\'group_image_large_max_width\'])
			->group_image_large_max_height($aInformationsystem[\'group_image_large_max_height\'])
			->group_image_small_max_width($aInformationsystem[\'group_image_small_max_width\'])
			->group_image_small_max_height($aInformationsystem[\'group_image_small_max_height\'])
			->typograph_default_items($aInformationsystem[\'typograph_default_items\'])
			->typograph_default_groups($aInformationsystem[\'typograph_default_groups\'])
			->use_captcha($aInformationsystem[\'use_captcha\'])
			->save();

		$iInformationsystem_Id = $oInformationsystem->id;

		CT::$aAssosiatedInformationsystems[$iInformationsystemId] = $iInformationsystem_Id;

		CT::$aReplace["\'Informationsystem\', {$iInformationsystemId})"]
			= $aSecondReplace["\'Informationsystem\', {$iInformationsystemId})"] = "\'Informationsystem\', " . $iInformationsystem_Id . ")";

		CT::$aReplace[\'$informationsystem_id = \' . $iInformationsystemId . \';\']
			= $aSecondReplace[\'$informationsystem_id = \' . $iInformationsystemId . \';\'] = \'$informationsystem_id = \' . $iInformationsystem_Id . \';\';

		if (isset($aInformationsystem[\'group_properties\']))
		{
			/** @var array $aInformationsystem */
			foreach ($aInformationsystem[\'group_properties\'] as $iPropertyId => $aProperty)
			{
				$aExplodeDir = explode(\'/\', $aProperty[\'dirName\']);

				foreach ($aExplodeDir as $sDirName)
				{
					if ($sDirName != \'\')
					{
						$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
						$oProperty_Dir
							->queryBuilder()
							->join(\'informationsystem_group_property_dirs\', \'property_dirs.id\', \'=\', \'informationsystem_group_property_dirs.property_dir_id\')
							->where(\'informationsystem_group_property_dirs.informationsystem_id\', \'=\', $iInformationsystem_Id)
							->where(\'property_dirs.parent_id\', \'=\', $iParent_Property_Id);

						$oProperty_Dir = $oProperty_Dir->getByName($sDirName, FALSE);

						if (is_null($oProperty_Dir))
						{
							$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
							$oProperty_Dir
								->parent_id($iParent_Property_Id)
								->name($sDirName)
								->save();

							$oInformationsystem_Group_Property_Dir = Core_Entity::factory(\'Informationsystem_Group_Property_Dir\');
							$oInformationsystem_Group_Property_Dir
								->informationsystem_id($iInformationsystem_Id)
								->property_dir_id($iParent_Property_Id)
								->save();
						}

						$iParent_Property_Id = $oProperty_Dir->id;
					}
				}

				$oProperty = Core_Entity::factory(\'Property\');
				$oProperty
					->property_dir_id($iParent_Property_Id)
					->list_id(isset($aProperty[\'list_id\']) && isset(CT::$aAssosiatedLists[$aProperty[\'list_id\']]) ? CT::$aAssosiatedLists[$aProperty[\'list_id\']] : 0)
					->informationsystem_id(isset($aProperty[\'informationsystem_id\']) ? $aProperty[\'informationsystem_id\'] : 0)
					->shop_id(0)
					->name(CT::translate($aProperty[\'name\']))
					->description($aProperty[\'description\'])
					->type($aProperty[\'type\'])
					->default_value($aProperty[\'default_value\'])
					->tag_name($aProperty[\'tag_name\'])
					->sorting($aProperty[\'sorting\'])
					->multiple($aProperty[\'multiple\'])
					->image_large_max_width(isset($aProperty[\'image_large_max_width\']) ? $aProperty[\'image_large_max_width\'] : 300)
					->image_large_max_height(isset($aProperty[\'image_large_max_height\']) ? $aProperty[\'image_large_max_height\'] : 300)
					->image_small_max_width(isset($aProperty[\'image_small_max_width\']) ? $aProperty[\'image_small_max_width\'] : 70)
					->image_small_max_height(isset($aProperty[\'image_small_max_height\']) ? $aProperty[\'image_small_max_height\'] : 70)
					->hide_small_image(isset($aProperty[\'hide_small_image\']) ? $aProperty[\'hide_small_image\'] : 0)
					->save();

				$oInformationsystem_Group_Property = Core_Entity::factory(\'Informationsystem_Group_Property\');
				$oInformationsystem_Group_Property
					->informationsystem_id($iInformationsystem_Id)
					->property_id($oProperty->id)
					->save();

				CT::$aAssosiatedProperties[$iPropertyId] = $oProperty->id;

				CT::$aReplace["property_id\', \'=\', {$iPropertyId})"]
					=  $aSecondReplace["property_id\', \'=\', {$iPropertyId})"] = "property_id\', \'=\', {$oProperty->id})";

				CT::$aReplace["\'Property\', {$iPropertyId})"] = "\'Property\', " . $oProperty->id . ")";
				CT::$aReplace[\'$property_id = \' . $iPropertyId . \';\']
					= $aSecondReplace[\'$property_id = \' . $iPropertyId . \';\'] = \'$property_id = \' . $oProperty->id . \';\';
			}
		}

		if (isset($aInformationsystem[\'informationsystem_groups\']))
		{
			foreach ($aInformationsystem[\'informationsystem_groups\'] as $iInformationsystemGroupId => $aInformationsystemGroup)
			{
				$oInformationsystem_Group = Core_Entity::factory(\'Informationsystem_Group\');

				$sInformationsystemGroupName = CT::translate($aInformationsystemGroup[\'name\']);

				$oInformationsystem_Group->name = $sInformationsystemGroupName;
				$oInformationsystem_Group->indexing = $aInformationsystemGroup[\'indexing\'];

				$oInformationsystem_Group
					->informationsystem_id($iInformationsystem_Id)
					/*->parent_id($aInformationsystemGroup[\'parent_id\'] > 0 && isset(CT::$aAssosiatedInformationsystemGroups[$aInformationsystemGroup[\'parent_id\']])
						? intval(CT::$aAssosiatedInformationsystemGroups[$aInformationsystemGroup[\'parent_id\']])
						: 0
					)*/
					->description($aInformationsystemGroup[\'description\'])
					->sorting($aInformationsystemGroup[\'sorting\'])
					->active($aInformationsystemGroup[\'active\'])
					->path(Core_Array::get($aInformationsystemGroup, \'path\', Core_Str::transliteration($sInformationsystemGroupName)))
					->save();

				$Install_Controller->moveInformationsystemGroupImage($oInformationsystem_Group->id, $sourceInformationsystem = $iInformationsystemId, $sourceInformationsystemGroupId = $iInformationsystemGroupId, $aInformationsystemGroup[\'image_large\'], $aInformationsystemGroup[\'image_small\'], $oSite->nesting_level);

				CT::$aAssosiatedInformationsystemGroups[$iInformationsystemGroupId] = $oInformationsystem_Group->id;

				CT::$aReplace[\'$informationsystem_group_id = \' . $iInformationsystemGroupId . \';\']
					= $aSecondReplace[\'$informationsystem_group_id = \' . $iInformationsystemGroupId . \';\'] = \'$informationsystem_group_id = \' . $oInformationsystem_Group->id . \';\';

				if (isset($aInformationsystemGroup[\'property_values\']))
				{
					foreach ($aInformationsystemGroup[\'property_values\'] as $iPropertyValueId => $aPropertyValue)
					{
						$oProperty = Core_Entity::factory(\'Property\')->getById(CT::$aAssosiatedProperties[$aPropertyValue[\'property_id\']], FALSE);

						if (!is_null($oProperty))
						{
							$oProperty_Value = $oProperty->createNewValue($oInformationsystem_Group->id);

							switch ($oProperty->type)
							{
								case 0: // Int
								case 1: // String
								case 4: // Textarea
								case 6: // Wysiwyg
								case 7: // Checkbox
								case 8: // Date
								case 9: // Datetime
									$oProperty_Value
										->value($aPropertyValue[\'value\'])
										->save();
								break;

								case 2: //File
									$Install_Controller->moveInformationsystemGroupPropertyImage($oInformationsystem_Group->id, $oProperty->id, $iInformationsystemId, $iInformationsystemGroupId, $iPropertyValueId, $oSite->nesting_level, $aPropertyValue[\'file\'], $aPropertyValue[\'file_small\']);
								break;

								case 3: //List
									if (Core::moduleIsActive(\'list\')
											&& isset(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']]))
									{
										$oProperty_Value
											->value(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']])
											->save();
									}
								break;
							}
						}
					}
				}
			}

			// Расстановка иерархии групп
			foreach ($aInformationsystem[\'informationsystem_groups\'] as $iInformationsystemGroupId => $aInformationsystemGroup)
			{
				$oInformationsystem_Group = Core_Entity::factory(\'Informationsystem_Group\', CT::$aAssosiatedInformationsystemGroups[$iInformationsystemGroupId]);

				$oInformationsystem_Group
					->parent_id($aInformationsystemGroup[\'parent_id\'] > 0 && isset(CT::$aAssosiatedInformationsystemGroups[$aInformationsystemGroup[\'parent_id\']])
						? intval(CT::$aAssosiatedInformationsystemGroups[$aInformationsystemGroup[\'parent_id\']])
						: 0
					)
					->save();
			}
		}

		if (isset($aInformationsystem[\'properties\']))
		{
			foreach ($aInformationsystem[\'properties\'] as $iPropertyId => $aProperty)
			{
				// $aExplodeDir = explode(\'/\', $aProperty[\'dirName\']);
				// array_unshift($aExplodeDir, $sSitePostfix);

				$iParent_Property_Id = 0;

				if ($aProperty[\'dirName\'] != \'\')
				{
					$aExplodeDir = explode(\'/\', $aProperty[\'dirName\']);

					foreach ($aExplodeDir as $sDirName)
					{
						if ($sDirName != \'\')
						{
							$sDirName = CT::translate($sDirName);

							$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
							$oProperty_Dir
								->queryBuilder()
								->join(\'informationsystem_item_property_dirs\', \'property_dirs.id\', \'=\', \'informationsystem_item_property_dirs.property_dir_id\')
								->where(\'informationsystem_item_property_dirs.informationsystem_id\', \'=\', $iInformationsystem_Id)
								->where(\'property_dirs.parent_id\', \'=\', $iParent_Property_Id);

							$oProperty_Dir = $oProperty_Dir->getByName($sDirName, FALSE);

							if (is_null($oProperty_Dir))
							{
								$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
								$oProperty_Dir
									->parent_id($iParent_Property_Id)
									->name($sDirName)
									->save();

								$oInformationsystem_Item_Property_Dir = Core_Entity::factory(\'Informationsystem_Item_Property_Dir\');
								$oInformationsystem_Item_Property_Dir
									->informationsystem_id($iInformationsystem_Id)
									->property_dir_id($oProperty_Dir->id)
									->save();
							}

							$iParent_Property_Id = $oProperty_Dir->id;
						}
					}
				}

				$oProperty = Core_Entity::factory(\'Property\');
				$oProperty
					->property_dir_id($iParent_Property_Id)
					//->list_id(isset($aProperty[\'list_id\']) ? $aProperty[\'list_id\'] : 0)
					->list_id(Core_Array::get($aProperty, \'list_id\', 0))
					->informationsystem_id(isset($aProperty[\'informationsystem_id\']) ? $aProperty[\'informationsystem_id\'] : 0)
					->shop_id(0)
					->name(CT::translate($aProperty[\'name\']))
					->description($aProperty[\'description\'])
					->type($aProperty[\'type\'])
					->default_value($aProperty[\'default_value\'])
					->tag_name($aProperty[\'tag_name\'])
					->sorting($aProperty[\'sorting\'])
					->multiple($aProperty[\'multiple\'])
					->image_large_max_width(isset($aProperty[\'image_large_max_width\']) ? $aProperty[\'image_large_max_width\'] : 300)
					->image_large_max_height(isset($aProperty[\'image_large_max_height\']) ? $aProperty[\'image_large_max_height\'] : 300)
					->image_small_max_width(isset($aProperty[\'image_small_max_width\']) ? $aProperty[\'image_small_max_width\'] : 70)
					->image_small_max_height(isset($aProperty[\'image_small_max_height\']) ? $aProperty[\'image_small_max_height\'] : 70)
					->hide_small_image(isset($aProperty[\'hide_small_image\']) ? $aProperty[\'hide_small_image\'] : 0)
					->save();

				$oInformationsystem_Item_Property = Core_Entity::factory(\'Informationsystem_Item_Property\');
				$oInformationsystem_Item_Property
					->informationsystem_id($iInformationsystem_Id)
					->property_id($oProperty->id)
					->save();

				CT::$aAssosiatedProperties[$iPropertyId] = $oProperty->id;

				CT::$aReplace["property_id\', \'=\', {$iPropertyId})"]
					=  $aSecondReplace["property_id\', \'=\', {$iPropertyId})"] = "property_id\', \'=\', {$oProperty->id})";

				CT::$aReplace["\'Property\', {$iPropertyId})"] = "\'Property\', " . $oProperty->id . ")";
				CT::$aReplace[\'$property_id = \' . $iPropertyId . \';\']
					= $aSecondReplace[\'$property_id = \' . $iPropertyId . \';\'] = \'$property_id = \' . $oProperty->id . \';\';
			}
		}

		if (isset($aInformationsystem[\'informationsystem_items\']))
		{
			foreach ($aInformationsystem[\'informationsystem_items\'] as $iInformationsystemItemId => $aInformationsystemItem)
			{
				$oInformationsystem_Item = Core_Entity::factory(\'Informationsystem_Item\');

				$sInformationsystemItemName = CT::translate($aInformationsystemItem[\'name\']);

				$oInformationsystem_Item->name = $sInformationsystemItemName;
				$oInformationsystem_Item->indexing = $aInformationsystemItem[\'indexing\'];

				$oInformationsystem_Item
					->informationsystem_id($iInformationsystem_Id)
					->informationsystem_group_id($aInformationsystemItem[\'informationsystem_group_id\'] > 0
						? Core_Array::get(CT::$aAssosiatedInformationsystemGroups, $aInformationsystemItem[\'informationsystem_group_id\'], 0)
						: 0
					)
					->shortcut_id(Core_Array::get($aInformationsystemItem, \'shortcut_id\', 0))
					->active(Core_Array::get($aInformationsystemItem, \'active\', 1))
					->sorting(Core_Array::get($aInformationsystemItem, \'sorting\', 0))
					->description(Core_Array::get($aInformationsystemItem, \'description\', \'\'))
					->text(Core_Array::get($aInformationsystemItem, \'text\', \'\'))
					->seo_title(Core_Array::get($aInformationsystemItem, \'seo_title\', \'\'))
					->seo_description(Core_Array::get($aInformationsystemItem, \'seo_description\', \'\'))
					->seo_keywords(Core_Array::get($aInformationsystemItem, \'seo_keywords\', \'\'))
					->path(Core_Array::get($aInformationsystemItem, \'path\', Core_Str::transliteration(Core_Array::get($aInformationsystemItem, \'name\', \'\'))))
					->save();

				$Install_Controller->moveInformationsystemItemImage($oInformationsystem_Item->id, $sourceInformationsystem = $iInformationsystemId, $sourceInformationsystemItemId = $iInformationsystemItemId, $aInformationsystemItem[\'image_large\'], $aInformationsystemItem[\'image_small\'], $oSite->nesting_level);

				CT::$aReplace[\'$informationsystem_item_id = \' . $iInformationsystemItemId . \';\']
					= $aSecondReplace[\'$informationsystem_item_id = \' . $iInformationsystemItemId . \';\'] = \'$informationsystem_item_id = \' . $oInformationsystem_Item->id . \';\';

				$iInformationsystemItem_Id = $oInformationsystem_Item->id;

				// Tags
				if (Core::moduleIsActive(\'tag\') && !empty($aInformationsystemItem[\'tags\']))
				{
					$aExplodeTags = explode(\',\', $aInformationsystemItem[\'tags\']);

					foreach ($aExplodeTags as $sTagName)
					{
						$oTag = Core_Entity::factory(\'Tag\')->getByName($sTagName, FALSE);

						if (is_null($oTag))
						{
							$oTag = Core_Entity::factory(\'Tag\');
							$oTag
								->tag_dir_id(0)
								->name($sTagName)
								->path($sTagName)
								->save();
						}

						$oTag_Informationsystem_Item = Core_Entity::factory(\'Tag_Informationsystem_Item\');
						$oTag_Informationsystem_Item
							->tag_id($oTag->id)
							->informationsystem_item_id($iInformationsystemItem_Id)
							->site_id($oSite->id)
							->save();
					}
				}

				if (isset($aInformationsystemItem[\'comments\']))
				{
					foreach ($aInformationsystemItem[\'comments\'] as $aComment)
					{
						$oComment = Core_Entity::factory(\'Comment\');

						$oComment->author = $aComment[\'author\'];
						$oComment->email = $aComment[\'email\'];

						$oComment
							->parent_id($aComment[\'parent_id\'])
							->subject($aComment[\'subject\'])
							->text($aComment[\'text\'])
							->phone($aComment[\'phone\'])
							->active($aComment[\'active\'])
							->grade($aComment[\'grade\'])
							->siteuser_id(isset($aComment[\'siteuser_id\'])
								? Core_Array::get(CT::$aAssosiatedSiteusers, $aComment[\'siteuser_id\'], 0)
								: 0
							)
							->datetime(Core_Date::timestamp2sql(time()));

						$oInformationsystem_Item->add($oComment);
					}
				}

				if (isset($aInformationsystemItem[\'property_values\']))
				{
					foreach ($aInformationsystemItem[\'property_values\'] as $iPropertyValueId => $aPropertyValue)
					{
						$oProperty = Core_Entity::factory(\'Property\')->getById(CT::$aAssosiatedProperties[$aPropertyValue[\'property_id\']], FALSE);

						if (!is_null($oProperty))
						{
							$oProperty_Value = $oProperty->createNewValue($oInformationsystem_Item->id);

							switch ($oProperty->type)
							{
								case 0: // Int
								case 1: // String
								case 4: // Textarea
								case 6: // Wysiwyg
								case 7: // Checkbox
								case 8: // Date
								case 9: // Datetime
									$oProperty_Value
										->value($aPropertyValue[\'value\'])
										->save();
								break;

								case 2: //File
									$Install_Controller->moveInformationsystemItemPropertyImage($oInformationsystem_Item->id, $oProperty->id, $iInformationsystemId, $iInformationsystemItemId, $iPropertyValueId, $oSite->nesting_level, $aPropertyValue[\'file\'], $aPropertyValue[\'file_small\']);
								break;

								case 3: //List
									if (Core::moduleIsActive(\'list\')
										&& isset(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']]))
									{
										$oProperty_Value
											->value(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']])
											->save();
									}
								break;
							}
						}
					}
				}
			}
		}
	}
}
unset($aInformationsystemi18n);

//Shop Currencies
foreach ($aShopCurrencies as $iShopCurrencyId => $aShopCurrency)
{
	$oShop_Currency = Core_Entity::factory(\'Shop_Currency\')->getByCode($aShopCurrency[\'code\'], FALSE);

	if (is_null($oShop_Currency))
	{
		$oShop_Currency = Core_Entity::factory(\'Shop_Currency\');
		$oShop_Currency
			->name($aShopCurrency[\'name\'])
			->code($aShopCurrency[\'code\'])
			->exchange_rate($aShopCurrency[\'exchange_rate\'])
			->default($aShopCurrency[\'default\'])
			->sorting($aShopCurrency[\'sorting\'])
			->save();
	}

	CT::$aAssosiatedShopCurrencies[$iShopCurrencyId] = $oShop_Currency->id;
}
unset($aShopCurrencies);

// Companies
foreach ($aCompaniesi18n as $iCompanyId => $aCompany)
{
	$oCompany = Core_Entity::factory(\'Company\');
	$oCompany
		->name(CT::translate($aCompany[\'name\']))
		->description($aCompany[\'description\'])
		->legal_name($aCompany[\'legal_name\'])
		->accountant_legal_name($aCompany[\'accountant_legal_name\'])
		->tin($aCompany[\'tin\'])
		->kpp($aCompany[\'kpp\'])
		->psrn($aCompany[\'psrn\'])
		->okpo($aCompany[\'okpo\'])
		->okved($aCompany[\'okved\'])
		// ->bic($aCompany[\'bic\'])
		// ->current_account($aCompany[\'current_account\'])
		// ->correspondent_account($aCompany[\'correspondent_account\'])
		// ->bank_name($aCompany[\'bank_name\'])
		// ->bank_address($aCompany[\'bank_address\'])
		->save();

	CT::$aAssosiatedCompanies[$iCompanyId] = $oCompany->id;

	$oCompany_Site = Core_Entity::factory(\'Company_Site\');
	$oCompany_Site
		->site_id($oSite->id)
		->company_id($oCompany->id)
		->save();
}
unset($aCompaniesi18n);

//Shops
foreach ($aShopi18n as $iShopId => $aShop)
{
	$aExplodeDir = explode(\'/\', $aShop[\'dirName\']);

	$iParent_Id = 0;
	$iParent_Property_Id = 0;
	$iParent_Tab_Id = 0;

	foreach ($aExplodeDir as $sDirName)
	{
		if ($sDirName != \'\')
		{
			$oShop_Dir = Core_Entity::factory(\'Shop_Dir\');
			$oShop_Dir
				->queryBuilder()
				->where(\'shop_dirs.parent_id\', \'=\', $iParent_Id);

			$oShop_Dir = $oShop_Dir->getByName($sDirName, FALSE);

			if (is_null($oShop_Dir))
			{
				$oShop_Dir = Core_Entity::factory(\'Shop_Dir\');
				$oShop_Dir
					->parent_id($iParent_Id)
					->site_id($oSite->id)
					->name($sDirName)
					->save();
			}

			$iParent_Id = $oShop_Dir->id;
		}
	}

	$oShop = Core_Entity::factory(\'Shop\');
	$oShop
		->shop_dir_id($iParent_Id)
		->shop_company_id(Core_Array::get(CT::$aAssosiatedCompanies, $aShop[\'shop_company_id\'], 0))
		->site_id($oSite->id)
		->name(CT::translate($aShop[\'name\']))
		->image_large_max_width($aShop[\'image_large_max_width\'])
		->image_large_max_height($aShop[\'image_large_max_height\'])
		->image_small_max_width($aShop[\'image_small_max_width\'])
		->image_small_max_height($aShop[\'image_small_max_height\'])
		->group_image_small_max_width($aShop[\'group_image_small_max_width\'])
		->group_image_small_max_height($aShop[\'group_image_small_max_height\'])
		->group_image_large_max_width($aShop[\'group_image_large_max_width\'])
		->group_image_large_max_height($aShop[\'group_image_large_max_height\'])
		->producer_image_small_max_width($aShop[\'producer_image_small_max_width\'])
		->producer_image_small_max_height($aShop[\'producer_image_small_max_height\'])
		->producer_image_large_max_width($aShop[\'producer_image_large_max_width\'])
		->producer_image_large_max_height($aShop[\'producer_image_large_max_height\'])
		->structure_id($aShop[\'structure_id\'])
		->shop_country_id($aShop[\'shop_country_id\'])
		->shop_currency_id(CT::$aAssosiatedShopCurrencies[$aShop[\'shop_currency_id\']])
		->email($aShop[\'email\'])
		->items_on_page($aShop[\'items_on_page\'])
		->send_order_email_admin($aShop[\'send_order_email_admin\'])
		->send_order_email_user($aShop[\'send_order_email_user\'])
		->items_sorting_field($aShop[\'items_sorting_field\'])
		->items_sorting_direction($aShop[\'items_sorting_direction\'])
		->groups_sorting_field($aShop[\'groups_sorting_field\'])
		->groups_sorting_direction($aShop[\'groups_sorting_direction\'])
		->comment_active($aShop[\'comment_active\'])
		->typograph_default_items($aShop[\'typograph_default_items\'])
		->typograph_default_groups($aShop[\'typograph_default_groups\'])
		->apply_tags_automatically($aShop[\'apply_tags_automatically\'])
		->write_off_paid_items($aShop[\'write_off_paid_items\'])
		->change_filename($aShop[\'change_filename\'])
		->attach_digital_items($aShop[\'attach_digital_items\'])
		->use_captcha($aShop[\'use_captcha\'])
		->filter($aShop[\'filter\'])
		->filter_mode($aShop[\'filter_mode\'])
		->order_admin_subject($aShop[\'order_admin_subject\'])
		->order_user_subject($aShop[\'order_user_subject\'])
		->confirm_admin_subject($aShop[\'confirm_admin_subject\'])
		->confirm_user_subject($aShop[\'confirm_user_subject\'])
		->cancel_admin_subject($aShop[\'cancel_admin_subject\'])
		->cancel_user_subject($aShop[\'cancel_user_subject\'])
		->reserve(1)
		->save();

	$iShop_Id = $oShop->id;

	CT::$aAssosiatedShops[$iShopId] = $iShop_Id;

	CT::$aReplace["\'Shop\', {$iShopId})"]
		= $aSecondReplace["\'Shop\', {$iShopId})"] = "\'Shop\', " . $iShop_Id . ")";

	CT::$aReplace[\'$shop_id = \' . $iShopId . \';\']
		= $aSecondReplace[\'$shop_id = \' . $iShopId . \';\'] = \'$shop_id = \' . $iShop_Id . \';\';

	// Tabs
	if (isset($aShop[\'shop_tabs\']))
	{
		foreach ($aShop[\'shop_tabs\'] as $iShopTabId => $aShopTab)
		{
			$aExplodeDir = explode(\'/\', $aShopTab[\'dirName\']);

			foreach ($aExplodeDir as $sDirName)
			{
				if ($sDirName != \'\')
				{
					$oShop_Tab_Dir = Core_Entity::factory(\'Shop_Tab_Dir\');
					$oShop_Tab_Dir
						->queryBuilder()
						->where(\'shop_tab_dirs.parent_id\', \'=\', $iParent_Tab_Id);

					$oShop_Tab_Dir = $oShop_Tab_Dir->getByName($sDirName, FALSE);

					if (is_null($oShop_Tab_Dir))
					{
						$oShop_Tab_Dir = Core_Entity::factory(\'Shop_Tab_Dir\');
						$oShop_Tab_Dir
							->parent_id($iParent_Tab_Id)
							->name($sDirName)
							->save();
					}

					$iParent_Tab_Id = $oShop_Tab_Dir->id;
				}
			}

			$oShop_Tab = Core_Entity::factory(\'Shop_Tab\');
			$oShop_Tab
				->shop_id($oShop->id)
				->shop_tab_dir_id($iParent_Tab_Id)
				->name(CT::translate($aShopTab[\'name\']))
				->caption($aShopTab[\'caption\'])
				->text($aShopTab[\'text\'])
				->icon($aShopTab[\'icon\'])
				->color($aShopTab[\'color\'])
				->sorting($aShopTab[\'sorting\'])
				->save();

			CT::$aAssosiatedShopTabs[$iShopTabId] = $oShop_Tab->id;
		}
	}

	//Shop group properties
	if (isset($aShop[\'group_properties\']))
	{
		foreach ($aShop[\'group_properties\'] as $iPropertyId => $aProperty)
		{
			$aExplodeDir = explode(\'/\', $aProperty[\'dirName\']);

			foreach ($aExplodeDir as $sDirName)
			{
				if ($sDirName != \'\')
				{
					$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
					$oProperty_Dir
						->queryBuilder()
						->join(\'shop_group_property_dirs\', \'property_dirs.id\', \'=\', \'shop_group_property_dirs.property_dir_id\')
						->where(\'shop_group_property_dirs.shop_id\', \'=\', $iShop_Id)
						->where(\'property_dirs.parent_id\', \'=\', $iParent_Property_Id);

					$oProperty_Dir = $oProperty_Dir->getByName($sDirName, FALSE);

					if (is_null($oProperty_Dir))
					{
						$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
						$oProperty_Dir
							->parent_id($iParent_Property_Id)
							->name($sDirName)
							->save();

						$oShop_Group_Property_Dir = Core_Entity::factory(\'Shop_Group_Property_Dir\');
						$oShop_Group_Property_Dir
							->shop_id($iShop_Id)
							->property_dir_id($oProperty_Dir->id)
							->save();
					}

					$iParent_Property_Id = $oProperty_Dir->id;
				}
			}

			$oProperty = Core_Entity::factory(\'Property\');
			$oProperty
				->property_dir_id($iParent_Property_Id)
				->list_id(isset($aProperty[\'list_id\']) && isset(CT::$aAssosiatedLists[$aProperty[\'list_id\']]) ? CT::$aAssosiatedLists[$aProperty[\'list_id\']] : 0)
				->informationsystem_id(0)
				->shop_id(isset($aProperty[\'shop_id\']) ? $aProperty[\'shop_id\'] : 0)
				->name(CT::translate($aProperty[\'name\']))
				->description($aProperty[\'description\'])
				->type($aProperty[\'type\'])
				->default_value($aProperty[\'default_value\'])
				->tag_name($aProperty[\'tag_name\'])
				->sorting($aProperty[\'sorting\'])
				->multiple($aProperty[\'multiple\'])
				->image_large_max_width(isset($aProperty[\'image_large_max_width\']) ? $aProperty[\'image_large_max_width\'] : 300)
				->image_large_max_height(isset($aProperty[\'image_large_max_height\']) ? $aProperty[\'image_large_max_height\'] : 300)
				->image_small_max_width(isset($aProperty[\'image_small_max_width\']) ? $aProperty[\'image_small_max_width\'] : 70)
				->image_small_max_height(isset($aProperty[\'image_small_max_height\']) ? $aProperty[\'image_small_max_height\'] : 70)
				->hide_small_image(isset($aProperty[\'hide_small_image\']) ? $aProperty[\'hide_small_image\'] : 0)
				->save();

			$oShop_Group_Property = Core_Entity::factory(\'Shop_Group_Property\');
			$oShop_Group_Property
				->shop_id($iShop_Id)
				->property_id($oProperty->id)
				->save();

			CT::$aAssosiatedProperties[$iPropertyId] = $oProperty->id;

			CT::$aReplace["property_id\', \'=\', {$iPropertyId})"]
				=  $aSecondReplace["property_id\', \'=\', {$iPropertyId})"] = "property_id\', \'=\', {$oProperty->id})";

			CT::$aReplace["\'Property\', {$iPropertyId})"] = "\'Property\', " . $oProperty->id . ")";
			CT::$aReplace[\'$property_id = \' . $iPropertyId . \';\']
				= $aSecondReplace[\'$property_id = \' . $iPropertyId . \';\'] = \'$property_id = \' . $oProperty->id . \';\';
		}
	}

	//Shop groups
	if (isset($aShop[\'shop_groups\']))
	{
		foreach ($aShop[\'shop_groups\'] as $iShopGroupId => $aShopGroup)
		{
			$oShop_Group = Core_Entity::factory(\'Shop_Group\');

			$oShop_Group->name = CT::translate($aShopGroup[\'name\']);
			$oShop_Group->indexing = $aShopGroup[\'indexing\'];

			$oShop_Group
				->shop_id($iShop_Id)
				/*->parent_id($aShopGroup[\'parent_id\'] > 0 && isset(CT::$aAssosiatedShopGroups[$aShopGroup[\'parent_id\']])
					? intval(CT::$aAssosiatedShopGroups[$aShopGroup[\'parent_id\']])
					: 0
				)*/
				->description($aShopGroup[\'description\'])
				->sorting($aShopGroup[\'sorting\'])
				->active($aShopGroup[\'active\'])
				->path(Core_Array::get($aShopGroup, \'path\', Core_Str::transliteration($aShopGroup[\'name\'])))
				->save();

			$Install_Controller->moveShopGroupImage($oShop_Group->id, $sourceShopId = $iShopId, $sourceShopGroupId = $iShopGroupId, $aShopGroup[\'image_large\'], $aShopGroup[\'image_small\'], $oSite->nesting_level);

			CT::$aAssosiatedShopGroups[$iShopGroupId] = $oShop_Group->id;

			CT::$aReplace[\'$shop_group_id = \' . $iShopGroupId . \';\']
				= $aSecondReplace[\'$shop_group_id = \' . $iShopGroupId . \';\'] = \'$shop_group_id = \' . $oShop_Group->id . \';\';

			if (isset($aShopGroup[\'property_values\']))
			{
				foreach ($aShopGroup[\'property_values\'] as $iPropertyValueId => $aPropertyValue)
				{
					$oProperty = Core_Entity::factory(\'Property\')->getById(CT::$aAssosiatedProperties[$aPropertyValue[\'property_id\']], FALSE);

					if (!is_null($oProperty))
					{
						$oProperty_Value = $oProperty->createNewValue($oShop_Group->id);

						switch ($oProperty->type)
						{
							case 0: // Int
							case 1: // String
							case 4: // Textarea
							case 6: // Wysiwyg
							case 7: // Checkbox
							case 8: // Date
							case 9: // Datetime
								$oProperty_Value
									->value($aPropertyValue[\'value\'])
									->save();
							break;

							case 2: //File
								$Install_Controller->moveShopGroupPropertyImage($oShop_Group->id, $oProperty->id, $iShopId, $iShopGroupId, $iPropertyValueId, $oSite->nesting_level, $aPropertyValue[\'file\'], $aPropertyValue[\'file_small\']);
							break;

							case 3: //List
								if (Core::moduleIsActive(\'list\')
									&& isset(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']]))
								{
									$oProperty_Value
										->value(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']])
										->save();
								}
							break;
						}
					}
				}
			}

			if (isset($aShopGroup[\'shop_tab_groups\']))
			{
				foreach ($aShopGroup[\'shop_tab_groups\'] as $iShopTabGroupId => $aShopTabGroup)
				{
					if (isset(CT::$aAssosiatedShopTabs[$aShopTabGroup[\'shop_tab_id\']]))
					{
						$oShop_Tab_Group = Core_Entity::factory(\'Shop_Tab_Group\');
						$oShop_Tab_Group->shop_id = $iShop_Id;
						$oShop_Tab_Group->shop_group_id = $oShop_Group->id;
						$oShop_Tab_Group->shop_tab_id = CT::$aAssosiatedShopTabs[$aShopTabGroup[\'shop_tab_id\']];
						$oShop_Tab_Group->save();
					}
				}
			}
		}

		// Расстановка иерархии групп
		foreach ($aShop[\'shop_groups\'] as $iShopGroupId => $aShopGroup)
		{
			$oShop_Group = Core_Entity::factory(\'Shop_Group\', CT::$aAssosiatedShopGroups[$iShopGroupId]);

			$oShop_Group
				->parent_id($aShopGroup[\'parent_id\'] > 0 && isset(CT::$aAssosiatedShopGroups[$aShopGroup[\'parent_id\']])
					? intval(CT::$aAssosiatedShopGroups[$aShopGroup[\'parent_id\']])
					: 0
				)
				->save();
		}
	}

	//Shop item properties
	if (isset($aShop[\'properties\']))
	{
		foreach ($aShop[\'properties\'] as $iPropertyId => $aProperty)
		{
			$iParent_Property_Id = 0;

			if ($aProperty[\'dirName\'] != \'\')
			{
				$aExplodeDir = explode(\'/\', $aProperty[\'dirName\']);

				foreach ($aExplodeDir as $sDirName)
				{
					if ($sDirName != \'\')
					{
						$sDirName = CT::translate($sDirName);

						$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
						$oProperty_Dir
							->queryBuilder()
							->join(\'shop_item_property_dirs\', \'property_dirs.id\', \'=\', \'shop_item_property_dirs.property_dir_id\')
							->where(\'shop_item_property_dirs.shop_id\', \'=\', $iShop_Id)
							->where(\'property_dirs.parent_id\', \'=\', $iParent_Property_Id);

						$oProperty_Dir = $oProperty_Dir->getByName($sDirName, FALSE);

						if (is_null($oProperty_Dir))
						{
							$oProperty_Dir = Core_Entity::factory(\'Property_Dir\');
							$oProperty_Dir
								->parent_id($iParent_Property_Id)
								->name($sDirName)
								->save();

							$oShop_Item_Property_Dir = Core_Entity::factory(\'Shop_Item_Property_Dir\');
							$oShop_Item_Property_Dir
								->shop_id($iShop_Id)
								->property_dir_id($oProperty_Dir->id)
								->save();
						}

						$iParent_Property_Id = $oProperty_Dir->id;
					}
				}
			}

			$oProperty = Core_Entity::factory(\'Property\');
			$oProperty
				->property_dir_id($iParent_Property_Id)
				->list_id(isset($aProperty[\'list_id\']) && isset(CT::$aAssosiatedLists[$aProperty[\'list_id\']]) ? CT::$aAssosiatedLists[$aProperty[\'list_id\']] : 0)
				->informationsystem_id(0)
				->shop_id(isset($aProperty[\'shop_id\']) ? $aProperty[\'shop_id\'] : 0)
				->name(CT::translate($aProperty[\'name\']))
				->description($aProperty[\'description\'])
				->type($aProperty[\'type\'])
				->default_value($aProperty[\'default_value\'])
				->tag_name($aProperty[\'tag_name\'])
				->sorting($aProperty[\'sorting\'])
				->multiple($aProperty[\'multiple\'])
				->image_large_max_width(isset($aProperty[\'image_large_max_width\']) ? $aProperty[\'image_large_max_width\'] : 300)
				->image_large_max_height(isset($aProperty[\'image_large_max_height\']) ? $aProperty[\'image_large_max_height\'] : 300)
				->image_small_max_width(isset($aProperty[\'image_small_max_width\']) ? $aProperty[\'image_small_max_width\'] : 70)
				->image_small_max_height(isset($aProperty[\'image_small_max_height\']) ? $aProperty[\'image_small_max_height\'] : 70)
				->hide_small_image(isset($aProperty[\'hide_small_image\']) ? $aProperty[\'hide_small_image\'] : 0)
				->save();

			$oShop_Item_Property = Core_Entity::factory(\'Shop_Item_Property\');
			$oShop_Item_Property
				->shop_id($iShop_Id)
				->property_id($oProperty->id)
				->prefix(Core_Array::get($aProperty, \'prefix\', \'\'))
				->filter(Core_Array::get($aProperty, \'filter\', 0))
				->show_in_group(Core_Array::get($aProperty, \'show_in_group\', 1))
				->show_in_item(Core_Array::get($aProperty, \'show_in_item\', 1))
				->save();

			CT::$aAssosiatedProperties[$iPropertyId] = $oProperty->id;

			CT::$aReplace["property_id\', \'=\', {$iPropertyId})"]
				=  $aSecondReplace["property_id\', \'=\', {$iPropertyId})"] = "property_id\', \'=\', {$oProperty->id})";

			CT::$aReplace["\'Property\', {$iPropertyId})"] = "\'Property\', " . $oProperty->id . ")";
			CT::$aReplace[\'$property_id = \' . $iPropertyId . \';\']
				= $aSecondReplace[\'$property_id = \' . $iPropertyId . \';\'] = \'$property_id = \' . $oProperty->id . \';\';

			if (isset($aProperty[\'shop_group_id\']) && is_array($aProperty[\'shop_group_id\']))
			{
				foreach ($aProperty[\'shop_group_id\'] as $iPropertyShopGroupId)
				{
					if (isset(CT::$aAssosiatedShopGroups[$iPropertyShopGroupId]))
					{
						$oShop_Item_Property_For_Group = Core_Entity::factory(\'Shop_Item_Property_For_Group\');
						$oShop_Item_Property_For_Group
							->shop_group_id($iPropertyShopGroupId > 0 ? CT::$aAssosiatedShopGroups[$iPropertyShopGroupId] : 0)
							->shop_item_property_id($oShop_Item_Property->id)
							->shop_id($iShop_Id)
							->save();
					}
				}
			}
		}
	}

	// Shop Payment Systems
	if (isset($aShop[\'shop_payment_systems\']))
	{
		foreach ($aShop[\'shop_payment_systems\'] as $iShopPaymentSystemId => $aShopPaymentSystem)
		{
			$oShop_Payment_System = Core_Entity::factory(\'Shop_Payment_System\');
			$oShop_Payment_System
				->shop_id($oShop->id)
				->name(CT::translate($aShopPaymentSystem[\'name\']))
				->description($aShopPaymentSystem[\'description\'])
				->active($aShopPaymentSystem[\'active\'])
				->sorting($aShopPaymentSystem[\'sorting\'])
				->image_height(isset($aShopPaymentSystem[\'image_height\']) ? $aShopPaymentSystem[\'image_height\'] : 0)
				->image_width(isset($aShopPaymentSystem[\'image_width\']) ? $aShopPaymentSystem[\'image_width\'] : 0)
				->save();

			CT::$aReplace["Shop_Payment_System_Handler{$iShopPaymentSystemId}"] = "Shop_Payment_System_Handler{$oShop_Payment_System->id}";

			$oShop_Payment_System->savePaymentSystemFile($Install_Controller->loadFile($tmpDir . "tmp/hostcmsfiles/shop/pay/handler" . $iShopPaymentSystemId . ".php", CT::$aReplace));

			CT::$aAssosiatedShopPaymentSystems[$iShopPaymentSystemId] = $oShop_Payment_System->id;
		}
	}

	$oDefaultShop = Core_Entity::factory(\'Shop\')->getById(1);
	if (!is_null($oDefaultShop))
	{
		// Shop_Deliveries
		$aShop_Deliveries = $oDefaultShop->Shop_Deliveries->findAll(FALSE);
		foreach ($aShop_Deliveries as $oShop_Delivery)
		{
			$oNew_Shop_Delivery = clone $oShop_Delivery;
			$oNew_Shop_Delivery->shop_id($iShop_Id);
			$oNew_Shop_Delivery->save();

			switch ($oShop_Delivery->type)
			{
				// Доставка по условиям
				case 0:
				default:
					$aShop_Delivery_Conditions = $oShop_Delivery->Shop_Delivery_Conditions->findAll(FALSE);
					foreach($aShop_Delivery_Conditions as $oShop_Delivery_Condition)
					{
						$oNew_Shop_Delivery_Condition = clone $oShop_Delivery_Condition;
						$oNew_Shop_Delivery_Condition->shop_delivery_id = $oNew_Shop_Delivery->id;
						$oNew_Shop_Delivery_Condition->save();
					}
				break;
				// Доставка по формуле
				case 1:
					if (is_file($oShop_Delivery->getHandlerFilePath()))
					{
						$sContent = $oShop_Delivery->loadHandlerFile();

						$sContent = str_replace("Shop_Delivery_Handler" . $oShop_Delivery->id, "Shop_Delivery_Handler" . $oNew_Shop_Delivery->id, $sContent);

						$oNew_Shop_Delivery->saveHandlerFile($sContent);
					}
				break;
			}

			$aShop_Delivery_Payment_Systems = $oShop_Delivery->Shop_Delivery_Payment_Systems->findAll(FALSE);
			foreach ($aShop_Delivery_Payment_Systems as $oShop_Delivery_Payment_System)
			{
				if (isset(CT::$aAssosiatedShopPaymentSystems[$oShop_Delivery_Payment_System->shop_payment_system_id]))
				{
					$oNew_Shop_Delivery_Payment_System = Core_Entity::factory(\'Shop_Delivery_Payment_System\');
					$oNew_Shop_Delivery_Payment_System->shop_delivery_id = $oNew_Shop_Delivery->id;
					$oNew_Shop_Delivery_Payment_System->shop_payment_system_id = CT::$aAssosiatedShopPaymentSystems[$oShop_Delivery_Payment_System->shop_payment_system_id];
					$oNew_Shop_Delivery_Payment_System->save();
				}
			}
		}
	}

	//Shop warehouses
	if (isset($aShop[\'shop_warehouses\']))
	{
		foreach ($aShop[\'shop_warehouses\'] as $iShopWarehouseId => $aShopWarehouse)
		{
			$oShop_Warehouse = Core_Entity::factory(\'Shop_Warehouse\');
			$oShop_Warehouse
				->shop_id($oShop->id)
				->name(CT::translate($aShopWarehouse[\'name\']))
				->sorting($aShopWarehouse[\'sorting\'])
				->active($aShopWarehouse[\'active\'])
				->default($aShopWarehouse[\'default\'])
				->guid(Core_Guid::get())
				->save();

			CT::$aAssosiatedShopWarehouses[$iShopWarehouseId] = $oShop_Warehouse->id;
		}
	}

	//Shop producers
	if (isset($aShop[\'shop_producers\']))
	{
		foreach ($aShop[\'shop_producers\'] as $iShopProducerId => $aShopProducer)
		{
			$oShop_Producer = Core_Entity::factory(\'Shop_Producer\');
			$oShop_Producer
				->shop_id($oShop->id)
				->name(CT::translate($aShopProducer[\'name\']))
				->active($aShopProducer[\'active\'])
				->sorting($aShopProducer[\'sorting\'])
				->path(Core_Str::transliteration($aShopProducer[\'name\']))
				->save();

			method_exists($Install_Controller, \'moveProducerImage\') && $Install_Controller->moveProducerImage($oShop_Producer->id, $sourceShopId = $iShopId, $sourceShopProducerId = $iShopProducerId);

			CT::$aAssosiatedShopProducers[$iShopProducerId] = $oShop_Producer->id;
		}
	}

	//Shop_Discounts
	if (isset($aShop[\'shop_discounts\']))
	{
		foreach ($aShop[\'shop_discounts\'] as $iShopDiscountId => $aShopDiscount)
		{
			$oShop_Discount = Core_Entity::factory(\'Shop_Discount\');
			$oShop_Discount
				->shop_id($oShop->id)
				->name(CT::translate($aShopDiscount[\'name\']))
				->active($aShopDiscount[\'active\'])
				->type($aShopDiscount[\'type\'])
				->value($aShopDiscount[\'value\'])
				->start_datetime($aShopDiscount[\'start_datetime\'])
				->end_datetime($aShopDiscount[\'end_datetime\'])
				->save();

			CT::$aAssosiatedShopDiscounts[$iShopDiscountId] = $oShop_Discount->id;

			CT::$aReplace["shop_discounts.id\', \'=\', {$iShopDiscountId})"]
				=  $aSecondReplace["shop_discounts.id\', \'=\', {$iShopDiscountId})"] = "shop_discounts.id\', \'=\', {$oShop_Discount->id})";

			if (isset($aShopDiscount[\'siteuser_groups\']) && is_array($aShopDiscount[\'siteuser_groups\']))
			{
				foreach ($aShopDiscount[\'siteuser_groups\'] as $siteuser_group_id)
				{
					$oShop_Discount_Siteuser_Group = Core_Entity::factory(\'Shop_Discount_Siteuser_Group\');
					$oShop_Discount_Siteuser_Group->shop_discount_id = $oShop_Discount->id;
					$oShop_Discount_Siteuser_Group->siteuser_group_id = $siteuser_group_id;
					$oShop_Discount_Siteuser_Group->save();
				}
			}
		}
	}

	//Shop_Bonuses
	if (isset($aShop[\'shop_bonuses\']))
	{
		foreach ($aShop[\'shop_bonuses\'] as $iShopBonusId => $aShopBonus)
		{
			$oShop_Bonus = Core_Entity::factory(\'Shop_Bonus\');
			$oShop_Bonus
				->shop_id($oShop->id)
				->name($aShopBonus[\'name\'])
				->active($aShopBonus[\'active\'])
				->type($aShopBonus[\'type\'])
				->value($aShopBonus[\'value\'])
				->start_datetime($aShopBonus[\'start_datetime\'])
				->end_datetime($aShopBonus[\'end_datetime\'])
				->save();

			CT::$aAssosiatedShopBonuses[$iShopBonusId] = $oShop_Bonus->id;

			CT::$aReplace["shop_bonuses.id\', \'=\', {$iShopBonusId})"]
				=  $aSecondReplace["shop_bonuses.id\', \'=\', {$iShopBonusId})"] = "shop_bonuses.id\', \'=\', {$oShop_Bonus->id})";
		}
	}

	//Shop items
	if (isset($aShop[\'shop_items\']))
	{
		foreach ($aShop[\'shop_items\'] as $iShopItemId => $aShopItem)
		{
			$oShop_Item = Core_Entity::factory(\'Shop_Item\');

			$oShop_Item->name = CT::translate($aShopItem[\'name\']);
			$oShop_Item->indexing = $aShopItem[\'indexing\'];

			$oShop_Item
				->shop_id($iShop_Id)
				->shortcut_id($aShopItem[\'shortcut_id\'])
				->shop_tax_id($aShopItem[\'shop_tax_id\'])
				->shop_seller_id($aShopItem[\'shop_seller_id\'])
				->shop_currency_id(isset(CT::$aAssosiatedShopCurrencies[$aShopItem[\'shop_currency_id\']]) ? CT::$aAssosiatedShopCurrencies[$aShopItem[\'shop_currency_id\']] : 0)
				->shop_producer_id(isset(CT::$aAssosiatedShopProducers[$aShopItem[\'shop_producer_id\']]) ? CT::$aAssosiatedShopProducers[$aShopItem[\'shop_producer_id\']] : 0)
				->shop_measure_id($aShopItem[\'shop_measure_id\'])
				->shop_group_id(Core_Array::get(CT::$aAssosiatedShopGroups, $aShopItem[\'shop_group_id\'], 0))
				->type($aShopItem[\'type\'])
				->weight($aShopItem[\'weight\'])
				->length($aShopItem[\'length\'])
				->width($aShopItem[\'width\'])
				->height($aShopItem[\'height\'])
				->marking($aShopItem[\'marking\'])
				->description($aShopItem[\'description\'])
				->text($aShopItem[\'text\'])
				->marking($aShopItem[\'marking\'])
				->sorting($aShopItem[\'sorting\'])
				->active($aShopItem[\'active\'])
				->price($aShopItem[\'price\'])
				->modification_id($aShopItem[\'modification_id\'] > 0 ? Core_Array::get(CT::$aAssosiatedShopItems, $aShopItem[\'modification_id\'], 0) : 0)
				->path(Core_Array::get($aShopItem, \'path\', Core_Str::transliteration($aShopItem[\'name\'])))
				->save();

			$Install_Controller->moveShopItemImage($oShop_Item->id, $sourceShopId = $iShopId, $sourceShopItemId = $iShopItemId, $aShopItem[\'image_large\'], $aShopItem[\'image_small\'], $oSite->nesting_level);

			CT::$aAssosiatedShopItems[$iShopItemId] = $oShop_Item->id;

			CT::$aReplace[\'$shop_item_id = \' . $iShopItemId . \';\']
				= $aSecondReplace[\'$shop_item_id = \' . $iShopItemId . \';\'] = \'$shop_item_id = \' . $oShop_Item->id . \';\';

			//Tags
			if (Core::moduleIsActive(\'tag\') && !empty($aShopItem[\'tags\']))
			{
				$aExplodeTags = explode(\',\', $aShopItem[\'tags\']);

				foreach ($aExplodeTags as $sTagName)
				{
					$oTag = Core_Entity::factory(\'Tag\')->getByName($sTagName, FALSE);

					if (is_null($oTag))
					{
						$oTag = Core_Entity::factory(\'Tag\');
						$oTag
							->tag_dir_id(0)
							->name($sTagName)
							->path($sTagName)
							->save();
					}

					$oTag_Shop_Item = Core_Entity::factory(\'Tag_Shop_Item\');
					$oTag_Shop_Item
						->tag_id($oTag->id)
						->shop_item_id($oShop_Item->id)
						->site_id($oSite->id)
						->save();
				}
			}

			if (isset($aShopItem[\'comments\']))
			{
				foreach ($aShopItem[\'comments\'] as $aShopComment)
				{
					$oComment = Core_Entity::factory(\'Comment\');

					$oComment->author = $aShopComment[\'author\'];
					$oComment->email = $aShopComment[\'email\'];

					$oComment
						->parent_id($aShopComment[\'parent_id\'])
						->subject($aShopComment[\'subject\'])
						->text($aShopComment[\'text\'])
						->phone($aShopComment[\'phone\'])
						->active($aShopComment[\'active\'])
						->grade($aShopComment[\'grade\'])
						->siteuser_id(isset($aShopComment[\'siteuser_id\'])
							? Core_Array::get(CT::$aAssosiatedSiteusers, $aShopComment[\'siteuser_id\'], 0)
							: 0
						)
						->datetime(Core_Date::timestamp2sql(time()));

					$oShop_Item->add($oComment);
				}
			}

			if (isset($aShopItem[\'property_values\']))
			{
				foreach ($aShopItem[\'property_values\'] as $iPropertyValueId => $aPropertyValue)
				{
					$oProperty = Core_Entity::factory(\'Property\')->getById(CT::$aAssosiatedProperties[$aPropertyValue[\'property_id\']], FALSE);

					if (!is_null($oProperty))
					{
						$oProperty_Value = $oProperty->createNewValue($oShop_Item->id);

						switch ($oProperty->type)
						{
							case 0: // Int
							case 1: // String
							case 4: // Textarea
							case 6: // Wysiwyg
							case 7: // Checkbox
							case 8: // Date
							case 9: // Datetime
								$oProperty_Value
									->value($aPropertyValue[\'value\'])
									->save();
							break;

							case 2: //File
								$Install_Controller->moveShopItemPropertyImage($oShop_Item->id, $oProperty->id, $iShopId, $iShopItemId, $iPropertyValueId, $oSite->nesting_level, $aPropertyValue[\'file\'], $aPropertyValue[\'file_small\']);
							break;

							case 3: //List
								if (Core::moduleIsActive(\'list\')
									&& isset(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']]))
								{
									$oProperty_Value
										->value(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']])
										->save();
								}
							break;
						}
					}
				}
			}

			// Скидки
			if (isset($aShopItem[\'discounts\']))
			{
				foreach ($aShopItem[\'discounts\'] as $iShopItemDiscountId => $aShopItemDiscount)
				{
					$oShop_Item_Discount = Core_Entity::factory(\'Shop_Item_Discount\');
					$oShop_Item_Discount
						->shop_item_id($oShop_Item->id)
						->shop_discount_id(isset(CT::$aAssosiatedShopDiscounts[$aShopItemDiscount[\'shop_discount_id\']]) ? CT::$aAssosiatedShopDiscounts[$aShopItemDiscount[\'shop_discount_id\']] : 0)
						->save();
				}
			}

			// Бонусы
			if (isset($aShopItem[\'bonuses\']))
			{
				foreach ($aShopItem[\'bonuses\'] as $iShopItemBonusId => $aShopItemBonus)
				{
					$oShop_Item_Bonus = Core_Entity::factory(\'Shop_Item_Bonus\');
					$oShop_Item_Bonus
						->shop_item_id($oShop_Item->id)
						->shop_bonus_id(CT::$aAssosiatedShopBonuses[$aShopItemBonus[\'shop_bonus_id\']])
						->save();
				}
			}

			// Остатки на складах
			if (isset($aShopItem[\'warehouses\']))
			{
				foreach ($aShopItem[\'warehouses\'] as $iShopWarehouseItemId => $aShopWarehouseItem)
				{
					$oShop_Warehouse_Item = Core_Entity::factory(\'Shop_Warehouse_Item\');
					$oShop_Warehouse_Item
						->shop_warehouse_id(CT::$aAssosiatedShopWarehouses[$aShopWarehouseItem[\'shop_warehouse_id\']])
						->shop_item_id($oShop_Item->id)
						->count($aShopWarehouseItem[\'count\'])
						->save();
				}
			}

			if (isset($aShopItem[\'shop_tab_items\']))
			{
				foreach ($aShopItem[\'shop_tab_items\'] as $iShopTabItemId => $aShopTabItem)
				{
					if (isset(CT::$aAssosiatedShopTabs[$aShopTabItem[\'shop_tab_id\']]))
					{
						$oShop_Tab_Item = Core_Entity::factory(\'Shop_Tab_Item\');
						$oShop_Tab_Item->shop_id = $iShop_Id;
						$oShop_Tab_Item->shop_item_id = $oShop_Item->id;
						$oShop_Tab_Item->shop_tab_id = CT::$aAssosiatedShopTabs[$aShopTabItem[\'shop_tab_id\']];
						$oShop_Tab_Item->save();
					}
				}
			}
		}

		// Отдельный цикл для сопутствующих товаров и комплектов
		foreach ($aShop[\'shop_items\'] as $iShopItemId => $aShopItem)
		{
			// Сопутствующие товары
			if (isset($aShopItem[\'associateds\']))
			{
				foreach ($aShopItem[\'associateds\'] as $aShopItemAssociated)
				{
					if (isset(CT::$aAssosiatedShopItems[$aShopItemAssociated[\'shop_item_associated_id\']]))
					{
						$oShop_Item_Associated = Core_Entity::factory(\'Shop_Item_Associated\');
						$oShop_Item_Associated
							->shop_item_associated_id(CT::$aAssosiatedShopItems[$aShopItemAssociated[\'shop_item_associated_id\']])
							->shop_item_id(CT::$aAssosiatedShopItems[$iShopItemId])
							->count($aShopItemAssociated[\'count\'])
							->save();
					}
				}
			}

			// Комплекты
			if (isset($aShopItem[\'sets\']))
			{
				foreach ($aShopItem[\'sets\'] as $aShopItemSet)
				{
					if (isset(CT::$aAssosiatedShopItems[$aShopItemSet[\'shop_item_set_id\']]))
					{
						$oShop_Item_Sets = Core_Entity::factory(\'Shop_Item_Set\');
						$oShop_Item_Sets
							->shop_item_set_id(CT::$aAssosiatedShopItems[$aShopItemSet[\'shop_item_set_id\']])
							->shop_item_id(CT::$aAssosiatedShopItems[$iShopItemId])
							->count($aShopItemSet[\'count\'])
							->save();
					}
				}
			}
		}
	}

	if ($oShop->filter)
	{
		// Groups
		$Shop_Filter_Group_Controller = new Shop_Filter_Group_Controller($oShop);
		$Shop_Filter_Group_Controller
			->dropTable()
			->createTable()
			->rebuild();

		// Items
		$oShop_Filter_Controller = new Shop_Filter_Controller($oShop);
		$oShop_Filter_Controller
			->dropTable()
			->createTable();

		$limit = 1000;
		$position = 0;

		do {
			$oShop_Items = $oShop->Shop_Items;
			$oShop_Items->queryBuilder()
				->where(\'shop_items.active\', \'=\', 1)
				->limit($limit)
				->offset($position)
				->clearOrderBy()
				->orderBy(\'shop_items.id\');

			$aShop_Items = $oShop_Items->findAll(FALSE);

			foreach ($aShop_Items as $oShop_Item)
			{
				$oShop_Filter_Controller->fill($oShop_Item);
			}

			$position += $limit;
		}
		while(count($aShop_Items));
	}
}
unset($aShopi18n);

//Forums
if (Core::moduleIsActive(\'forum\'))
{
	foreach ($aForumi18n as $iForumId => $aForum)
	{
		$oForum = Core_Entity::factory(\'Forum\');
		$oForum
			->queryBuilder()
			->where(\'forums.site_id\', \'=\', $oSite->id);

		$sForumName = CT::translate($aForum[\'name\']);

		$oForum = $oForum->getByName($sForumName, FALSE);

		if (is_null($oForum))
		{
			$oForum = Core_Entity::factory(\'Forum\');

			$oForum
				->structure_id($aForum[\'structure_id\'])
				->site_id($oSite->id)
				->name($sForumName)
				->description($aForum[\'description\'])
				->topics_on_page($aForum[\'topics_on_page\'])
				->posts_on_page($aForum[\'posts_on_page\'])
				->flood_protection_time($aForum[\'flood_protection_time\'])
				->allow_edit_time($aForum[\'allow_edit_time\'])
				->allow_delete_time($aForum[\'allow_delete_time\'])
				->save();

			CT::$aAssosiatedForums[$iForumId] = $oForum->id;

			if (isset($aForum[\'forum_groups\']))
			{
				foreach ($aForum[\'forum_groups\'] as $iForumGroupId => $aForumGroup)
				{
					$oForum_Group = Core_Entity::factory(\'Forum_Group\');
					$oForum_Group
						->queryBuilder()
						->where(\'forum_groups.forum_id\', \'=\', $oForum->id);

					$sForumGroupName = CT::translate($aForumGroup[\'name\']);

					$oForum_Group = $oForum_Group->getByName($sForumGroupName, FALSE);

					if (is_null($oForum_Group))
					{
						$oForum_Group = Core_Entity::factory(\'Forum_Group\');
						$oForum_Group
							->name($sForumGroupName)
							->description($aForumGroup[\'description\'])
							->sorting($aForumGroup[\'sorting\'])
							->forum_id($oForum->id)
							->save();

						if (isset($aForumGroup[\'forum_categories\']))
						{
							foreach ($aForumGroup[\'forum_categories\'] as $iForumCategoryId => $aForumCategory)
							{
								$oForum_Category = Core_Entity::factory(\'Forum_Category\');
								$oForum_Category
									->queryBuilder()
									->where(\'forum_categories.forum_group_id\', \'=\', $oForum_Group->id);

								$oForum_Category = $oForum_Category->getByName(CT::translate($aForumCategory[\'name\']), FALSE);

								if (is_null($oForum_Category))
								{
									$oForum_Category = Core_Entity::factory(\'Forum_Category\');
									$oForum_Category
										->forum_group_id($oForum_Group->id)
										->name(CT::translate($aForumCategory[\'name\']))
										->description($aForumCategory[\'description\'])
										->closed($aForumCategory[\'closed\'])
										->sorting($aForumCategory[\'sorting\'])
										->email($aForumCategory[\'email\'])
										->postmoderation($aForumCategory[\'postmoderation\'])
										->visible($aForumCategory[\'visible\'])
										->use_captcha($aForumCategory[\'use_captcha\'])
										->allow_guest_posting($aForumCategory[\'allow_guest_posting\'])
										->save();

									if (isset($aForumCategory[\'forum_topics\']))
									{
										/** @var array $aForumCategory */
										foreach ($aForumCategory[\'forum_topics\'] as $iForumTopicId => $aForumTopic)
										{
											$oForum_Topic = Core_Entity::factory(\'Forum_Topic\');
											$oForum_Topic
												->forum_category_id($oForum_Category->id)
												->visible($aForumTopic[\'visible\'])
												->announcement($aForumTopic[\'announcement\'])
												->closed($aForumTopic[\'closed\'])
												->save();
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	unset($aForumi18n);
}

//Helpdesks
if (Core::moduleIsActive(\'helpdesk\'))
{
	foreach ($aHelpdeski18n as $iHelpdekId => $aHelpdesk)
	{
		$oHelpdesk = Core_Entity::factory(\'Helpdesk\');
		$oHelpdesk
			->queryBuilder()
			->where(\'helpdesks.site_id\', \'=\', $oSite->id);

		$sHelpdeskName = CT::translate($aHelpdesk[\'name\']);

		$oHelpdesk = $oHelpdesk->getByName($sHelpdeskName, FALSE);

		if (is_null($oHelpdesk))
		{
			$oHelpdesk = Core_Entity::factory(\'Helpdesk\');

			$oHelpdesk
				->structure_id($aHelpdesk[\'structure_id\'])
				->site_id($oSite->id)
				->name($sHelpdeskName)
				->notify($aHelpdesk[\'notify\'])
				->notify_change_criticality_level($aHelpdesk[\'notify_change_criticality_level\'])
				->delete_attach_in_days($aHelpdesk[\'delete_attach_in_days\'])
				->helpdesk_category_id(0)
				->save();

			CT::$aAssosiatedHelpdesks[$iHelpdekId] = $oHelpdesk->id;
		}
	}
	unset($aHelpdeski18n);
}

//Advertisements
if (Core::moduleIsActive(\'advertisement\'))
{
	foreach ($aAdvertisementGroupi18n as $iAdvGroupId => $aAdvertisementGroups)
	{
		$oAdvertisement_Group = Core_Entity::factory(\'Advertisement_Group\');
		$oAdvertisement_Group
			->queryBuilder()
			->where(\'advertisement_groups.site_id\', \'=\', $oSite->id);

		$oAdvertisement_Group = $oAdvertisement_Group->getByName(CT::translate($aAdvertisementGroups[\'name\']), FALSE);

		if (is_null($oAdvertisement_Group))
		{
			$oAdvertisement_Group = Core_Entity::factory(\'Advertisement_Group\');

			$oAdvertisement_Group
				->name(CT::translate($aAdvertisementGroups[\'name\']))
				->description($aAdvertisementGroups[\'description\'])
				->site_id($oSite->id)
				->save();

			CT::$aReplace["\'Advertisement_Group\', {$iAdvGroupId})"] = "\'Advertisement_Group\', " . $oAdvertisement_Group->id . ")";

			isset($aAdvertisementGroups["field_values"])
				&& CT::importFields($aAdvertisementGroups["field_values"], $oAdvertisement_Group);

			if (isset($aAdvertisementGroups[\'advertisement\']))
			{
				foreach ($aAdvertisementGroups[\'advertisement\'] as $iAdvId => $aAdvertisements)
				{
					$oAdvertisement = Core_Entity::factory(\'Advertisement\');
					$oAdvertisement
						->queryBuilder()
						->where(\'advertisements.site_id\', \'=\', $oSite->id);

					$oAdvertisement = $oAdvertisement->getByName(CT::translate($aAdvertisements[\'name\']), FALSE);

					if (is_null($oAdvertisement) && is_file($tmpDir . "tmp/upload/img/" . $aAdvertisements[\'file_name\']))
					{
						$oAdvertisement = Core_Entity::factory(\'Advertisement\');

						$oAdvertisement
							->name(CT::translate($aAdvertisements[\'name\']) . "-" . $oSite->id)
							->description($aAdvertisements[\'description\'])
							->type($aAdvertisements[\'type\'])
							->site_id($oSite->id)
							->href($aAdvertisements[\'href\'])
							->start_datetime(Core_Date::timestamp2sql(time()))
							->end_datetime(Core_Date::timestamp2sql(strtotime("+1 year", time())))
							->save();

						try {
							$oAdvertisement->saveFile($tmpDir . "tmp/upload/img/" . $aAdvertisements[\'file_name\'], $aAdvertisements[\'file_name\']);
						}
						catch (Exception $e) {
							Core_Message::show($e->getMessage(), "error");
						}

						$oAdvertisement_Group_List = Core_Entity::factory(\'Advertisement_Group_List\');
						$oAdvertisement_Group_List
							->advertisement_group_id($oAdvertisement_Group->id)
							->advertisement_id($oAdvertisement->id)
							->probability(100)
							->save();

						isset($aAdvertisements["field_values"])
							&& CT::importFields($aAdvertisements["field_values"], $oAdvertisement);
					}
				}
			}
		}

		CT::$aAssosiatedAdvertisementGroups[$iAdvGroupId] = $oAdvertisement_Group->id;
	}
	unset($aAdvertisementGroupi18n);
}

//Templates
foreach ($aTemplatei18n as $iTemplateId => $aTemplate)
{
	$sTemplateName = CT::translate($aTemplate[\'name\']);

	$oTemplate = Core_Entity::factory(\'Template\')->getByName($sTemplateName . $sSitePostfix, FALSE);

	if (is_null($oTemplate))
	{
		$aExplodeDir = explode(\'/\', $aTemplate[\'dirName\']);
		array_unshift($aExplodeDir, $sSitePostfix);

		$iParent_Id = 0;

		foreach ($aExplodeDir as $sDirName)
		{
			if ($sDirName != \'\')
			{
				$oTemplate_Dir = Core_Entity::factory(\'Template_Dir\');
				$oTemplate_Dir
					->queryBuilder()
					->where(\'template_dirs.parent_id\', \'=\', $iParent_Id);

				$oTemplate_Dir = $oTemplate_Dir->getByName($sDirName, FALSE);

				if (is_null($oTemplate_Dir))
				{
					$oTemplate_Dir = Core_Entity::factory(\'Template_Dir\');
					$oTemplate_Dir
						->parent_id($iParent_Id)
						->name($sDirName)
						->site_id($oSite->id)
						->save();
				}

				$iParent_Id = $oTemplate_Dir->id;
			}
		}

		$oTemplate = Core_Entity::factory(\'Template\');
		$oTemplate
			->name($sTemplateName . $sSitePostfix)
			->template_id(0 /*$aTemplate[\'parent_template_id\'] > 0
				? Core_Array::get(CT::$aAssosiatedTemplates, $aTemplate[\'parent_template_id\'], 0)
				: 0*/
			)
			->template_dir_id($iParent_Id)
			->site_id($oSite->id)
			->type($aTemplate[\'type\'])
			->save();

		if (isset($aTemplate[\'template_sections\']))
		{
			foreach ($aTemplate[\'template_sections\'] as $iTemplateSectionId => $aTemplateSection)
			{
				$oTemplate_Section = Core_Entity::factory(\'Template_Section\');

				$oTemplate_Section
					->template_id($oTemplate->id)
					->name(Core_Array::get($aTemplateSection, \'name\'))
					->alias(Core_Array::get($aTemplateSection, \'alias\'))
					->prefix(Core_Array::get($aTemplateSection, \'prefix\'))
					->suffix(Core_Array::get($aTemplateSection, \'suffix\'))
					->color(Core_Array::get($aTemplateSection, \'color\'))
					->sorting(Core_Array::get($aTemplateSection, \'sorting\'))
					->save();

				if (isset($aTemplateSection[\'template_section_libs\']))
				{
					foreach ($aTemplateSection[\'template_section_libs\'] as $iTemplateSectionLibId => $aTemplateSectionLib)
					{
						$oTemplate_Section_Lib = Core_Entity::factory(\'Template_Section_Lib\');
						$oTemplate_Section_Lib
							->template_section_id($oTemplate_Section->id)
							->lib_id(
								Core_Array::get(CT::$aAssosiatedLibs, $aTemplateSectionLib[\'lib_id\'], 0)
							)
							->options(Core_Array::get($aTemplateSectionLib, \'options\'))
							->class(Core_Array::get($aTemplateSectionLib, \'class\'))
							->style(Core_Array::get($aTemplateSectionLib, \'style\'))
							->active(Core_Array::get($aTemplateSectionLib, \'active\'))
							->sorting(Core_Array::get($aTemplateSectionLib, \'sorting\'))
							->save();

						// Files
						$sourceWidgetDir = "upload/libs/lib_{$aTemplateSectionLib[\'lib_id\']}/widget_{$iTemplateSectionLibId}/";
						$sSourceWidget = $tmpDir . "tmp/{$sourceWidgetDir}";
						if (is_dir($sSourceWidget))
						{
							CT::$aReplace[$sourceWidgetDir] = "upload/libs/lib_{$oTemplate_Section_Lib->lib_id}/widget_{$oTemplate_Section_Lib->id}/";

							Core_File::copyDir($sSourceWidget, $oTemplate_Section_Lib->getLibFilePath());
						}

						// options
						if (strlen($oTemplate_Section_Lib->options))
						{
							// Подмена значений для нового сайта
							$aTmpDat = json_decode($oTemplate_Section_Lib->options, TRUE);

							if (is_array($aTmpDat))
							{
								$aTmpDat = CT::replaceOptions($aTmpDat);
								$oTemplate_Section_Lib->options = json_encode($aTmpDat);
								$oTemplate_Section_Lib->save();
							}
						}
					}
				}
			}
		}

		$oTemplate->saveTemplateFile($Install_Controller->loadFile($tmpDir . "tmp/templates/template" . $iTemplateId . "/template.htm", CT::$aReplace));

		$sTmpCssPath = $tmpDir . "tmp/templates/template" . $iTemplateId . "/style.css";
		if (is_file($sTmpCssPath))
		{
			$oTemplate->saveTemplateCssFile($Install_Controller->loadFile($sTmpCssPath, CT::$aReplace));
		}

		$sTmpLessPath = $tmpDir . "tmp/templates/template" . $iTemplateId . "/style.less";
		if (is_file($sTmpLessPath))
		{
			try
			{
				$oTemplate->saveTemplateLessFile($Install_Controller->loadFile($sTmpLessPath, CT::$aReplace));
			}
			catch (Exception $e)
			{
				Core_Message::show($e->getMessage(), \'error\');
			}
		}

		$sTmpScssPath = $tmpDir . "tmp/templates/template" . $iTemplateId . "/style.scss";
		if (is_file($sTmpScssPath))
		{
			try
			{
				$oTemplate->saveTemplateScssFile($Install_Controller->loadFile($sTmpScssPath, CT::$aReplace));
			}
			catch (Exception $e)
			{
				Core_Message::show($e->getMessage(), \'error\');
			}
		}

		$sTmpJsPath = $tmpDir . "tmp/templates/template" . $iTemplateId . "/script.js";
		if (is_file($sTmpJsPath))
		{
			$oTemplate->saveTemplateJsFile($Install_Controller->loadFile($sTmpJsPath, CT::$aReplace));
		}

		$sTmpManifestPath = $tmpDir . "tmp/templates/template" . $iTemplateId . "/manifest.xml";
		if (is_file($sTmpManifestPath))
		{
			$oTemplate->saveManifestFile($Install_Controller->loadFile($sTmpManifestPath, CT::$aReplace));
		}

		foreach ($aLngs as $sTmpLng)
		{
			$i18nPath = $tmpDir . "tmp/templates/template{$iTemplateId}/i18n/{$sTmpLng}.php";

			if (is_file($i18nPath))
			{
				$oTemplate->saveLngFile($sTmpLng, $Install_Controller->loadFile($i18nPath, CT::$aReplace));
			}
		}
	}

	$aSecondReplace["\'Template\', {$iTemplateId})"]
		= CT::$aReplace["\'Template\', {$iTemplateId})"] = "\'Template\', " . $oTemplate->id . ")";

	CT::$aReplace[\'$template_id = \' . $iTemplateId . \';\']
		= $aSecondReplace[\'$template_id = \' . $iTemplateId . \';\'] = \'$template_id = \' . $oTemplate->id . \';\';

	CT::$aAssosiatedTemplates[$iTemplateId] = $oTemplate->id;
}
// Установка иерархии макетов
foreach ($aTemplatei18n as $iTemplateId => $aTemplate)
{
	$oTemplate = Core_Entity::factory(\'Template\', CT::$aAssosiatedTemplates[$iTemplateId]);
	$oTemplate->template_id = Core_Array::get(CT::$aAssosiatedTemplates, $aTemplate[\'parent_template_id\'], 0);
	$oTemplate->template_id
		&& $oTemplate->template_dir_id = 0;
	$oTemplate->save();
}

// Documents
foreach ($aDoci18n as $iDocId => $aDocument)
{
	$sDocumentName = CT::translate($aDocument[\'name\']);

	$oDocument = Core_Entity::factory(\'Document\')->getByName($sDocumentName . $sSitePostfix, FALSE);

	if (is_null($oDocument))
	{
		$aExplodeDir = explode(\'/\', $aDocument[\'dirName\']);
		array_unshift($aExplodeDir, $sSitePostfix);

		$iParent_Id = 0;
		foreach ($aExplodeDir as $sDirName)
		{
			if ($sDirName != \'\')
			{
				$oDocument_Dir = Core_Entity::factory(\'Document_Dir\');
				$oDocument_Dir
					->queryBuilder()
					->where(\'document_dirs.parent_id\', \'=\', $iParent_Id);

				$oDocument_Dir = $oDocument_Dir->getByName($sDirName, FALSE);

				if (is_null($oDocument_Dir))
				{
					$oDocument_Dir = Core_Entity::factory(\'Document_Dir\');
					$oDocument_Dir
						->parent_id($iParent_Id)
						->site_id($oSite->id)
						->name($sDirName)
						->save();
				}

				$iParent_Id = $oDocument_Dir->id;
			}
		}

		$oDocument = Core_Entity::factory(\'Document\');
		$oDocument
			->name($sDocumentName . $sSitePostfix)
			->document_dir_id($iParent_Id)
			->text(
				$Install_Controller->macroReplace($aDocument[\'text\'], CT::$aReplace)
			)
			->datetime($aDocument[\'datetime\'])
			->template_id(isset(CT::$aAssosiatedTemplates[$aDocument[\'template_id\']]) ? CT::$aAssosiatedTemplates[$aDocument[\'template_id\']] : 0)
			->site_id($oSite->id)
			->save();
	}

	$aSecondReplace["\'Document\', {$iDocId})"]
		= CT::$aReplace["\'Document\', {$iDocId})"] = "\'Document\', " . $oDocument->id . ")";

	CT::$aAssosiatedDocuments[$iDocId] = $oDocument->id;
}
unset($aDoci18n);

//Structures
foreach ($aStructurei18n as $iStructureId => $aStructure)
{
	$oStructure = Core_Entity::factory(\'Structure\');

	$oStructure->name = CT::translate($aStructure[\'name\']);
	$oStructure->indexing = $aStructure[\'indexing\'];
	$oStructure->type = $aStructure[\'type\'];
	$oStructure->active = $aStructure[\'active\'];
	$oStructure->path = $aStructure[\'path\'] != \'\'
		? $aStructure[\'path\']
		: Core_Str::transliteration($aStructure[\'name\']);

	$oStructure->url = $aStructure[\'url\'];

	$oStructure
		->structure_menu_id(Core_Array::get(CT::$aAssosiatedStructureMenus, $aStructure[\'structure_menu_id\'], 0))
		->template_id(Core_Array::get(CT::$aAssosiatedTemplates, $aStructure[\'template_id\'], 0))
		->siteuser_group_id(Core_Array::get(CT::$aAssosiatedSiteuserGroups, Core_Array::get($aStructure, \'siteuser_group_id\', 0), 0))
		->site_id($oSite->id)
		->document_id(isset($aStructure[\'document_id\'])
			? Core_Array::get(CT::$aAssosiatedDocuments, $aStructure[\'document_id\'], 0)
			: 0
		)
		->lib_id(isset($aStructure[\'lib_id\'])
			? Core_Array::get(CT::$aAssosiatedLibs, $aStructure[\'lib_id\'], $aStructure[\'lib_id\'])
			: 0
		)
		->parent_id($aStructure[\'parent_id\'] > 0
			? Core_Array::get(CT::$aAssosiatedStructures, $aStructure[\'parent_id\'], 0)
			: 0
		)
		->show($aStructure[\'show\'])
		->sorting($aStructure[\'sorting\'])
		->seo_title($aStructure[\'seo_title\'])
		->seo_description($aStructure[\'seo_description\'])
		->seo_keywords($aStructure[\'seo_keywords\'])
		->options($aStructure[\'options\'])
		->save();

	if ($oStructure->type == 1)
	{
		$oStructure->saveStructureFile($Install_Controller->loadFile($tmpDir . "tmp/hostcmsfiles/structure/Structure" . $iStructureId . ".php", CT::$aReplace));
		$oStructure->saveStructureConfigFile($Install_Controller->loadFile($tmpDir . "tmp/hostcmsfiles/structure/StructureConfig" . $iStructureId . ".php", CT::$aReplace));
	}

	// В конце скобка или пробел
	$aSecondReplace["CURRENT_STRUCTURE_ID == {$iStructureId})"]
			= CT::$aReplace["CURRENT_STRUCTURE_ID == {$iStructureId})"] = "CURRENT_STRUCTURE_ID == " . $oStructure->id . ")";

	$aSecondReplace["CURRENT_STRUCTURE_ID == {$iStructureId} "]
			= CT::$aReplace["CURRENT_STRUCTURE_ID == {$iStructureId} "] = "CURRENT_STRUCTURE_ID == " . $oStructure->id . " ";

	// Вначале скобка или пробел
	$aSecondReplace["({$iStructureId} == CURRENT_STRUCTURE_ID"]
			= CT::$aReplace["({$iStructureId} == CURRENT_STRUCTURE_ID"] = "(CURRENT_STRUCTURE_ID == " . $oStructure->id;

	$aSecondReplace[" {$iStructureId} == CURRENT_STRUCTURE_ID"]
			= CT::$aReplace[" {$iStructureId} == CURRENT_STRUCTURE_ID"] = " CURRENT_STRUCTURE_ID == " . $oStructure->id;

	$aSecondReplace["\'Structure\', {$iStructureId})"]
		= CT::$aReplace["\'Structure\', {$iStructureId})"] = "\'Structure\', " . $oStructure->id . ")";

	$aSecondReplace[\'$structure_id = \' . $iStructureId . ";"]
		= CT::$aReplace[\'$structure_id = \' . $iStructureId . ";"] = \'$structure_id = \' . $oStructure->id . ";";

	$aSecondReplace["->parentId({$iStructureId})"]
		= CT::$aReplace["->parentId({$iStructureId})"] = "->parentId(" . $oStructure->id . ")";

	CT::$aAssosiatedStructures[$iStructureId] = $oStructure->id;

	// options для узла структуры
	if (isset($aStructure[\'lib_id\']) && $aStructure[\'lib_id\'] > 0)
	{
		if (strlen($oStructure->options))
		{
			// Подмена значений для нового сайта
			$aTmpDat = json_decode($oStructure->options, TRUE);

			if (is_array($aTmpDat))
			{
				$aTmpDat = CT::replaceOptions($aTmpDat);
				$oStructure->options = json_encode($aTmpDat);
				$oStructure->save();
			}
		}
	}

	if (isset($aStructure[\'property_values\']))
	{
		foreach ($aStructure[\'property_values\'] as $iPropertyValueId => $aPropertyValue)
		{
			$oProperty = Core_Entity::factory(\'Property\')->getById(CT::$aAssosiatedProperties[$aPropertyValue[\'property_id\']], FALSE);

			if (!is_null($oProperty))
			{
				$oProperty_Value = $oProperty->createNewValue($oStructure->id);

				switch ($oProperty->type)
				{
					case 0: // Int
					case 1: // String
					case 4: // Textarea
					case 6: // Wysiwyg
					case 7: // Checkbox
					case 8: // Date
					case 9: // Datetime
						$oProperty_Value
							->value($aPropertyValue[\'value\'])
							->save();
					break;

					case 2: //File
						$Install_Controller->MoveStructureItemPropertyImage($oStructure->id, $oProperty->id, $aStructure[\'site_id\'], $iStructureId, $iPropertyValueId, $oSite->nesting_level, $aPropertyValue[\'file\'], $aPropertyValue[\'file_small\']);
					break;

					case 3: //List
						if (Core::moduleIsActive(\'list\')
							&& isset(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']]))
						{
							$oProperty_Value
								->value(CT::$aAssosiatedListValues[$aPropertyValue[\'value\']])
								->save();
						}
					break;
				}
			}
		}
	}
}
unset($aStructurei18n);

// Повторный цикл по макетам для подмены ID
foreach ($aTemplatei18n as $iTemplateId => $aTemplate)
{
	$oTemplate = Core_Entity::factory(\'Template\')->getByName(CT::translate($aTemplate[\'name\']) . $sSitePostfix, FALSE);

	if (!is_null($oTemplate))
	{
		$oTemplate->saveTemplateFile($Install_Controller->loadFile($oTemplate->getTemplateFilePath(), $aSecondReplace));
	}
}
unset($aTemplatei18n);

// Повторный цикл по ТДС для подмены ID макетов
foreach ($aLibi18n as $iLibId => $aLib)
{
	$oLib = Core_Entity::factory(\'Lib\')->getByName(CT::translate($aLib[\'name\']) . $sSitePostfix, FALSE);

	if (!is_null($oLib))
	{
		$oLib->saveLibConfigFile($Install_Controller->loadFile($oLib->getLibConfigFilePath(), $aSecondReplace));
		$oLib->saveLibFile($Install_Controller->loadFile($oLib->getLibFilePath(), $aSecondReplace));
	}
}
unset($aLibi18n);

// Цикл для подмены lng и import
foreach ($aXsli18n as $sFileName => $aXsl)
{
	$oXsl = Core_Entity::factory(\'Xsl\')->getByName(CT::translate($aXsl[\'name\']) . $sSitePostfix, FALSE);

	if (!is_null($oXsl))
	{
		$oXsl->saveXslFile($Install_Controller->loadFile($oXsl->getXslFilePath(), $aSecondReplace));
	}
}
unset($aXsli18n);

// Подмена ID узлов структуры
//403
if (array_key_exists($oSite->error403, CT::$aAssosiatedStructures))
{
	$oSite->error403 = CT::$aAssosiatedStructures[$oSite->error403];
	$oSite->save();
}

//404
if (array_key_exists($oSite->error404, CT::$aAssosiatedStructures))
{
	$oSite->error404 = CT::$aAssosiatedStructures[$oSite->error404];
	$oSite->save();
}

//503
if (array_key_exists($oSite->closed, CT::$aAssosiatedStructures))
{
	$oSite->closed = CT::$aAssosiatedStructures[$oSite->closed];
	$oSite->save();
}

if (Core::moduleIsActive(\'poll\'))
{
	$aTmpPollGroups = $oSite->Poll_Groups->findAll(FALSE);
	foreach ($aTmpPollGroups as $oPollGroup)
	{
		if (array_key_exists($oPollGroup->structure_id, CT::$aAssosiatedStructures))
		{
			$oPollGroup->structure_id = CT::$aAssosiatedStructures[$oPollGroup->structure_id];
			$oPollGroup->save();
		}
	}
}

$aTmpInformationsystems = $oSite->Informationsystems->findAll(FALSE);
foreach ($aTmpInformationsystems as $oInformationsystem)
{
	if (array_key_exists($oInformationsystem->structure_id, CT::$aAssosiatedStructures))
	{
		$oInformationsystem->structure_id = CT::$aAssosiatedStructures[$oInformationsystem->structure_id];
		$oInformationsystem->save();
	}
}

$aTmpShops = $oSite->Shops->findAll(FALSE);
foreach ($aTmpShops as $oShop)
{
	if (array_key_exists($oShop->structure_id, CT::$aAssosiatedStructures))
	{
		$oShop->structure_id = CT::$aAssosiatedStructures[$oShop->structure_id];
		$oShop->save();
	}
}

if (Core::moduleIsActive(\'forum\'))
{
	$aTmpForums = $oSite->Forums->findAll(FALSE);
	foreach ($aTmpForums as $oForum)
	{
		if (array_key_exists($oForum->structure_id, CT::$aAssosiatedStructures))
		{
			$oForum->structure_id = CT::$aAssosiatedStructures[$oForum->structure_id];
			$oForum->save();
		}
	}
}

if (Core::moduleIsActive(\'helpdesk\'))
{
	$aTmpHelpdesks = $oSite->Helpdesks->findAll(FALSE);
	foreach ($aTmpHelpdesks as $oHelpdesk)
	{
		if (array_key_exists($oHelpdesk->structure_id, CT::$aAssosiatedStructures))
		{
			$oHelpdesk->structure_id = CT::$aAssosiatedStructures[$oHelpdesk->structure_id];
			$oHelpdesk->save();
		}
	}
}

if (Core::moduleIsActive(\'field\'))
{
	$aTmpFields = Core_Entity::factory(\'Field\')->findAll(FALSE);
	foreach ($aTmpFields as $oField)
	{
		if (array_key_exists($oField->list_id, CT::$aAssosiatedLists))
		{
			$oField->list_id = CT::$aAssosiatedLists[$oField->list_id];
			$oField->save();
		}

		if (array_key_exists($oField->informationsystem_id, CT::$aAssosiatedInformationsystems))
		{
			$oField->informationsystem_id = CT::$aAssosiatedInformationsystems[$oField->informationsystem_id];
			$oField->save();
		}

		if (array_key_exists($oField->shop_id, CT::$aAssosiatedShops))
		{
			$oField->shop_id = CT::$aAssosiatedShops[$oField->shop_id];
			$oField->save();
		}
	}
}
';
}

	// Создаем файл .php
	$source_file = $templateDir . $filename;
	Core_File::write($source_file, $content);

	// Создаем файл .xml
	$source_file_xml = $templateDir . $filename_xml;

	$content_xml = '<?xml version="1.0" encoding="UTF-8"?>
<module>
	<options>
		<create_module>0</create_module>
	</options>
</module>
';
		if (!is_file($source_file_xml))
		{
			Core_File::write($source_file_xml, $content_xml);
		}

		// Константа для результата
		$isReady = 1;
}
?>

<!doctype html>
<html lang="ru">
<head>
	<meta charset="UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<title>Создание пакета установки для макета сайта</title>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
	<!--[if lt IE 9]>
	<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
	<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
	<![endif]-->
	<style>
		.dir-block { margin-left: 20px }
		.dir-block > div:first-child { font-weight: 600 }

		.margin-right-10 { margin-right: 10px !important }

		.select-all { font-size: 10px; color: blue }
		.select-all input { margin-top: 0 }
		.items-list { margin-bottom: 40px }
	</style>
</head>
<body>
<div class="container">
	<div class="page-header"  style="margin-bottom: 40px;">
		<img src="https://www.hostcms.ru/images/logo.gif" class="pull-right"/>
		<h1>Создание пакета установки</h1>
	</div>

	<?php
	if (Core_Array::getPost('apply') && Core_Array::getPost('step_2'))
	{
		if ($isReady == 1)
		{
			$aMessages[] = array('type' => 'success', 'text' => "Пакет создан");
		}
		else
		{
			$aMessages[] = array('type' => 'danger', 'text' => "В процесе подготовки пакета возникла ошибка!");
		}
	}
	elseif (!Core_Array::getPost('site_id'))
	{
		$aMessages[] = array('type' => 'warning', 'text' => "Не выбран сайт");
	}
	else
	{
		$aMessages[] = array('type' => 'success', 'text' => "Сайт выбран");
	}

	foreach ($aMessages as $aMessage)
	{
		?><div class="alert alert-<?php echo $aMessage['type']?>" role="alert"><?php echo $aMessage['text']?></div><?php
	}
	?>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
	<script>
		$(function() {
			$(".check-checkboxes").change(function(){
				$(this).parents('.dir-block,.items-list').eq(0).find(':checkbox').prop('checked', $(this).is(':checked'));
			});
		});
	</script>

	<?php
	if (!Core_Array::getPost('step_1'))
	{
	?>
		<form name="template-create" action="create_template.php" method="POST" enctype="multipart/form-data">
			<section  style="margin: 40px 0;">
				<p>Скрипт создаст папку create_template в корне. В ней будут создаваться папки вида site_XXX, где XXX — ID выбранного в грабере сайта.</p>
				<p>Папка tmp будет содержать исходные файлы системы (XSL, ТДС и т.д.), а вот в files (из которой при установке макета все копируется один к одному) нужно будет размещать доп.файлы вашего макета. Например, js-скрипты и т.д. Т.е. то, чего нет в стандартной поставке, но есть в вашем макете.</p>

				<div class="alert alert-danger" role="alert"><b>ВНИМАНИЕ! Паковать в tar.gz необходимо только содержимое получившейся папки site_XXX!</b></div>
			</section>

			<section class="form-group" style="margin-bottom: 40px;">
				<h2 class="h4">1. Выберите сайт:</h2>
				<select name="site_id" class="form-control">
					<option value="0">...</option>
					<?php Install::setSites(); ?>
				</select>
			</section>

			<hr/>

			<p class="clearfix" style="margin-bottom: 100px;">
				<input type="submit" name="apply" class="btn btn-primary" value="Далее"/>
			</p>

			<input name="step_1" value="step_1" type="hidden"/>
		</form>

	<?php
	}
	elseif (Core_Array::getPost('step_1'))
	{
		Install::$iSiteId = intval(Core_Array::getPost('site_id'));
		?>
		<form name="template-create" action="create_template.php" method="POST" enctype="multipart/form-data">
			<section  style="margin: 40px 0;">
				<p>Скрипт создаст папку create_template в корне. В ней будут создаваться папки вида site_XXX, где XXX — ID выбранного в грабере сайта.</p>
				<p>Папка tmp будет содержать исходные файлы системы (XSL, ТДС, TPL и т.д.), а вот в files (из которой при установке макета все копируется один к одному) нужно будет размещать доп.файлы вашего макета. Например, js-скрипты и т.д. Т.е. то, чего нет в стандартной поставке, но есть в вашем макете.</p>

				<div class="alert alert-danger" role="alert"><b>ВНИМАНИЕ! Паковать в tar.gz необходимо только содержимое получившейся папки site_XXX!</b></div>
			</section>
			<section class="form-group items-list">
				<h2 class="h4">2. XSL для пакета установки:</h2>

				<div class="checkbox">
					<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
				</div>

				<?php Install::setXsls()?>
			</section>
			<section class="form-group items-list">
				<h2 class="h4">3. ТДС для пакета установки:</h2>

				<div class="checkbox">
					<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
				</div>

				<?php Install::setLibs()?>
			</section>
			<?php
			if (Core::moduleIsActive('tpl'))
			{
				?>
				<section class="form-group items-list">
					<h2 class="h4">4. TPL для пакета установки:</h2>

					<div class="checkbox">
						<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
					</div>

					<?php Install::setTpls()?>
				</section>
			<?php
			}

			if (Core::moduleIsActive('shop'))
			{
				?>
				<section class="form-group items-list">
					<h2 class="h4">5. Платежные системы:</h2>

					<div class="checkbox">
						<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
					</div>

					<?php Install::setPaymentSystems()?>
				</section>
			<?php
			}

			?>
			<section class="form-group items-list">
				<h2 class="h4">6. Константы:</h2>

				<div class="checkbox">
					<label class="select-all"><input type="checkbox" class="check-checkboxes">Выбрать всё</label>
				</div>

				<?php Install::setConstants()?>
			</section>

			<hr/>

			<p class="clearfix" style="margin-bottom: 100px;">
				<input type="submit" name="apply" class="btn btn-primary" value="Подготовить пакет"/>
			</p>

			<input name="step_2" value="step_2" type="hidden"/>
			<input name="site_id" value="<?php echo Install::$iSiteId?>" type="hidden"/>
		</form>
		<?php
	}
	?>
</div>
</body>
</html>