HEX
Server: Apache
System: Linux sg241.singhost.net 2.6.32-896.16.1.lve1.4.51.el6.x86_64 #1 SMP Wed Jan 17 13:19:23 EST 2018 x86_64
User: honghock (909)
PHP: 8.0.30
Disabled: passthru,system,shell_exec,show_source,exec,popen,proc_open
Upload Files
File: //opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/modules/tryout/classes/RvsCategoryMgr.php
<?php
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// WebSite:  http://www.rvglobalsoft.com
// Unauthorized copying is strictly forbidden and may result in severe legal action.
// Copyright (c) 2006 RV Global Soft Co.,Ltd. All rights reserved.
//
// =====YOU MUST KEEP THIS COPYRIGHTS NOTICE INTACT AND CAN NOT BE REMOVE =======
// Copyright (c) 2006 RV Global Soft Co.,Ltd. All rights reserved.
// This Agreement is a legal contract, which specifies the terms of the license
// and warranty limitation between you and RV Global Soft Co.,Ltd. and RV Site Builder.
// You should carefully read the following terms and conditions before
// installing or using this software.  Unless you have a different license
// agreement obtained from RV Global Soft Co.,Ltd., installation or use of this software
// indicates your acceptance of the license and warranty limitation terms
// contained in this Agreement. If you do not agree to the terms of this
// Agreement, promptly delete and destroy all copies of the Software.
//
// =====  Grant of License =======
// The Software may only be installed and used on a single host machine.
//
// =====  Disclaimer of Warranty =======
// THIS SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE PROVIDED "AS IS" AND
// WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR ANY OTHER
// WARRANTIES WHETHER EXPRESSED OR IMPLIED.   BECAUSE OF THE VARIOUS HARDWARE
// AND SOFTWARE ENVIRONMENTS INTO WHICH RV SITE BUILDER MAY BE USED, NO WARRANTY OF
// FITNESS FOR A PARTICULAR PURPOSE IS OFFERED.  THE USER MUST ASSUME THE
// ENTIRE RISK OF USING THIS PROGRAM.  ANY LIABILITY OF RV GLOBAL SOFT CO.,LTD. WILL BE
// LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
// IN NO CASE SHALL RV GLOBAL SOFT CO.,LTD. BE LIABLE FOR ANY INCIDENTAL, SPECIAL OR
// CONSEQUENTIAL DAMAGES OR LOSS, INCLUDING, WITHOUT LIMITATION, LOST PROFITS
// OR THE INABILITY TO USE EQUIPMENT OR ACCESS DATA, WHETHER SUCH DAMAGES ARE
// BASED UPON A BREACH OF EXPRESS OR IMPLIED WARRANTIES, BREACH OF CONTRACT,
// NEGLIGENCE, STRICT TORT, OR ANY OTHER LEGAL THEORY. THIS IS TRUE EVEN IF
// RV GLOBAL SOFT CO.,LTD. IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL
// RV GLOBAL SOFT CO.,LTD.'S LIABILITY EXCEED THE AMOUNT OF THE LICENSE FEE ACTUALLY PAID
// BY LICENSEE TO RV GLOBAL SOFT CO.,LTD.
// +---------------------------------------------------------------------------+
// $Id: RvsCategoryMgr.php,v 1.41 2006/03/30 10:29:02 thiraphat Exp $
// +---------------------------------------------------------------------------+

/**
 * RvsCategoryMgr.php use both
 * 1. tryout website page template category
 * 2. rvsitebulder STEP 2 category
 *
 * @package sitebuilder
 * @author  Apiruk <apiruk@rvglobalsoft.com>
 * @version $Revision: 1.41 $
 * @since   PHP 4.1
 */

class RvsCategoryMgr extends SGL_Manager
{
	var $oTemplateList;
	var $oMain;
	function RvsCategoryMgr()
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		parent::SGL_Manager();

		$this->module       = 'sitebuilder';
		$this->pageTitle    = 'STEP1';
		$this->masterTemplate = 'rvs_sitebuilder.html';
		$this->template     = 'RvsCategory.html';//'Category.html';
		// call tryout mode
		if ($this->conf['localConfig']['moduleName'] == 'tryout') {
			$this->template     = 'Category.html';
			define('CPMODE','tryout');
			if (defined('RVS_USER_NAME') === false) {
				define('RVS_USER_NAME', null);
			}
			if (defined('RVS_IS_ADMIN') === false) {
				define('RVS_IS_ADMIN', null);
			}
			if (defined('RVS_IS_RESELLER') === false) {
				define('RVS_IS_RESELLER', null);
			}
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/DbWrapper.php');
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/TemplateDao.php');
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/TemplateImportDao.php');
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/CategoryDao.php');
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/UsrDao.php');
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/ColorDao.php');
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/ProjectDao.php');
			require_once( SGL_MOD_DIR . '/../lib/RVSGL/SitebuilderDao/TryoutDao.php');
			require_once SGL_MOD_DIR.'/../lib/RVSGL/DaoFactory.php';
			//RvsLibs
			$coreLibs =  SGL_MOD_DIR.'/../lib/RVSGL/rvsLibs';
			$aRequiredFiles = array(
			$coreLibs . '/AjaxProvider.php',
			$coreLibs . '/Archive.php',
			$coreLibs . '/Component.php',
			$coreLibs . '/Config.php',
			$coreLibs . '/DB.php',
			$coreLibs . '/File.php',
			$coreLibs . '/Image.php',
			$coreLibs . '/License.php',
			$coreLibs . '/Project.php',
			$coreLibs . '/Publish.php',
			$coreLibs . '/Registry.php',
			$coreLibs . '/String.php',
			$coreLibs . '/System.php',
			$coreLibs . '/Template.php',
			$coreLibs . '/Url.php',
			$coreLibs . '/User.php',
			$coreLibs . '/Util.php',
			);
			foreach ($aRequiredFiles as $file) {
				require_once $file;
			}
		 /// include cphandle
			$pathCpHandle = dirname(__FILE__). '/CpHandle.php';
			if (is_file($pathCpHandle) && class_exists('CpHandle') === false) {
				require_once($pathCpHandle);
			}
			require_once(RvsLibs_File::buildPath(array(SGL_MOD_DIR, 'tryout', 'classes', 'TemplateList.php')));
		} else {
			require_once(RvsLibs_File::buildPath(array(SGL_MOD_DIR, 'sitebuilder', 'classes', 'TemplateList.php')));
		}
		$this->oTemplateList = new TemplateList();
		$this->_aActionsMapping =  array(
	        'list'		=>    array('list'),
	        'add'		=>    array('add'),
	        'edit'		=>    array('edit'),
		);
	}

	function validate($req, &$input)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$this->validated    = true;
		$input->error       = array();
		$input->step = '1';
		$input->mode = 'Template';
		$input->pageTitle   = RvsLibs_String::translate($this->pageTitle);
		$input->pathwayName = RvsLibs_String::translate('Step1 Description');
		$input->moduleName = ($req->get('moduleName'))? $req->get('moduleName') : '';
		$input->masterTemplate = $this->masterTemplate;
		$input->template    = $this->template;
		$input->action      = ($req->get('action')) ? $req->get('action') : 'list';
		$input->project_id = SGL_Session::get('rvs_project_id');

		$input->deletemplateUrl = SGL_Output::makeUrl('deleteTemplate', 'editdeletetemplate', 'sitebuilder');

		$input->tryoutMode = false;
		//start tryout website page template category
		if ($input->moduleName == 'tryout') {
			$oSitebuilder = new TryoutDao();
			$input->webThemeUrl = $aInput['rvs_url_www'];
			$input->masterTemplate = 'tryoutMaster.html';
			$aSitebuilderConfig = $oSitebuilder->getSitebuilderConfig();
			$dbh = $oSitebuilder->rvsConnectDb();
			$aSitebuilderConfig['tryoutlogin'] = $this->conf['tryoutlogin'];
			$this->oTemplateList->registRvsConf($aSitebuilderConfig, $dbh);
			$aInput = $this->getFileSystemPath();
			$path = SGL_Config::get('path.webRoot') . '/tryout/tryout_config.ini.php';
			$aSetting = parse_ini_file($path);
			if (!defined('SGL_BASE_URL')) {
				define('SGL_BASE_URL', $aInput['rvs_url_www']);
			}
			if (!defined('WEB_THEME_URL')) {
				define('WEB_THEME_URL', $aInput['rvs_url_www']);
			}
			if (!defined('SGL_WEB_ROOT')) {
			define('SGL_WEB_ROOT', $aSetting['program_path'] . '/www');
			}
			if (!defined('SGL_PATH')) {
				define('SGL_PATH', $aSetting['program_path']);
			}
			if (!defined('RVS_OWNER_USER_NAME')) {
				define('RVS_OWNER_USER_NAME', $aSetting['owner']);
			}
			define('INDEX_PHPSU', $this->conf['site']['frontScriptName']);
			define('PUBLIC_IMG_URL', $aInput['rvs_url_www'] . '/themes/default/sitebuilder/images');
			define('PUBLIC_IMG_V5_URL', $aInput['rvs_url_www'] . '/themes/default/sitebuilder/images5');

			$oCategoryDao = CategoryDao::singleton($autoload = false);
			$oCategoryDao->registRvsConf($aSitebuilderConfig, $dbh);
			$oTemplateDao = TemplateDao::singleton($autoload = false);
			$oTemplateDao->registRvsConf($aSitebuilderConfig, $dbh);
			$oTemplateImportDao = TemplateImportDao::singleton($autoload = false);
			$oTemplateImportDao->registRvsConf($aSitebuilderConfig, $dbh);
			$oUsrDao = UsrDao::singleton($autoload = false);
			$oUsrDao->registRvsConf($aSitebuilderConfig, $dbh);
			//ProjectDao
			$oProjectDao = ProjectDao::singleton($autoload = false);
			$oProjectDao->registRvsConf($aSitebuilderConfig, $dbh);
			//ColorDao
            $oColorDao = ColorDao::singleton($autoload = false);
            $oColorDao->registRvsConf($aSitebuilderConfig, $dbh);
			// Initialise Db DataObject
			$oSitebuilder->rvsInitialiseDbDataObject();
			$rvsUrl = (isset($aInput['rvs_url_www'])) ? $aInput['rvs_url_www'] : '';
			$input->rvs_url_css = (isset($aInput['url_php_suexec'])) ? $aInput['url_php_suexec'] : $rvsUrl;
			$input->pagerUrl = $aInput['pagerUrl'];
// 			$input->noLink = '1';
			$input->tryoutMode = true;
			//end  validate tryout


			$fileAutoConf = SGL_VAR_DIR . '/listcomponentmemberpage.ini.php';
			if (is_file($fileAutoConf) == true) {
				$aAutoConf = RvsLibs_Config::parse_ini_file($fileAutoConf, true);
			}
			//is member by page
			$isMemberPage = (isset($aAutoConf['isMember_Tryout']))
			                 ? $aAutoConf['isMember_Tryout'] : '0';
			//is member redirect to memberpage
			if ($isMemberPage == '1') {
				if (!SGL_Session::getUid()) {
					$aUrl = array(
	                    'managerName' => 'memberpage',
	                    'moduleName'  => 'default',
	                    'page'     => 'Tryout',
					);
					SGL_HTTP::redirect($aUrl);
				}

			}
		} else {
			//ถ้า ใน pager  use httpMethod = 'GET' จะต้อง  detech phpsu :: ถ้า httpMethod  = 'POST' ไม่ต้อง detech phpsu ก็ได้
			$referPhpsuexec = (INDEX_PHPSU == "index.php?" ) ? "/&" : "/?";
			$input->pagerUrl = RvsLibs_File::buildPath(array(SGL_BASE_URL, INDEX_PHPSU, 'sitebuilder', 'rvscategory', $referPhpsuexec));
			// $this->oMain->validateProjectId($input->project_id);
			$validateProject = RvsLibs_Project::validateProjectId($input->project_id);
			if (SGL::isError($validateProject) === true) {
				SGL::raiseMsg($validateProject->getMessage());
				SGL_Error::pop();
				if ((isset($input->isTest) && $input->isTest === false) || (isset($input->isTest) === false)) {
				    SGL_HTTP::redirect(array('managerName' => 'sitebuilder'));
				}
			}
		}

		$input->template_type_id = $req->get('templatestyle') ? $req->get('templatestyle') : 0;
		$categoryId = $req->get('select_category_id');

		SGL::logMessage('cmd ==req== select_category_id:' . $categoryId, PEAR_LOG_DEBUG);
		//exit;
		$input->import_template_style = $req->get('import_template_style');
		$input->tryoutWebsite = ($req->get('moduleName') == 'rvuser') ? true : false;

		$input->classFocusImport = ($req->get('import_template_style')) ? 'class=curr' : '';
		$input->classFocusDiy = ($req->get('select_category_id') && $req->get('select_category_id') == 'DiyPicture') ? 'class=curr' : '';

		$input->picture_style = $req->get('picture_style') ? $req->get('picture_style') : 0;
		$input->color_id = $req->get('color_id');
		$input->getNumPage = $req->get('getNumPage') ? $req->get('getNumPage') : 12;

		$input->rvs_url_www = WEB_THEME_URL;
		$input->rvs_usr_id  = RvsLibs_User::getUserId();
		$input->rvs_owner_usr_id = RvsLibs_User::getOwnerId();

		//get reference template data
		$input->aRefTemplateData = RvsLibs_Template::getTemplatesData($input->project_id, true, false);
		$aCateId = (isset($input->aRefTemplateData->products_id)) ? explode('-', $input->aRefTemplateData->products_id) : 0;
		$input->ref_category_id = (isset($aCateId[0])) ? $aCateId[0] : 0;
		$input->ref_navigator_id = isset($input->aRefTemplateData->navigator_id) ? $input->aRefTemplateData->navigator_id : '';
		$input->ref_template_item_id = isset($input->aRefTemplateData->template_item_id) ? $input->aRefTemplateData->template_item_id : '';

		$input->select_category_id = (isset($categoryId) && $categoryId != '') ? $categoryId : $input->ref_category_id;
		$input->select_category_id = $input->select_category_id != '' ? $input->select_category_id : '0';

		SGL::logMessage('cmd:1.1 $categoryId:' . $categoryId, PEAR_LOG_DEBUG);
		SGL::logMessage('cmd:1.2 $input->ref_category_id:' . $input->ref_category_id, PEAR_LOG_DEBUG);
		SGL::logMessage('cmd:1.3 select_category_id:' . $input->select_category_id, PEAR_LOG_DEBUG);

		$input->managerName = $req->get('managerName');
		$input->productIdSearch = $req->get('productIdSearch');

		/*Get on-demand Configuration*/
		//start in not tryout website page template category
		$input->ondemand_template = 0;
		if ($input->moduleName != 'tryout') {

			$input->ondemand_template = RvsLibs_Config::getOnDemandTemplate();
			$getOnDemandTemplateUrl = RvsLibs_Config::getOnDemandTemplateUrl();
			$input->url_preview = $getOnDemandTemplateUrl . '/template-preview.php';
			$input->ondemand_url = $getOnDemandTemplateUrl;

			if ($input->ondemand_template && $getOnDemandTemplateUrl) {
				$input->url_download_template = $getOnDemandTemplateUrl;

				$input->nextredirect = ($req->get('nextredirect')) ? $req->get('nextredirect') : 'rvscategory';
				$input->noredirect = ($req->get('noredirect')) ? $req->get('noredirect') : '0';

				$input->ondemand_template = 1;
			} else {
				$input->ondemand_template = 0;
			}
        }

		//create auto preview ใช้อยู่
		//SGL_Session::set('select_category_id',$input->select_category_id);

		//is blog return boolean(true) :: is not blog return String('')
		$blog = SGL_Session::get('rvs_blog');

		/*
		 * function create blog
		 * check step 2 select data
		 */
		if ($categoryId == '') {
			$input->select_category_id = $blog &&  $input->select_category_id == '0'
				? "21"
				: $input->select_category_id;
			$blogCategory = ($input->select_category_id != '0')
				? $input->select_category_id
				: '';
			$input->category_id = $blogCategory;
			SGL::logMessage('cmd 00000:' . $blogCategory, PEAR_LOG_DEBUG);
		} elseif ($categoryId == '0') {
			$input->category_id = '';
			SGL::logMessage('cmd 11111', PEAR_LOG_DEBUG);
		} else {
			$input->category_id = $categoryId;
			SGL::logMessage('cmd 222222', PEAR_LOG_DEBUG);
		}

		// validate enable icon user import template
		if ($input->moduleName != 'tryout'
		    && RvsLibs_License::isLicensePro()
		    && RvsLibs_Config::getOwnerConf('AllowUserImportTemplate')) {
			$input->allowImportTemplate = true;
		}
		// case tryout errer
		if ($input->moduleName != 'tryout') {
			$input->allowDIYTemplate = (RvsLibs_Config::getOwnerConf('AllowDIYTemplate') && RvsLibs_License::isLicensePro()) ? true : false;
		}
		//but set tryoutMode = 1 in tryoutlogin only
		//TODO: submitUserImport noLink downloadTemplate reupload ตรวจดูอีกทีว่าใช้รึป่าว
// 		$input->submitUserImport = false;
// 		if ( $req->get('submitUserImport') ) {
			$input->mode = 'Export Template';
// 			$input->submitUserImport = true;
// 			$input->downloadTemplate = '1';
// 			$input->noLink = '1';
			$input->refer_phpsuexec = (INDEX_PHPSU == "index.php?") ? "&" : "?";
			$input->current_template_id = $req->get('current_template_id');
			$input->current_template_item_id = $req->get('current_template_item_id');
// 			$input->reupload = $req->get('reupload');
// 		}
		$command = "\$this->_validate_" . $input->action . "(\$req, \$input, \$aErrors);";
		eval("$command");

		/**
		 * Below validations apply to all actions
		 */
		/**
		 * Set error messages if error found
		 */
		if (isset($aErrors) && count($aErrors)) {
			//To Translate raiseMsg Ex. RvsLibs_String::translate(SGL::raiseMsg('Message'));
			SGL::raiseMsg('Please fill in all the indicated fields and try again.',true);
			$input->error = $aErrors;
			$input->template = 'Category.html';
			$this->validated = false;
		}
	}

	function display(&$output)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		if ($output->moduleName != 'tryout') {
		    $output->addJavascriptFile('js/PreLoadImage.js');
		    $output->addJavascriptFile('js/rvsitebuilder/download_template.js');
		    $output->addJavascriptFile('js/rvsitebuilder/directadmin/uploadfile.js');
		    $output->addJavascriptFile('js/rvsitebuilder/RvsCategory.js');
		    $output->addJavascriptFile('js/rvsitebuilder/DiyResponsive.js');

		    //ProductIdOfTemplate
		    $output->addJavascriptFile(RvsLibs_Project::getJsCssPathV5('js/rvsitebuilder/ProductIdOfTemplate.js'));
		    $output->addJavascriptFile(RvsLibs_Project::getJsCssPathV5('js/rvsitebuilder/KeyWordOfTemplate.js'));
		    $output->addJavascriptFile('js/jquery-ui/external/pagination/jquery.pagination.js');
		    // ===  start tag suggestion
		    $output->addJavascriptFile('js/jquery-ui/external/tagsearch/jquery.jsonSuggest-2.js');

		    // ===  end tag suggestion
		    if(RvsLibs_License::isLicensePro() === true ) {
				$output->addJavascriptFile(RvsLibs_Project::getJsCssPathV5('js/rvsitebuilder/allTemplate.js'));
		    } else {
		    	$output->addJavascriptFile(RvsLibs_Project::getJsCssPathV5('js/rvsitebuilder/allTemplateLite.js'));
		    }
			$output->addJavascriptFile(RvsLibs_Project::getJsCssPathV5('js/rvsitebuilder/catedata.js'));
			$output->addJavascriptFile(RvsLibs_Project::getJsCssPathV5('js/rvsitebuilder/aColorDB.js'));

			$output->addJavascriptFile('js/rvsitebuilder/preViewNavigator.css.js');
		    $output->addJavascriptFile('js/rvsitebuilder/commonTemplate.js');
            $output->addCssFile(RvsLibs_Project::getJsCssPathV5('themes/default/sitebuilder/css/pagination.css', 'css'));
            $output->addCssFile('themes/default/sitebuilder/css/jquery-ui-1.8.9.custom.css');

		    $imagepreload = array(
		    PUBLIC_IMG_URL . '/btnOk02.gif',
		    // new 5/6/09
		    PUBLIC_IMG_URL . '/sprite_button.gif',
		    PUBLIC_IMG_URL . '/sprite_icon.gif',
		    PUBLIC_IMG_V5_URL . '/spnavigator.gif',
            PUBLIC_IMG_V5_URL . '/spicon.png',
		    );
		    $image = join("','" , $imagepreload);
		    $output->addOnLoadEvent("PreLoadImage(['" . $image . "'])");
		    $output->ignoreXmlDeclare = true;
		    //case no tryout
		    if ($output->moduleName != 'tryout') {
		        $output->addjQueryEvent('click','.jq_DownloadTemStep2','
                       jQuery.sitebuilder.downloadTemplate.OpenFrm(jQuery(this));
                        ');
		    }
		}

		$output->addjQueryEvent('click','.previews','jQuery.sitebuilder.RvsCategory.openPreview(jQuery(this)) ');
		$output->addjQueryEvent('load','#keepData',' ');
		$output->addjQueryEvent('click','#btnGotoStep1','
		    window.location=pagerUrl + "template_item_id=" + jQuery("#currentTemId").val() + "&action=add&gotostep=1";
		');
		$output->addjQueryEvent('click','#btnGotoStep2','
			window.location=pagerUrl + "template_item_id=" + jQuery("#currentTemId").val() + "&action=add&gotostep=2";
		');

		//$output->addjQueryEvent('click','#uploadTemplate','jQuery("#uploadFormx").rvsDialog("open");');
		$output->addjQueryEvent('click','#btnBack','
			jQuery("#newDataCategory").show();
			jQuery.sitebuilder.RvsCategory.viewCategory();');

		$output->addjQueryEvent('ready','document','
		 	jQuery("input#suggestBox").jsonSuggest({data: aKeyWordOfTemplate, minCharacters: 2
		 		,onSelect:jQuery.sitebuilder.RvsCategory.addInnerBySearch
		 		,onResultEmpty:jQuery.sitebuilder.RvsCategory.addBySearchID
		 		,objDivShowDesc:"idDivShowExample"
	     	});
			jQuery.sitebuilder.RvsCategory.buildSearchAction();
			jQuery.sitebuilder.RvsCategory.viewCategory();
			jQuery.sitebuilder.RvsCategory.fixSelectedDiy("' . $output->cateIdCurrent . '");
			jQuery.sitebuilder.RvsCategory.currentCategory("' . $output->select_category_id . '");
		');
		$output->addjQueryEvent('click','.listCategory','jQuery.sitebuilder.RvsCategory.selectCategory(jQuery(this));');
		$output->addjQueryEvent('change','#listCategory','jQuery.sitebuilder.RvsCategory.selectCategory(jQuery(this));'); //for isV5
		$output->addjQueryEvent('change','#templateTypeStyle','jQuery.sitebuilder.RvsCategory.selectTemplateStyle(jQuery(this));');
		$output->addjQueryEvent('click','#updateFilecate','jQuery.sitebuilder.RvsCategory.updateFilecate(jQuery(this));');
		//TODO v 5.99 uikit import only
		//if (isset($output->currentIsResponsive) && $output->currentIsResponsive == true) {
			$oCp = CpHandle::factory();
			if ($oCp->isDirectAdmin()) {
				$output->addjQueryEvent('click','.ui-dialog-titlebar-close','removeOverLay();');
				$output->addjQueryEvent('click','#uploadTemplate','
						jQuery("#dialogUploadTemplate").find(".msgblock-info").show();
						jQuery("#dialogUploadTemplate").find(".msgblock-error").hide();
						jQuery("#dialogUploadTemplate").find(".fuploadTempt").hide();
						jQuery("#fileUploadTemplate").val("");
						jQuery("#uploadFormx").rvsDialog("open");
						removeOverLay();
						startOverLay();
						jQuery("#uploadFormx").prev().find("span.ui-icon-closethick").click(function(){
							removeOverLay();
                        });
						');
				$output->addjQueryEvent ( 'change', '#file1', 'jQuery.sitebuilder.uploadtemplateDA.doUploadTemplate("#frmUploadTemplateDa","submitUploadGoToStep3");');
			} else {
				$output->addjQueryEvent ( 'click', '#uploadTemplate', '
						jQuery("#dialogUploadTemplate").find(".msgblock-info").show();
						jQuery("#dialogUploadTemplate").find(".msgblock-error").hide();
						jQuery("#dialogUploadTemplate").find(".fuploadTempt").hide();
						jQuery("#fileUploadTemplate").val("");jQuery("#dialogUploadTemplate").rvsDialog("open");

						' );
				$output->addjQueryEvent ( 'change', '#fileUploadTemplate', 'jQuery.sitebuilder.RvsCategory.uploadTemplate();' );
			}
		//} else {
		//	$output->addjQueryEvent('click','#uploadTemplate','jQuery("#confire_change_template").rvsDialog("open");');
		//}

	}

	/**
	 * register template missing folder for Import Template and DIY Template Only not Distribuild Template
	 *
	 * @return multitype:
	 */
	function _getTemplateMissing($userId, $ownerId)
	{
		$cache = &RvsLibs_File::rvsCache();
		if ($serialized = $cache->get('getTemplateMissing', 'cachedata')) {
			$aTemplateFolder = unserialize($serialized);
			SGL::logMessage('=============== optimize getTemplateMissing from cache', PEAR_LOG_DEBUG);
		} else {
            $aTemplate = DaoFactory::Template()->findImportTemplateByUsrIdAndOwnerId($userId, $ownerId);
            //print_r($aTemplate);
			$aTemplateFolder = array();
			$pathImportTemplate = RvsLibs_File::buildPath(array(USER_HOME_USERDATA_PATH, 'upload', 'template'));
			$pathOwnerImportTemplate = RvsLibs_File::buildPath(array(OWNER_HOME_USERDATA_PATH, 'upload', 'template'));
			foreach ($aTemplate as $k => $v){
				$pathImportTemplateItem = RvsLibs_File::buildPath(array($pathImportTemplate, $v->template_item_folder));
				$pathOwnerImportTemplateItem =  RvsLibs_File::buildPath(array($pathOwnerImportTemplate, $v->template_item_folder));
				$templateDistribuild = RvsLibs_File::buildPath(array(TEMPLATE_PATH, $v->template_item_folder));
				if (is_dir($pathImportTemplateItem) === false
					&& is_dir($pathOwnerImportTemplateItem) === false
					&& is_dir($templateDistribuild) === false){
					$aTemplateFolder[$v->template_id] = $v->template_item_folder;
				}
 			}
			$serialized = serialize($aTemplateFolder);
			$cache->save($serialized, 'getTemplateMissing', 'cachedata');
			SGL::logMessage('=============== optimize getTemplateMissing from file', PEAR_LOG_DEBUG);
		}
		return $aTemplateFolder;
	}

	function getTemplateItemPath($projectId)
	{
		$aTemplateData = RvsLibs_Template::getTemplatesData($projectId, true, false);
		if (isset($aTemplateData->templatePath)) {
			return $aTemplateData->templatePath . '/' . $aTemplateData->template_item_folder;
		} else {
			return '';
		}
	}

	function _validate_list(&$req, &$input, &$aErrors)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		// Show Template
		if ($input->moduleName == 'tryout') {
			$input->aShowData = $this->oTemplateList->_generateCodeHTMLCategory($input);
			$input->totalTemplate = count($input->aAllTemplate);
			$input->aTemplateMissing =  SGL_AjaxProvider::jsonEncode(array());
		} else {
			$TemplateMissing = $this->_getTemplateMissing($input->rvs_usr_id, $input->rvs_owner_usr_id);
			$input->aTemplateMissing =  SGL_AjaxProvider::jsonEncode($TemplateMissing);
		}

		//Get total Diy & Import
		$aImportTemplate = DaoFactory::Template()->findImportTemplateByUsrIdAndOwnerId($input->rvs_usr_id, $input->rvs_owner_usr_id);
		$aImport = DaoFactory::Template()->findTemplateItemDataByGroupTemplateItemIdAndTemplateIdImport(23, $input->rvs_usr_id, $input->rvs_owner_usr_id,'getAssoc');

		// Show Current Template or Category Image
		$categoryData = $this->oTemplateList->_getCurrentTemplate($input);
		$templateFolderPath = (isset($categoryData['template_item_folder']))
		                      ? $categoryData['template_path'] . '/' . $categoryData['template_item_folder']
		                      : self::getTemplateItemPath($input->project_id);

		$input->currentIsResponsive = (RvsLibs_Template::isResponsiveTemplate($templateFolderPath)) ? true : false;
		$input->currentIsUikit = (RvsLibs_Template::isUikitTemplate($templateFolderPath)) ? true : false;
		$input->currentIsNormal = ($input->currentIsResponsive == false && $input->currentIsUikit == false) ? true : false;

		SGL::logMessage(' currentIsResponsive: ' . $input->currentIsResponsive);
		SGL::logMessage(' currentIsUikit: ' . $input->currentIsUikit);
		SGL::logMessage(' currentIsNormal: ' . $input->currentIsNormal);

		$input->templateIsEmpty = ($templateFolderPath == "") ? true : false;

		$categoryData = (isset($categoryData) && $categoryData) ? $categoryData : false;
		$input->categoryData = SGL_AjaxProvider::jsonEncode($categoryData);

		$aCateId = !empty($categoryData['products_id']) ? explode('-', $categoryData['products_id']) : '0';
		$cateIdCurrent = !empty($aCateId[0]) ? $aCateId[0] : '0';
		$cateIdCurrent = !empty($input->category_id) ? $input->category_id : $cateIdCurrent;
		//กรณีที่ current เป็น DIY $input->category_id = 23 แต่ picture_name = DiyPicture
		$input->cateIdCurrent = (isset($categoryData['picture_name']) && $categoryData['picture_name'] == 'DiyPicture')
									? 'DiyPicture'
									: $cateIdCurrent;
		$input->countImportTemplate = count($aImport);
		$input->countDiyTemplate = count($aImportTemplate) - count($aImport);

		$input->currentCategoryName = (isset($categoryData['category_name'])) ? RvsLibs_String::translate($categoryData['category_name']) : "";
		$input->currentOption = self::getCategoryOption($input->cateIdCurrent);

		///Start Get TemplateType AND ListCategory
		$aTemplateType = $this->oTemplateList->getListTemplateType();

		$input->aTemplateTypeStyle = $aTemplateType;
		///ค้นหา Index DIY Template สำหรับลบข้อมูล DIY Template เพื่อไม่ให้แสดงที่ Template Style :: May
		$key = array_search("DIY Template",$aTemplateType);

		//$aTemplateType = $this->oTemplateList->unSetDownloadTemplate($aTemplateType, $input->submitUserImport);
		$aTemplateType[0] = 'All Style' ;
		$aTemplateType = $this->oTemplateList->getTranslation($aTemplateType);
		ksort($aTemplateType);

		$input->aTemplateType = $this->setFocus($aTemplateType, $input->template_type_id);
		//หลังจากทำ SetFocus ลบ DIY Template เพื่อไม่ให้แสดงที่ Template Style :: May
		if (isset($input->aTemplateType[$key])) {
			unset($input->aTemplateType[$key]);
		}
		$aCustomCategory = array();
		$aCategory = $this->oTemplateList->getCategoryList();
		unset($aCategory['23']);
		//case tryout

		//custom category
		if (isset($input->moduleName) === false ||  $input->moduleName != 'tryout') {
			$aCustomCategory = RvsLibs_Template::getCustomCategoryList();
			$this->changCategoryById();
		}
		$aCategory[0] = 'All Categories';

		//ksort($aCategory);
		//ksort($aCustomCategory);
		$aCategory = RvsLibs_Project::unsetCategory($aCategory);
		if (SGL_Output::isV6Session() == false) {
			//show custom category in v5 only
			$aCategory = RvsLibs_Project::arrayMerge($aCategory, $aCustomCategory);
		}
		$aCategory = $this->oTemplateList->getTranslation($aCategory);

		//sort array valule all lang
		$aListCategory = array();
		$aListCategory = $aCategory;
		unset($aListCategory[0]);
		asort($aListCategory); //

		//first begin [0] = All Categories
		$aAll = array();
		$aAll[0] = $aCategory[0];
		foreach ($aListCategory as $cateId => $cateName) {
			$aAll[$cateId] = $cateName;
		}
		$input->aListCategory = $aAll;

		$input->aCategory = $this->setFocus($aCategory, $input->select_category_id);
		$input->selectCategoryName = isset($aCategory[$input->select_category_id]) ? $aCategory[$input->select_category_id] : '' ;

		$input->selectCategoryId = $input->select_category_id;
		// $input->isAllCategory = ($input->select_category_id == 0 ) ? true : false;
		//เหตุที่เช็ค count(select_category_id) เท่ากับ 0 เพราะว่าถ้าคลิก allcategory จะมีค่าเป็น 0 จะได้template ทั้งหมด
		$input->isAllCategory = (count($aCategory) == 0 ) ? true : false;
		///End Get TemplateType AND ListCategory

		//search template(import, DIY, custom category)
		if ($input->moduleName != 'tryout') {
			$aImportTemplate = DaoFactory::Template()->findImportTemplateByUsrIdAndOwnerId($input->rvs_usr_id, $input->rvs_owner_usr_id);
			$aImport = DaoFactory::Template()->findTemplateItemDataByGroupTemplateItemIdAndTemplateIdImport(23, $input->rvs_usr_id, $input->rvs_owner_usr_id,'getAssoc');
			$countImportTemplate = count($aImport);
			$countDiyTemplate = count($aImportTemplate) - count($aImport);

			$aImportTemplate = $this->oTemplateList->newSetTemplateOutput($aImportTemplate, null, null);
			$input->searchImportTemplateId = '';
			if (isset($aImportTemplate[0]) && count($aImportTemplate[0]) > 0) {
				$input->searchImportTemplateId = SGL_AjaxProvider::jsonEncode($aImportTemplate[0]);
			}

			/*
			/// BEGIN: Analytics Total Diy,Total Import / Users ::Apiruk
			try {
				if (RvsLibs_String::isPHP53() == true) {
					$mainIp = Sitebuilder::getMainIP();
					$oRVGATracking = RvsLibs_RVGATracking::singleton();

					//get google config
					$aGoogleConf = RvsLibs_Config::getGoogleAnalyticsConfig();
					$totalDiyConf = (isset($aGoogleConf['TotalTemplate']['TotalDiyTemplate'])) ? $aGoogleConf['TotalTemplate']['TotalDiyTemplate'] : 0;
					$totalImportConf = (isset($aGoogleConf['TotalTemplate']['TotalImportTemplate'])) ? $aGoogleConf['TotalTemplate']['TotalImportTemplate'] : 0;

					//current - config
					$totalDiy = $countDiyTemplate - $totalDiyConf;
					$totalImport = $countImportTemplate - $totalImportConf;

					SGL::logMessage('google : diy = ' . $countDiyTemplate . ' - ' . $totalDiyConf, PEAR_LOG_DEBUG);
					SGL::logMessage('google : import = ' . $countImportTemplate . ' - ' . $totalImportConf, PEAR_LOG_DEBUG);
					SGL::logMessage('google :total diy = ' . $totalDiy, PEAR_LOG_DEBUG);
					SGL::logMessage('google :total import = ' . $totalImport, PEAR_LOG_DEBUG);

					//update google config
					$aGoogleConf['TotalTemplate']['TotalDiyTemplate'] = $countDiyTemplate;
					$aGoogleConf['TotalTemplate']['TotalImportTemplate'] = $countImportTemplate;
					RvsLibs_Config::setGoogleAnalyticsConfig($aGoogleConf);

					if ($totalDiy != 0) {
						$oRVGATracking->setEvent('RVSiteBuilder/TotalDiyTemplate',$mainIp, RVS_USER_NAME . '_' . $input->project_id, $totalDiy);
					}


					if ($totalImport != 0) {
						$oRVGATracking->setEvent('RVSiteBuilder/TotalImportTemplate', $mainIp, RVS_USER_NAME . '_' . $input->project_id, $totalImport);
					}

					$oRVGATracking->sendAllEvent();
				}
			} catch (Exception $e) {}
			/// END: Analytics Total Diy,Total Import / Users ::Apiruk

			 */
		}
	}

	/**
	 * for step1 v5
	 * @param string $cateIdCurrent
	 */
	static function getCategoryOption($cateIdCurrent = '')
	{
		$currentOption = '';
		if ($cateIdCurrent == '23') {
			$currentOption = '
								  <option value="DiyPicture">' . RvsLibs_String::translate('Diy Template') . '</option>
						          <option value="23" selected="selected">' . RvsLibs_String::translate('Import Template') . '</option>
			';
		} elseif ($cateIdCurrent == 'DiyPicture') {
			$currentOption = '
								  <option value="DiyPicture" selected="selected">' . RvsLibs_String::translate('Diy Template') . '</option>
						          <option value="23">' . RvsLibs_String::translate('Import Template') . '</option>
			';
		} else {
			$currentOption = '
								<option value="DiyPicture">' . RvsLibs_String::translate('Diy Template') . '</option>
			 					<option value="23">' . RvsLibs_String::translate('Import Template') . '</option>
			';
		}
		return (SGL_Output::isV6Session() == false) ? $currentOption : '';
	}

	/**
	 * update template impot business to category
	 * chang category_id = 17  to category_id = 23
	 */
	function changCategoryById()
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$resCategory = DaoFactory::TemplateImport()->findTemplateImportAllCategoryId('getassoc');
		foreach ($resCategory as $kTemplateId => $vCategoryId) {
			$res = DaoFactory::TemplateImport()->fileTemplateCategoriesXref($kTemplateId=null, '23', 'getrow');
			if (count($res) > 0 ) continue;
			DaoFactory::TemplateImport()->updaterTemplateCategoriesXref($kTemplateId, $vCategoryId, '23');
		}
	}

	/*
	 unittest add step1**
	 case -$get- template_item_id,template_current move to validate
	 input move to validate
	 _validate_add_edit (&$aErrors, $input->project_id, $input->template_item_id)
	 */
	function _validate_add_edit($req, &$input, &$aErrors)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		//Start define variable
		$input->template_item_id = $req->get('template_item_id');
		if (empty($input->template_item_id)) {
			SGL::logMessage('req not found: template_item_id' . $input->template_item_id, PEAR_LOG_ERR);
		}
		$input->gotostep = $req->get('gotostep');

		//End define variable
		$aProjectInfoData = DaoFactory::Project()->findProjectInfoDataByProjectId($input->project_id, 'getall');
		if (!$req->get('template_current')) {
			$aProjectInfoData = DaoFactory::Project()->findProjectInfoDataByProjectId($input->project_id, 'getall');
			$res = $this->getTemplateItemNavigatorData($input->template_item_id);
			$navigatorNameId = (isset($res->navigator_name_id))
			                     ? $res->navigator_name_id
			                                          : '3';
			$input->navigator_name_id = (isset($aProjectInfoData[0]->navigator_name_id))
			                             ? $aProjectInfoData[0]->navigator_name_id
			                             : $navigatorNameId;
		}
		//case input --->$this->oTemplateList->_getCategoryIdNavigatorId($input->project_id, $input->template_item_id);
		$aTemplateData = $this->oTemplateList->_getCategoryIdNavigatorId($input);
		$input->category_id = $aTemplateData->rvs_category_id;
		SGL::logMessage('cmd ref category_id:' . $input->category_id, PEAR_LOG_DEBUG);
		$input->navigator_id = $aTemplateData->navigator_id;

		$input->aProjectInfoData  = RvsLibs_Project::getProjectInfoData($input->project_id);
		$input->project_info_id = $input->aProjectInfoData[0]->project_info_id;
		$input->check_step = $input->aProjectInfoData[0]->check_step;
	}

	function _validate_add($req, &$input, &$aErrors)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$this->_validate_add_edit($req, $input, $aErrors);
	}

	function _validate_edit($req, &$input, &$aErrors)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$this->_validate_add_edit($req, $input, $aErrors);
	}

	/**
	 * for Test change banner to add new page
	 * make file RVS_USER_HOME .'/.rvsitebuilder/deletepage.txt
	 *
	 * @param unknown $templateres
	 * @param array $aPageStructure
	 * @param string $checkIsUikit
	 * @param unknown $projectId
	 * @param unknown $usrId
	 */
	function skipDeletePageAll($templateres, $projectId, $usrId, $aPageStructure = array(), $checkIsUikit = false)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$path = RVS_USER_HOME .'/.rvsitebuilder/deletepage.txt';
		$checkskipgetpage = ($checkIsUikit == true && is_file($path)) ? true : false;
		if ($checkskipgetpage == true && count($aPageStructure)) {
			//clear all page
			foreach ($aPageStructure as $projectPageId => $v) {
				DaoFactory::ProjectPage()->deleteProjectPageByprojectIpageIdAndProjectIdAndUsrId($projectId, $usrId, $projectPageId);
				SGL::logMessage('delete all page: ' . $projectPageId, PEAR_LOG_DEBUG);
			}
			$aPageStructure = array();
		}
		return $aPageStructure;
	}

	function getPrivacyPage($aPageData)
	{
		$aPageData['pageStructure']['privacy_policy'] = 'Privacy Policy';
		$aPageData['pathway']['privacy_policy']= '<div class="uk-container uk-container-center">
			<div class="bgContent">
			<div class="uk-container uk-container-center">
				<ul class="uk-breadcrumb">
				   <li><a href="index.php">Home</a></li><li class="uk-active">Privacy Policy</li>
				 </ul>
			</div>
			</div>
		</div>';
		
		$aPageData['pageData']['privacy_policy'] = file_get_contents(WEB_THEME_PATH . '/UikitTemplate/default_content/privacy_policy.html');
		//$aPageData['navCode'] = $aPageData['navCode'] . "\n" . '<li><a href="privacy_policy.php"><span>Privacy Policy</span></a></li>' . "\n";
		$aPageData['footerNav'] = $aPageData['footerNav'] . ' | ' . '<a href="privacy_policy.php">Privacy Policy</a>' . "\n";
		
		return $aPageData;
	}
	
	function _cmd_add(&$input, &$output)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		//Delete file preview when change template
	    RvsLibs_Project::deleteFileProjectPreview($input->project_id);
	    SGL::logMessage('cmd:category_id:' . $input->category_id, PEAR_LOG_DEBUG);
	    if ($input->category_id) {
			// UPDATE rvs_project_item
			$resultAdd = DaoFactory::Project()->updateProjectInfoDataByTemplateItemIdAndCategoryId($input->template_item_id, $input->category_id, $input->navigator_id, $input->check_step, $input->navigator_name_id, $input->project_id, $input->rvs_usr_id, $input->project_info_id);
		} else {
			SGL::logMessage('Undefine category_id ', PEAR_LOG_DEBUG);
			RvsLibs_String::translate(SGL::raiseError('Please select category!', SGL_ERROR_NOFILE));
		}
		//Start case select new template reset navigator to default : duangdao.k
		$input->aTemplateData = RvsLibs_Template::getTemplatesData($input->project_id, true, false);
		$templateres = $input->aTemplateData->templatePath . '/' . $input->aTemplateData->template_item_folder;
		$checkIstemplateresponsive = RvsLibs_Template::isResponsiveTemplate($templateres);
		$checkIsUikit = RvsLibs_Template::isUikitTemplate($templateres);

		//add page data : (ครั้งแรกที่ user create project)
		$aPageStructure = RvsLibs_Project::getAllPageIdByProjectId($input->project_id);
		//for skip delete all page
		$aPageStructure = self::skipDeletePageAll($templateres, $input->project_id, $input->rvs_usr_id, $aPageStructure, $checkIsUikit);

		if ($checkIsUikit == true && !count($aPageStructure)) {
			$filePathData = $templateres . '/templateData.txt';
			if (is_readable($filePathData)) {
				SGL::logMessage('load page: ' . $filePathData, PEAR_LOG_DEBUG);
				$content = file_get_contents($filePathData);
				$aPageData = json_decode($content, true);
				$aListpage = array_keys(($aPageData['pageData']));
			}
			//echo '<pre>';
			array_push($aListpage, 'privacy_policy');
			//print_r($aListpage);
			$aPageData = $this->getPrivacyPage($aPageData);
			//print_r($aPageData);
			//exit;
			
			$pageStructer = RvsLibs_Project::addPageStructure($aListpage, $aPageData);

			$path = WEB_THEME_PATH . '/UikitTemplate/uikit_block_design/footer/project_footer.html';
			$content = (is_file($path)) ? file_get_contents($path) : '';
			$content = str_replace('&copy; 2016', '&copy; ' . date("Y"), $content);

			$aPageData['footer'] = $content;


			DaoFactory::Project()->updateProjectFooterByProjectId(
				$aPageData['footer'],
				$input->project_id,
				$input->rvs_usr_id
			);
			$pageId = '';
			if (isset($pageStructer['home'])) {
				$pageId = $pageStructer['home'];
			}
			SGL_Session::set('template_item_path', $templateres);
		}

		/// BEGIN: Analytics Switch Template Users ::Apiruk
		try {
			if (RvsLibs_String::isPHP53() == true && RvsLibs_User::isSkipAnalytics() == false) {
				$mainIp = Sitebuilder::getMainIP();
				$projectId = SGL_Session::get('rvs_project_id');
				$oRVGATracking = RvsLibs_RVGATracking::singleton();

				// count switch template
				if ($input->category_id && $input->template_item_id) {
					$oRVGATracking->setEvent('RVSiteBuilder/SwitchTemplate', $mainIp, RVS_USER_NAME . '_' . $projectId, 1);
					$oRVGATracking->sendAllEvent();
				}

				if ($input->ref_category_id != $input->category_id) {
					//defind old type
					$isDisOld = RvsLibs_Template::isDistributeTemplate($input->aRefTemplateData->template_item_folder);
					$isDiyOld = RvsLibs_Template::isDiyTemplate($input->aRefTemplateData->templatePath, $input->aRefTemplateData->template_item_folder);
					$isImportOld = RvsLibs_Template::isImportTemplate($input->aRefTemplateData->template_item_id);

					//defind new type
					$isDisNew = RvsLibs_Template::isDistributeTemplate($input->aTemplateData->template_item_folder);
					$isDiyNew = RvsLibs_Template::isDiyTemplate($input->aTemplateData->templatePath, $input->aTemplateData->template_item_folder);
					$isImportNew = RvsLibs_Template::isImportTemplate($input->aTemplateData->template_item_id);

					SGL::logMessage('rvgatrack: old cid:' . $input->ref_category_id . ' old folder:' . $input->aRefTemplateData->template_item_folder);
					SGL::logMessage('rvgatrack: new cid:' . $input->category_id . ' new folder:' . $input->aTemplateData->template_item_folder);
					SGL::logMessage('rvgatrack: old isDisOld:' . $isDisOld . ' isDiyOld:' . $isDiyOld . ' isImportOld:' . $isImportOld);
					SGL::logMessage('rvgatrack: old isDisNew:' . $isDisNew . ' isDiyNew:' . $isDiyNew . ' isImportNew:' . $isImportNew);
					//delete old type
					if ($isDisOld) {
						$oRVGATracking->setEvent('RVSiteBuilder/UseDistribuildTemplate', $mainIp, RVS_USER_NAME . '_' . $projectId, -1);
					} elseif ($isDiyOld) {
						$oRVGATracking->setEvent('RVSiteBuilder/UseDiyTemplate', $mainIp, RVS_USER_NAME . '_' . $projectId, -1);
					} elseif ($isImportOld) {
						$oRVGATracking->setEvent('RVSiteBuilder/UseImportTemplate', $mainIp, RVS_USER_NAME . '_' . $projectId, -1);
					}

					//add new type
					if ($isDisNew) {
						$oRVGATracking->setEvent('RVSiteBuilder/UseDistribuildTemplate', $mainIp, RVS_USER_NAME . '_' . $projectId, 1);
					} elseif ($isDiyNew) {
						$oRVGATracking->setEvent('RVSiteBuilder/UseDiyTemplate', $mainIp, RVS_USER_NAME . '_' . $projectId, 1);
					} elseif ($isImportNew) {
						$oRVGATracking->setEvent('RVSiteBuilder/UseImportTemplate', $mainIp, RVS_USER_NAME . '_' . $projectId, 1);
					}

					$oRVGATracking->sendAllEvent();
				}
			}
		} catch (Exception $e) {

		}
		/// END: Analytics Switch Template ::Apiruk

        //validate on-demand template
        $isDistributeTemplate = RvsLibs_Template::isDistributeTemplate($input->aTemplateData->template_item_folder);
        //SGL::logMessage('cmd: isDistributeTemplate : ' . $isDistributeTemplate, PEAR_LOG_DEBUG);
        //SGL::logMessage('cmd: noredirect : ' . $input->noredirect, PEAR_LOG_DEBUG);

        if ($isDistributeTemplate && isset($input->url_download_template) && $input->url_download_template) {
            if ($input->noredirect == '0' && RvsLibs_Template::validateDownload($input->aTemplateData->template_item_folder)) {

                SGL_HTTP::redirect(array('managerName' => 'preview'
                	,'action' => 'viewdownload'
                    ,'nextredirect' => 'rvscategory'
                    ,'nextaction' => 'add'
                    ,'template_item_id' => $input->template_item_id)
               );
            }
        }

        $customPath = RvsLibs_Project::getCustomCssPath(
        	$input->project_id,
        	$input->aTemplateData->template_item_folder
        );
        //isUikit
        if ($checkIsUikit == true) {
        	//Default copy rvsb-css
        	//From:: www/UikitTemplate/MasterTemplateUIKit
        	//To: Custom
        	$sourceLib = UIKIT_LIB_PATH . '/rvsb-css';
        	$source = $templateres . '/rvsb-css';
        	$dest = RvsLibs_File::buildPath(
        			array($customPath, 'rvsb-css'
        	));
        	if (is_dir($dest) == false) {
        		//Case1: select template first copy rvs-css
        		SGL::logMessage('Case1: select template first copy rvs-css', PEAR_LOG_DEBUG);
        		RvsLibs_System::mkdir(array('-p', '-m', 0755, $dest));
        		RvsLibs_System::copy(array('-R', $source, $dest));
        		SGL::logMessage('Copy source::== ' . $source, PEAR_LOG_DEBUG);
        		SGL::logMessage('Copy dest::== ' . $dest, PEAR_LOG_DEBUG);

        		//extend uikit
        		RvsLibs_System::copy(array($sourceLib . '/rvsb-common.css', $dest . '/rvsb-common.css'));
        		RvsLibs_System::copy(array($sourceLib . '/rvsb-extended-uikit.css', $dest . '/rvsb-extended-uikit.css'));
        		RvsLibs_System::copy(array($sourceLib . '/rvsb-footer-block.css', $dest . '/rvsb-footer-block.css'));
        		//copy default navigator style 3-5
        		RvsLibs_System::copy(array($sourceLib . '/rvsb-nav-style-3.css', $dest . '/rvsb-nav-style-3.css'));
        		RvsLibs_System::copy(array($sourceLib . '/rvsb-nav-style-4.css', $dest . '/rvsb-nav-style-4.css'));
        		RvsLibs_System::copy(array($sourceLib . '/rvsb-nav-style-5.css', $dest . '/rvsb-nav-style-5.css'));

        		SGL::logMessage('Copy source::== ' . $source, PEAR_LOG_DEBUG);
        		SGL::logMessage('Copy dest::== ' . $dest, PEAR_LOG_DEBUG);

        		//test
        		RvsLibs_Navigator::generateCssUikitStyle3to5($customPath);
        	} else {
        		//Case2: update rvs-css
        		SGL::logMessage('Case2: update rvs-css', PEAR_LOG_DEBUG);
        		RvsLibs_Template::updateUikitCss($source, $dest);

        		//test
        		RvsLibs_Navigator::generateCssUikitStyle3to5($customPath);
        	}
        	//copy template images
        	$source = $templateres . '/images';
        	$dest = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $input->project_id, 'images'));
        	if (is_dir($source) == true) {
        		//RvsLibs_System::copy(array('-f', '-R', $source, $dest));
        		$cmd = 'cp -a ' . $source . '/* ' . $dest;
        		$res = RvsLibs_System::exec($cmd);

        		RvsLibs_System::exec("chmod 755 -R {$dest}");
        		//RvsLibs_System::copy(array('-R', $source, $dest));
        		//RvsLibs_System::secureCommand('copyrvsecure', array('source_path' => $source,'dest_path' => $dest));
        		SGL::logMessage('Copy image::== ' . $source, PEAR_LOG_DEBUG);
        		SGL::logMessage('Copy image::== ' . $dest, PEAR_LOG_DEBUG);
        		//exit;
        	}

        	$input->aHeaderBanner = RvsLibs_Template::updateUikitHB($templateres, $customPath, $input->project_id);

        	//select template fisrt page layout deafult full_width
        	$fileConfigImgHeaderBanner = RvsLibs_File::buildPath(array($customPath, 'headerbannner.ini.php'));
        	$aData = RvsLibs_File::getJsonDecodeFile($fileConfigImgHeaderBanner, true);
        	$aData['width'] = 'full_width';
        	RvsLibs_File::writeJsonEncodeFile($fileConfigImgHeaderBanner, $aData);
        }

		///ปรับการ load responsive template
		if ($checkIstemplateresponsive === true ) {
			///load template.ini.php
			$aTemplateConfig = RvsLibs_Template::getTemplateConfig(
				$input->project_id,
				$input->aTemplateData->templatePath,
				$input->aTemplateData->template_item_folder
			);
			$hbFile = RvsLibs_File::buildPath(array(
				$customPath,
				'headerbannner.ini.php'
			));

			if (!empty($aTemplateConfig['rs_hb_img']) && !is_file($hbFile)) {
				$pathImgHB = RvsLibs_File::buildPath(array(
					$input->aTemplateData->templatePath,
					$input->aTemplateData->template_item_folder,
					'images',
					trim($aTemplateConfig['rs_hb_img'])
				));
				//Only the 1ft time to add headerbanner auto
				RvsLibs_Template::updateDefaultHB(
					$input->project_id,
					$pathImgHB,
					$input->aTemplateData->template_item_folder
				);
			} else {
				//reset main header_banner
				$pathImgHB = RvsLibs_File::buildPath(array(
                    $input->aTemplateData->templatePath,
                    $input->aTemplateData->template_item_folder,
                    'images',
                    trim($aTemplateConfig['rs_hb_img'])
                ));
                $pathHeaderBaner = RvsLibs_File::buildPath(array(
                    REAL_PROJECT_PATH, $input->project_id, 'images', 'headerbanner', 'header_banner.jpg'
                ));
                $pathHeaderBanerOrg = RvsLibs_File::buildPath(array(
                    REAL_PROJECT_PATH, $input->project_id, 'images', 'headerbannerorg', 'header_banner.jpg'
                ));
				@copy($pathImgHB, $pathHeaderBaner);
				@copy($pathImgHB, $pathHeaderBanerOrg);
			}
		}
        //End template responsive


		$this->UpdateDynamicVar($input);
		$this->_SetDefaultLayout($input);

		if ($checkIsUikit == true) {
			if (empty($pageId)) {
				$pageId = RvsLibs_Project::getLessPriority($input->project_id);
			}
			SGL_HTTP::redirect(array('managerName' => 'rvwysiwyguikit'));
		}
        if (isset($input->gotostep) && $input->gotostep === '1') {
            SGL_HTTP::redirect(array('managerName' => 'rvscategory'));
        } else if ( (isset($input->isTest) && $input->isTest === false)
            || (isset($input->isTest) === false)
            || (isset($input->gotostep) && $input->gotostep === '2')
            ) {
            SGL_HTTP::redirect(array('managerName' => 'adjustStyle'));
        }
	}

	function _cmd_edit(&$input, &$output)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
	}

	function _cmd_list(&$input, &$output)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$isDistributeTemplate = false;
		$aTemplateData = RvsLibs_Template::getTemplatesData($input->project_id, true, false);
		if (isset($aTemplateData->template_item_folder) == true) {
			$isDistributeTemplate = RvsLibs_Template::isDistributeTemplate($aTemplateData->template_item_folder);
		}
		if ($isDistributeTemplate) {
			$customCssPath = RvsLibs_Project::getCustomCssPath($input->project_id, $aTemplateData->template_item_folder);
			$hbFile = RvsLibs_File::buildPath(array(
					$customCssPath,
					'headerbannner.ini.php'
			));
			$aHeaderBanner = RvsLibs_File::getHeaderBannerData($hbFile);
			foreach ($aHeaderBanner as $val) {
				$imgFile = REAL_PROJECT_PATH . '/' . $input->project_id . '/images/headerbanner/' . $val['name'];
				$orgHB = TEMPLATE_PATH . '/' . $aTemplateData->template_item_folder . '/images/' . $val['name'];
				if (!is_file($imgFile) && is_file($orgHB)) {
					$pathHeaderBaner = RvsLibs_File::buildPath(array(
							REAL_PROJECT_PATH, $input->project_id, 'images', 'headerbanner'
					));
					$pathHeaderBanerOrg = RvsLibs_File::buildPath(array(
							REAL_PROJECT_PATH, $input->project_id, 'images', 'headerbannerorg'
					));
					if (!is_dir($pathHeaderBaner)) {
						RvsLibs_System::mkDir(array('-p', '-m', '0755', $pathHeaderBaner));
					}
					if (!is_dir($pathHeaderBanerOrg)) {
						RvsLibs_System::mkDir(array('-p', '-m', '0755', $pathHeaderBanerOrg));
					}

					$aSizeImg = array('h' => $val['hd_height'],'w' => $val['hd_width']);
					$aPositionXY = array('x' => $val['position_x'],'y' => $val['position_y']);

					//make crop $quality 100%
					$res = RvsLibs_Image2::makeCrop(
							$orgHB,
							$imgFile,
							164, 100,'gd',$aSizeImg,
							$aPositionXY
					);
					if (SGL::isError($res)) {
						SGL::logMessage('Crop image not success:' . $res->getMessage(), PEAR_LOG_DEBUG);
						SGL_Error::pop();
						RvsLibs_System::copy(array($orgHB, $imgFile));
					}
					$pathImgHeaderBannerOrg = RvsLibs_File::buildPath(array($pathHeaderBanerOrg, $val['name']));
					if (is_file($pathImgHeaderBannerOrg)) {
						RvsLibs_System::rm(array('-f', $pathImgHeaderBannerOrg));
					}
					RvsLibs_System::copy(array($orgHB, $pathImgHeaderBannerOrg));

				}
			}
			if (isset($input->currentIsResponsive) && $input->currentIsResponsive == true) {
				$this->_isResponsiveCreateLayoutCss(
						TEMPLATE_PATH . '/' . $aTemplateData->template_item_folder,
						$customCssPath
				);
			}
		}


		/*
		if ($input->ondemand_template && $isDistributeTemplate && isset($input->url_download_template) && $input->url_download_template) {
			if (RvsLibs_Template::validateDownload($aTemplateData->template_item_folder) && $input->noredirect == '0') {
				SGL_HTTP::redirect(array(
					'managerName' => 'preview'
					, 'action' => 'viewdownload'
					, 'nextredirect' => 'rvscategory'
					, 'nextaction' => 'list'
					, 'template_item_id' => $aTemplateData->template_item_id
				));
			}
		}
		*/
	}

	function _isResponsiveCreateLayoutCss($templateItemFolderPath, $customCssPath)
	{
		$layoutCss = RvsLibs_File::buildPath(array($customCssPath, 'layout.css'));
		SGL::logMessage($layoutCss, PEAR_LOG_DEBUG);
		if (!is_file($layoutCss)) {
			$layoutCssSrc = RvsLibs_File::buildPath(array($templateItemFolderPath, 'layout.css'));
			$staticLayout = SGL_WEB_ROOT . '/responsiveTemplates/stylesheets/static_layout.css';
			$layoutCustomCss = RvsLibs_File::buildPath(array($customCssPath, 'custom_layout.css'));
			RvsLibs_Template::mergeCustomcss($layoutCss, array($layoutCssSrc, $layoutCustomCss, $staticLayout));
		}
	}

	function _SetDefaultLayout(&$input)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$aProjectInfoData = RvsLibs_Project::getProjectInfoData($input->project_id);
		$layoutTemplateId = (isset($aProjectInfoData[0]->layout_template_id))? $aProjectInfoData[0]->layout_template_id : '';
		$layoutTemplateId = $this->getLayoutTemplateIdExistsOldId($layoutTemplateId);
		$projectInfoId = (isset($aProjectInfoData[0]->project_info_id))? $aProjectInfoData[0]->project_info_id : '';

		if ($layoutTemplateId == 0 || $layoutTemplateId == '') {
			$aFullLayout = DaoFactory::LayoutTemplate()->findLayoutTemplateIdByLayoutCategoryId('1', 'getall');
			foreach ($aFullLayout as $k =>$v) {
				$layoutId = $aFullLayout[$k]->layout_template_id;
				$aLayOutId[$layoutId] = $layoutId;
			}
			$aKeys = array_keys($aLayOutId);
			$randLayoutId = array_rand($aKeys, 1);

			if ($input->template_item_id) {
				$layoutId =  $this->oTemplateList->_GetDefaultLayoutId($input->template_item_id);
				if (in_array($layoutId, $aLayOutId)) {
					$defaultLayoutId = $layoutId;
				} else {
					$defaultLayoutId = $aKeys[$randLayoutId];
				}
			} else {
				$defaultLayoutId = $aKeys[$randLayoutId];
			}
			$res = DaoFactory::Project()->updateLayoutTemplateId($defaultLayoutId, $input->project_id, $input->rvs_usr_id, $projectInfoId);
			SGL::logMessage('L: ' . __LINE__ . '*** RVS query update ' . NULL, PEAR_LOG_DEBUG);
		}

		//update layout id change template to old template
		RvsLibs_Project::changeLayoutUpdatatoDb($input->project_id, $input->rvs_usr_id);

		return $layoutTemplateId;
	}

	function getTemplateItemNavigatorData($templateItemId)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$res = DaoFactory::Template()->findTemplateItemByTemplateItemId($templateItemId, 'getrow');
		// optimize :nipaporn
		return DaoFactory::Navigator()->findTemplateDataAndNavigatorDataAndNavigatorNameDataByNavigatorId($res['template_id'], 'getrowobj');
	}

	function getLayoutTemplateIdExistsOldId($layoutTemplateId)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$aOldLayoutTemplateId = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
		if (in_array($layoutTemplateId, $aOldLayoutTemplateId)) {
			return $layoutTemplateId;
		} else {
			$res = DaoFactory::LayoutTemplate()->findLayoutTemplatePreviewAndDataByLayoutTemplateId($layoutTemplateId, 'getrow');
			// optimize :nipaporn
			return (!$res) ? '' : $layoutTemplateId;
		}
	}

	function setFocus($aCategoryFocus , $focusID)
	{
		$aSetFocusN = array();
		foreach ($aCategoryFocus as $kCategoryFocus => $vCategoryFocus) {
			$aSetFocusN[$kCategoryFocus]['name'] = $vCategoryFocus;
		}
		if ($focusID != 23 && $focusID != 'DiyPicture') {
			$aSetFocusN[$focusID]['focus'] = true;
		}
		return $aSetFocusN;
	}

	function getFileSystemPath()
	{
	    SGL::logMessage(null, PEAR_LOG_DEBUG);
	    $aInput['templateUrl'] = SGL_BASE_URL . '/tryout/www/template';
	    $aInput['templatePath'] = SGL_PATH  . '/tryout/www/template';
	    $aInput['rvs_url_www'] = SGL_BASE_URL  . '/tryout/www';
	    $aInput['pagerUrl'] = SGL_BASE_URL . '/' . $this->conf['site']['frontScriptName'] . '/tryout/RvsCategory';
	    if ($this->conf['site']['frontScriptName'] == "rvsindex.php?" || preg_match("/cgi|apache2filter/i", php_sapi_name())) {
	    	$aInput['url_php_suexec'] = SGL_BASE_URL  . '/tryout/www';
	    }
		define('TEMPLATE_PATH', $aInput['templatePath']);
		define('TEMPLATE_URL', $aInput['templateUrl']);
		return $aInput;
	}

	function UpdateDynamicVar($input)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		// Get Page Data
		$projectId = $input->project_id ? $input->project_id : SGL_Session::get('rvs_project_id');
		$ursId = $input->rvs_usr_id ? $input->rvs_usr_id : RvsLibs_User::getUserId();
		$aPageData = RvsLibs_Project::getProjectPageData($projectId, $ursId);
		// Get Path index.html
		if ($input->template_item_id) {
			$aTemplateItemData = DaoFactory::Template()->findTemplateItemByTemplateItemId($input->template_item_id, 'getrow');
			$templateItemFolder = $aTemplateItemData['template_item_folder'];
		} else {
			$aProjectInfoData = RvsLibs_Project::getProjectInfoData($projectId);
			$templateItemFolder = $aProjectInfoData[0]->template_item_folder;
		}
		$fileTemplateIndex = TEMPLATE_PATH . '/' . $templateItemFolder . '/index.htm';
		// Loop aPageData
		foreach ($aPageData as $key=>$value) {
			$pageData = $aPageData[$key]->page_data;
			$projectPageId = $aPageData[$key]->project_page_id;
			// Get Replace Tag
			$aTagRvsLayoutTemplate = RvsLibs_Project::getRvsLayoutTag($pageData);
			// Check Layout Template is Exist
			if (count($aTagRvsLayoutTemplate) != 0 && is_readable($fileTemplateIndex)) {
				$replaceWidth = RvsLibs_Template::GetLayoutReplaceWidth($fileTemplateIndex);
				// Define Replace <table>
				foreach ($aTagRvsLayoutTemplate as $key=>$value) {
					$regExpWidth = '/width\s*=\s*["|\'][0-9]{1,}["|\']/i';
					$aResultSplit = RvsLibs_String::preg_split($regExpWidth, $value);
					$width = 'width="' . $replaceWidth . '"';
					$aReplaceTable[$key] = $aResultSplit[0] . $width . $aResultSplit[1];
				}
				// Replace <table> layout template
				foreach ($aTagRvsLayoutTemplate as $key=>$value) {
					$pageData = str_replace($value, $aReplaceTable[$key], $pageData);
				}
				// Update Page Data
				$res = DaoFactory::ProjectPage()->updatePageDataByProjectIdAndUsrIdAndProjectPageId($pageData, $projectId, $ursId, $projectPageId, false);
			}
		}
	}
}
?>