<?php

/**
 * Автоматическая генерация пакета установки виджета
 *
 * @package HostCMS
 * @version 6.x
 * @author Hostmake LLC
 * @copyright © 2005-2017 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 */

require_once(dirname(__FILE__) . '/' . 'bootstrap.php');

define('CURRENT_SITE', 1);

$oSite = Core_Entity::factory('Site', CURRENT_SITE);
Core::initConstants($oSite);

// Массив сообщений
$aMessages = array();

// Экранирование апострофа
function addslashesapostrophe($str)
{
	return str_replace("'", "\'", $str);
}

// Заполнение списка типовых динамических страниц
function setLibs()
{
	$oLibs = Core_Entity::factory('Lib');

	$oLibs
		->queryBuilder()
		->clearOrderBy()
		->orderBy('libs.id', 'DESC');

	$aLibs = $oLibs->findAll(FALSE);

	foreach ($aLibs as $oLib)
	{
		?><option value="<?php echo $oLib->id?>" <?php echo Core_Array::getPost('lib_id') == $oLib->id ? 'selected="selected"' : ''?>><?php echo htmlspecialchars($oLib->name) . " [" . $oLib->id . "]"?></option><?php
	}
}

// Заполнение списка XSL-шаблонов
function setXsls()
{
	$oXsls = Core_Entity::factory('Xsl');

	$oXsls
		->queryBuilder()
		->clearOrderBy()
		->orderBy('xsls.id', 'DESC');

	$aXsls = $oXsls->findAll();

	foreach ($aXsls as $oXsl)
	{
		$checked = Core_Array::getPost('xsl_' . $oXsl->id) == $oXsl->id
			? 'checked="checked"'
			: '';

		?>

		<div class="checkbox">
			<label>
				<input type="checkbox" name="xsl_<?php echo $oXsl->id?>" value="<?php echo $oXsl->id?>" <?php echo $checked?>/> <?php echo $oXsl->name?> <span class="label label-default"><?php echo $oXsl->id?></span>
			</label>
		</div>

		<?php
	}
}

// Получение групп ТДС
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);
}

// Получение групп XSL-шаблонов
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);
}

// Создание
if (Core_Array::getPost('apply'))
{
	// Массив типов параметров типовых динамических страниц
	$aLibPropertyTypes = array(
		"input" => 0,
		"checkbox" => 1,
		"xsl" => 2,
		"list" => 3,
		"sql" => 4,
		"textarea" => 5,
		"multiple" => 6,
	);

	$sLng = 'ru';

	// Результат
	$isReady = 0;

	// Выбран виджет из списка
	$iWidgetId = intval(Core_Array::getPost('lib_id'));
	if($iWidgetId)
	{
		$widgetDir = CMS_FOLDER . 'create_widget/widget_' . $iWidgetId . '/';

		// Создаем директорию для файлов
		Core_File::mkdir($widgetDir, CHMOD, TRUE);

		// Создаем директорию tmp
		$tmpDir = $widgetDir . 'tmp/';
		Core_File::mkdir($tmpDir, CHMOD, TRUE);

		$filename = 'module.php';
		$filename_xml = 'module.xml';

		$content = '<?php
/**
 * Установка виджета
 */

$tmpDir = Market_Controller::instance()->tmpDir . DIRECTORY_SEPARATOR;

$Install_Controller = Install_Controller::instance();
$Install_Controller->setTemplatePath($tmpDir);

$aReplace = array();

$sLng = "ru";
$aPossibleLanguages = array("en", "ru");
$sSitePostfix = "";

$aOptions = Market_Controller::instance()->options;
foreach ($aOptions as $optionName => $optionValue)
{
	$aReplace["%" . $optionName . "%"] = $optionValue;
}

// Массив типов параметров типовых динамических страниц
$aLibPropertyTypes = array(
	"input" => 0,
	"checkbox" => 1,
	"xsl" => 2,
	"list" => 3,
	"sql" => 4,
	"textarea" => 5,
	"multiple" => 6,
);

// Массив типовых динамических страниц
$aLibi18n = array(
	"' . $sLng . '" => array(' . "\n";

	$oLib = Core_Entity::factory('Lib')->getById($iWidgetId, FALSE);

	$content .= "		{$oLib->id} => array(" . "\n" .
	"			'name' => '" . addslashesapostrophe($oLib->name) . "'," . "\n" .
	"			'dirName' => '" . getLibDirName($oLib) ."'," . "\n" .
	"			'description' => '" . addslashesapostrophe($oLib->description) . "'," . "\n" .
	"			'code' => 'lib_" . $oLib->id . ".php'," . "\n" .
	"			'config' => 'lib_config_" . $oLib->id . ".php'," . "\n" .
	"			'params' => array(" . "\n";

	// Параметры ТДС
	$aLib_Properties = $oLib->Lib_Properties->findAll(FALSE);
	foreach ($aLib_Properties as $oLib_Property)
	{
		$content .= "				{$oLib_Property->id} => array(" . "\n" .
		"					'name' => '" . addslashesapostrophe($oLib_Property->name) . "'," . "\n" .
		"					'varible_name' => '" . addslashesapostrophe($oLib_Property->varible_name) . "'," . "\n" .
		"					'type' => '" . array_search($oLib_Property->type, $aLibPropertyTypes) . "'," . "\n" .
		"					'default_value' => '" . $oLib_Property->default_value . "'," . "\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(FALSE);
		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 .= "					)," . "\n";
		}

		$content .= "				)," . "\n";
	}

	$content .= "			)" . "\n" . "		),\n";

	Core_File::copy($oLib->getLibFilePath(), $tmpDir . 'lib_' . $oLib->id . '.php');
	Core_File::copy($oLib->getLibConfigFilePath(), $tmpDir . 'lib_config_' . $oLib->id . '.php');

	$content .= '	)
);

// Массив XSL-шаблонов
$aXsli18n = array(
	"' . $sLng . '" => 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('name' => '" . addslashesapostrophe($oXsl->name) . "', 'dirName' => '" . getXslDirName($oXsl) ."'),\n";

			if (is_file($oXsl->getXslFilePath()))
			{
				Core_File::copy($oXsl->getXslFilePath(), $tmpDir . 'xsl_' . $oXsl->id . '.xsl');
			}
			else
			{
				$aMessages[] = array('type' => 'warning', 'text' => "Предупреждение: Для XSL-шаблона '{$oXsl->name}' (id {$oXsl->id}) отсутствует .xsl-файл");
			}
		}
	}

	$content .= '	)
);

// Виджет
foreach ($aLibi18n[$sLng] as $iLibId => $aLib)
{
	$oLib = Core_Entity::factory(\'Lib\')->getByName($aLib[\'name\'], FALSE);

	if (is_null($oLib))
	{
		$aExplodeDir = explode(\'/\', $aLib[\'dirName\']);
		array_reverse($aExplodeDir);

		$iParent_Id = 0;

		foreach ($aExplodeDir as $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($aLib[\'name\']))
			->lib_dir_id($iParent_Id)
			->description(strval($aLib[\'description\']))
			->save();

		$sLibFile = $tmpDir . "tmp/" . $aLib[\'code\'];
		$sLibConfigFile = $tmpDir . "tmp/" . $aLib[\'config\'];

		if (is_file($sLibFile))
		{
			$oLib->saveLibFile($Install_Controller->loadFile($sLibFile, $aReplace));
		}

		if (is_file($sLibConfigFile))
		{
			$oLib->saveLibConfigFile($Install_Controller->loadFile($sLibConfigFile, $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($aParams[\'name\']))
					->varible_name(strval($aParams[\'varible_name\']))
					->type($aLibPropertyTypes[$aParams[\'type\']])
					->default_value(Core_Array::get($aParams, \'default_value\', \'\'))
					->sorting(strval($aParams[\'sorting\']))
					->sql_request(Core_Array::get($aParams, \'sql_request\', \'\'))
					->sql_caption_field(Core_Array::get($aParams, \'sql_caption_field\', \'\'))
					->sql_value_field(Core_Array::get($aParams, \'sql_value_field\', \'\'))
					->save();

				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($oLib_Property->id)
							->name($name)
							->value($value)
							->save();
					}
				}
			}
		}
	}
}

unset($aLibi18n[$sLng]);

//Xsls
foreach ($aXsli18n[$sLng] as $sFileName => $aXsl)
{
	$oXsl = Core_Entity::factory(\'Xsl\')->getByName($aXsl[\'name\'], FALSE);

	if (is_null($oXsl))
	{
		$aExplodeDir = explode(\'/\', $aXsl[\'dirName\']);
		array_reverse($aExplodeDir);

		$iParent_Id = 0;
		foreach ($aExplodeDir as $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($aXsl[\'name\'])
			->xsl_dir_id($iParent_Id)
			->save();

		$oXsl->saveXslFile($Install_Controller->loadFile($tmpDir . "xsl_" . $sFileName, $aReplace));
	}
}

unset($aXsli18n[$sLng]);
';

		// Создаем файл .php
		$source_file = $widgetDir . $filename;
		Core_File::write($source_file, $content);

		// Создаем файл .xml
		$source_file_xml = $widgetDir . $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;
	}
	else
	{
		$aMessages[] = array('type' => 'danger', 'text' => "Выберите виджет из списка!");
	}
}
?>

<!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.5/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]-->
</head>
<body>
<div class="container">
	<div class="page-header"  style="margin-bottom: 40px;">
		<img src="http://www.hostcms.ru/images/logo.gif" class="pull-right"/>
		<h1>Создание пакета установки виджета</h1>
	</div>

	<?php
	if (Core_Array::getPost('apply'))
	{
		if ($isReady == 1)
		{
			$aMessages[] = array('type' => 'success', 'text' => "Создано");
		}
		else
		{
			$aMessages[] = array('type' => 'danger', 'text' => "В процесе возникла ошибка!");
		}
	}

	foreach ($aMessages as $aMessage)
	{
		?><div class="alert alert-<?php echo $aMessage['type']?>" role="alert"><?php echo $aMessage['text']?></div><?php
	}
	?>

	<form name="template-create" action="create_widget.php" method="POST" enctype="multipart/form-data">
		<section  style="margin: 40px 0;">
			<p>Скрипт создаст папку create_widget в корне. В ней будут создаваться папки вида widget_XXX, где XXX — ID выбранного виджета.</p>
			<p>Папка tmp будет содержать исходный файл виджета.<br/>
			<b>ВНИМАНИЕ! Паковать в tar.gz необходимо только содержимое получившейся папки widget_XXX!</b>
			</p>
		</section>

		<section class="form-group" style="margin-bottom: 40px;">
			<h2 class="h4">Выберите виджет</h2>
			<select name="lib_id" class="form-control">
				<option value="0">...</option>
				<?php setLibs(); ?>
			</select>
		</section>
		<section class="form-group" style="margin-bottom: 40px;">
			<h2 class="h4">XSL для виджета:</h2>
			<?php setXsls();?>
		</section>

		<hr/>
		<p class="clearfix" style="margin-bottom: 100px;">
			<input type="submit" name="apply" class="btn btn-primary" value="Создать"/>
		</p>
	</form>
</div>
</body>
</html>