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/lib/RVSGL/rvsLibs/Project.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$
// +---------------------------------------------------------------------------+

/**
 * RvSiteBuilder project(s) libary
 *
 * @package RvsLibs
 * @author  Pairote Manunphol <pairote@rvglobalsoft.com>
 * @version $Revision$
 * @since   PHP 5.1
 */
if (class_exists('RvsLibs_Project_Delete') === false) {
	class RvsLibs_Project_Delete
	{
		public static function deleteProjectDB($projectId, $usrId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aMethods = DaoFactory::getClassMethods();
			$aTasks = array();
			foreach ($aMethods as $method) {
				if ($method != 'DaoFactory' && $method != 'factory') {
					$aTasks[] = DaoFactory::factory($method);
				}
			}
			foreach ($aTasks as $task) {
				$res = $task->deleteProjectOfUserId($projectId, $usrId);
				if (SGL::isError($res) === true) {
					return $res;
				}
			}
		}

		public static function deleteProjectFolder($projectFolderPath)
		{
			$realProjectFolder = (is_link($projectFolderPath)) ? readlink($projectFolderPath) : "";
			if (file_exists($realProjectFolder)) {
				RvsLibs_System::rm(array('-rf', $realProjectFolder));
			}
			if (file_exists($projectFolderPath)) {
				RvsLibs_System::rm(array('-rf', $projectFolderPath));
			}
		}

		public static function removeComponentSession($createNew = 1)
		{
			if ($createNew == 1) {
				SGL_Session::remove('rvs_tryout');
				SGL_Session::remove('rvs_project_id');
			}
		}

		public static function deleteFileProjectPreview($projectId)
		{
			//delete folder images css js กรณีที่มีการเลือก template ใหม่
			$previewPathCss = PROJECT_PATH . '/' . $projectId . '/RvSitebuilderPreview/preview';
			$previewPathImg = PROJECT_PATH . '/' . $projectId . '/RvSitebuilderPreview/preview/images';
			$previewPathJs = PROJECT_PATH . '/' . $projectId . '/RvSitebuilderPreview/preview/js';
			if (is_dir($previewPathCss)) {
				$aCssFiles = System::find("$previewPathCss -name *.css");
				foreach ($aCssFiles as $key => $file) {
					if (preg_match("/\.css$/",$file)) {
						if (is_file($file)) {
							RvsLibs_System::rm(array('-f', $file));
						}
					}
				}
			}

			if (is_dir($previewPathImg)) {
				RvsLibs_System::rm(array('-rf', $previewPathImg));
			}

			if (is_dir($previewPathJs)) {
				RvsLibs_System::rm(array('-rf', $previewPathJs));
			}
		}

		/**
		 * not have compodb delete componentframework
		 * @return unknown_type
		 */
		public static function deleteComponentFramework($projectId,$userId)
		{
			$pathComponentDB = REAL_PROJECT_PATH . '/' . $projectId . '/compoDBConnect.ini.php';
			$isCombo  = RvsLibs_Component::isComponentDB($projectId);
			if ($isCombo === false && is_file($pathComponentDB)) {
				$pageId = DaoFactory::ProjectPage()->findComponentAndUserFrameworkPageByProjectId($projectId,'getone');
				if ($pageId) {
					$aProjectPage = DaoFactory::ProjectPage()->deleteProjectPageByprojectIpageIdAndProjectIdAndUsrId($projectId, $userId, $pageId);
					$aProjectLayoutPage = DaoFactory::ProjectLayoutPage()->deleteProjectLayoutByProjectPageIdAndUsrIdAndProjectId($pageId, $userId, $projectId);
				}
				//unlink($pathComponentDB);
			}
		}
	} //end class
}

if (class_exists('RvsLibs_Project_Set') === false) {
	class RvsLibs_Project_Set extends RvsLibs_Project_Delete
	{
		/**
		 * if page name exist and do not have custom_page_name
		 * to do update custom_page_name auto by priority of pagestructure
		 *
		 * @param <string> $pageId
		 * @param <string> $pageName
		 * @param <string> $projectId
		 * @return boolean
		 */
		public static function updateCustomPageIfPageNameExist($pageId, $pageName, $projectId)
		{
			$res = DaoFactory::ProjectPage()->updatecustomPageNameByprojectPageIdAndProjectId($pageName, $pageId, $projectId);
			return ($res) ? true : false;
		}

		/**
		 *  ยุบ function templateitemid
		 * @param unknown_type $projectInfoId
		 * @param unknown_type $templateItemId
		 * @return unknown
		 */
		public static function updateTemplateItemId($projectInfoId,$templateItemId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$projectId = SGL_Session::get('rvs_project_id');
			$rvsUserId =  RvsLibs_User::getUserId();
			$aDetailTem = DaoFactory::Template()->findRefTemplateDataByCategoryIdAndTemplateItemId(null, $templateItemId,'getrow');
			$aProjectInfoData = DaoFactory::Project()->findProjectInfoDataByProjectId($projectInfoId, 'getrow');
			$resTemplate = DaoFactory::Template()->findTemplateItemByTemplateItemId($templateItemId, 'getrow');
			$res = DaoFactory::Navigator()->findTemplateDataAndNavigatorDataAndNavigatorNameDataByNavigatorId($resTemplate['template_id'], 'getrowobj');

			$navigatorNameId = (isset($res->navigator_name_id)) ? $res->navigator_name_id : '3';
			$navigator_id  = (isset($res->navigator_id)) ? $res->navigator_id : '';
			$navigatorNameId = (isset($aProjectInfoData[0]->navigator_name_id))
			                     ? $aProjectInfoData[0]->navigator_name_id
			                     : $navigatorNameId;
			//Delete file preview when change template
			RvsLibs_Project::deleteFileProjectPreview($projectId);

			return DaoFactory::Project()->updateProjectInfoDataByTemplateItemIdAndCategoryId(
			             $templateItemId
			             , $aDetailTem['rvs_category_id']
			             , $navigator_id
			             , '5'
			             , $navigatorNameId
			             , $projectId
			             , $rvsUserId
			             , $projectInfoId
			      );
		}

		function addPageStructure($aListpage, $aPageData) {
			//print_r($aPageData);exit;
			if(count($aListpage) > 0){
				$priority = 1;
				require_once SGL_MOD_DIR . '/sitebuilder/classes/PageStructureMgr.php';
				$oPageStructure= new PageStructureMgr();
				$userId = RvsLibs_User::getUserId();
				$projectId = RvsLibs_Project::getProjectId();
				foreach($aListpage as $k=>$v){
					$componentId = '0';
					//default layout page
					if (isset($aPageData['pageStructure'][$v])) {
						$pagename = $aPageData['pageStructure'][$v];
						$pagedata = $aPageData['pageData'][$v];
					} else {
						$pagedata = file_get_contents(RvsLibs_File::buildPath(array(SGL_WEB_ROOT, 'UikitTemplate','default_content', 'body.html')));
					}
					$chkCompo = RvsLibs_String::strpos($v, '@');
					if ($chkCompo > 0) {
						$page = RvsLibs_String::dbeExplode('@@', $v);
						if (isset($page[1]) && $page[1] == 'Online_Form') {
							$componentId = $oPageStructure->_searchComponent($page);
							$aDataJotform = $oPageStructure->setDataJotform();
							$oPageStructure->makeInsertDataForJotform($aDataJotform);
							$pagedata = $oPageStructure->getDataJotformWys($aDataJotform['jotformId']);
							$v = $page[0];
						}
					}
					if (!isset($pagename)) {
						$pagename = RvsLibs_String::translate($v);
					}

					//page layout deafult full_width
					$pagedata = str_replace('<div class="uk-container uk-container-center"> <!-- Set Row Full width must use class  of Design block -->'
							, '<div class="uk-container uk-container-center rv-block-full"> <!-- Set Row Full width must use class  of Design block -->'
							, $pagedata);

					$projectPageId = RvsLibs_String::genUniqueId();
					$pageStructer[$v] = $projectPageId;
					SGL::logMessage('insert page ===> :' .  $pagename, PEAR_LOG_DEBUG);
					$res2 = DaoFactory::ProjectPage()->insertProjectPage('', $pagedata, $componentId, $pagename, $userId, $projectPageId, '', '');
					$res1 = DaoFactory::ProjectPage()->insertProjectPageOutSeggestion($projectPageId, $k);
					$isHome = (strtolower($v) == 'home' || $priority == 1) ? '1' : '0';
					
					//privacy_policy add internal page
					if (strtolower($v) == 'privacy_policy') {
						$internalPageId = RvsLibs_String::genUniqueId();
						$resInsert = DaoFactory::InternalPage()->insertInternalPage($internalPageId, $projectId, $projectPageId);
					} else {
						$res = DaoFactory::ProjectLayoutPage()->insertProjectLayout($priority,'0', $projectPageId, $projectId, $isHome);
					}
					
					$priority++;
				}
				return $pageStructer;
			}
		}
	}
}

if (class_exists('RvsLibs_Project_Get') === false) {
	class RvsLibs_Project_Get extends RvsLibs_Project_Set
	{
		public static function getProjectVersion($projectId = null)
		{
			$projectCreateAt = '0';
			$projectId = (empty($projectId)) ? RvsLibs_Project::getProjectId() : $projectId;
			$projectPath = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $projectId, 'version.txt'));
			if (is_file($projectPath)) {
				$content = file_get_contents($projectPath);
				$projectCreateAt = RvsLibs_Util::getFloat($content);
			}
			return $projectCreateAt;
		}

		public static function getPhotoAlbumInfo($albumID)
		{
			$albumInfo = array(
				'album_id' => $albumID
			);
			$projectId = RvsLibs_Project::getProjectId();
			$data = RvsLibs_File::buildPath(
				array(REAL_PROJECT_PATH, $projectId, 'album_'.$albumID, 'data.dat')
			);
			if (is_file($data)) {
				$content = file_get_contents($data);
				$albumInfo = json_decode(trim($content), true);
			}
			return $albumInfo;
		}

		public static function getEditorMgr($isUikit = '')
		{
			$projectVersion = SGL_Session::get('project_version');
			$editor = ($isUikit == true) ? 'rvwysiwyguikit' : (($projectVersion < 5.4) ? 'wysiwyg' : 'rvwysiwyg');
			SGL::logMessage('return editor:' . $editor, PEAR_LOG_DEBUG);
			return $editor;

		}

		public static function getLoginBlockId()
		{
			return md5('login block');
		}

		public static function getNewsletterBlockId()
		{
			return md5('newsletter block');
		}

		public static function getAvaliableBlockByProject($project_id)
		{
			$blockData = DaoFactory::Block()->findBlockDataByProjectId($project_id);
			$isComponentDb = RvsLibs_Component::isComponentDB($project_id);
			$loginBlockId = RvsLibs_Project::getLoginBlockId();
			if ($isComponentDb == false && isset($blockData[$loginBlockId])) {
				//if not componentdb, unset block login
				unset($blockData[$loginBlockId]);
			}

			$res = DaoFactory::ProjectPage()->findProjectPageDataByComponentName($project_id, 'Newsletter');
			if (SGL::isError($res)) {
				SGL_Error::pop();
			} else {
				$newsletterBlockId = RvsLibs_Project::getNewsletterBlockId();
				if (!count($res) && isset($blockData[$newsletterBlockId])) {
					//if not newsletter, unset block newsletter
					unset($blockData[$newsletterBlockId]);
				}
			}
			return $blockData;
		}

		/**
		 *
		 * Enter description here ...
		 * @param $blockData
		 * @param $bloclOfLayout
		 * @param $activeLeft
		 * @param $activeRight
		 * @return array(1 => object(),2 => object(),3 => object(),4 => object())
		 */
		public static function getBlockBySection($blockData, $bloclOfLayout, $activeLeft, $activeRight, $publishUrl, $themeUrl)
		{
			$projectId = SGL_Session::get('rvs_project_id');
			$buff = array();
			$checkEdiableArea = array();
			foreach ($blockData as $key => $val) {
				$isAvilable = false;
				if (isset($bloclOfLayout[$key])) {
					$val = (object)array_merge((array)$val, (array)$bloclOfLayout[$key]);
				} else {
					$isAvilable = true;
				}
				//replace url to variable
				if (isset($val->block_data) && !empty($val->block_data)) {
					$val->block_data = RvsLibs_Project::replaceUrlToValue($val->block_data, $projectId);
					$val->block_data = RvsLibs_Project::replaceValueToUrl($val->block_data, $publishUrl, $themeUrl);
				}

				if ((!$activeLeft && ($val->section == 3)) || (!$activeRight && ($val->section == 4)) || $isAvilable) {
					$val->section = 0;
					$val->priority = isset($buff[0]) ? count($buff[0])+1 : 1;
				}
				$val->isEditableArea = false;
				if ($val->block_id == 'editable_area_left' || $val->block_id == 'editable_area_right') {
					$val->isEditableArea = true;
					array_push($checkEdiableArea, $val->block_id);
				}
				if (isset($buff[$val->section][$val->priority])) {
					//$val->priority = count($buff[$val->section])+1;
					$val->priority = RvsLibs_Project::getSortIndex($buff[$val->section], $val->priority);
					$buff[$val->section][$val->priority] = $val;
				} else {
					$buff[$val->section][$val->priority] = $val;
				}
			}
			/**กรณี editable area อยู่ล่างสุด**/
			if ($activeLeft && isset($bloclOfLayout['editable_area_left'])
			&& !in_array('editable_area_left', $checkEdiableArea)) {
				$priority = $bloclOfLayout['editable_area_left']->priority;
				if (isset($buff[3][$priority])) {
					$priority += 1;
					$bloclOfLayout['editable_area_left']->priority = $priority;
				}
				$buff[3][$priority] = $bloclOfLayout['editable_area_left'];
				$buff[3][$priority]->isEditableArea = true;
			} elseif ($activeLeft && !in_array('editable_area_left', $checkEdiableArea)) {
				$NextPriority = count($buff)+1;
				if(empty($buff[3][$NextPriority])) {
					$buff[3][$NextPriority] = new stdClass();
				}
				$buff[3][$NextPriority]->block_id = 'editable_area_left';
				$buff[3][$NextPriority]->section = 3;
				$buff[3][$NextPriority]->priority = $NextPriority;
				$buff[3][$NextPriority]->isEditableArea = true;
			}
			if ($activeRight && isset($bloclOfLayout['editable_area_right'])
			&& !in_array('editable_area_right', $checkEdiableArea)) {
				$priority = $bloclOfLayout['editable_area_right']->priority;
				if (isset($buff[4][$priority])) {
					$priority += 1;
					$bloclOfLayout['editable_area_right']->priority = $priority;
				}
				$buff[4][$priority] = $bloclOfLayout['editable_area_right'];
				$buff[4][$priority]->isEditableArea = true;
			} elseif ($activeRight && !in_array('editable_area_right', $checkEdiableArea)) {
				$NextPriority = count($buff)+1;
				if(empty($buff[4][$NextPriority])) {
					$buff[4][$NextPriority] = new stdClass();
				}
				$buff[4][$NextPriority]->block_id = 'editable_area_right';
				$buff[4][$NextPriority]->section = 4;
				$buff[4][$NextPriority]->priority = $NextPriority;
				$buff[4][$NextPriority]->isEditableArea = true;
			}

			if (isset($buff[1])) {
				ksort($buff[1]);
			}
			if (isset($buff[2])) {
				ksort($buff[2]);
			}
			if (isset($buff[3])) {
				ksort($buff[3]);
			}
			if (isset($buff[4])) {
				ksort($buff[4]);
			}
			//echo '<pre> ====>';print_r($buff);exit;
			/**กรณี editable area อยู่ล่างสุด**/
			return $buff;
		}

		public static function getSortIndex($buff, $priority)
		{
			foreach ($buff as $k => $v) {
				if (isset($v->priority) && $priority == $v->priority) {
					$priority++;
					$priority = RvsLibs_Project::getSortIndex($buff, $priority);
				}
			}
			return $priority;
		}

		public static function getProjectPathId()
		{
			$projectId = RvsLibs_Project::getProjectId();
			return RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $projectId));
		}

		/**
		 * Get Project ID in Session
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @return string; Return RVSiteBuilder Project ID , if not found RVSitebuilder project id in session orturn PEAR::ERROR
		 */
		public static function getProjectId()
		{
			$projectId = SGL_Session::get('rvs_project_id');
			if ($projectId) {
				return $projectId;
			} else {
				SGL::logMessage(RvsLibs_String::translate('Not found project id in session.'), PEAR_LOG_NOTICE);
				return '';
			}
		}

		/**
		 * getInternalPageData ๏ฟฝ๏ฟฝ๏ฟฝ hyperlink.php
		 * ๏ฟฝ๏ฟฝ๏ฟฝ็นต๏ฟฝอง๏ฟฝยก๏ฟฝอก๏ฟฝ๏ฟฝ ๏ฟฝ๏ฟฝ๏ฟฝอป๏ฟฝอง๏ฟฝัน๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝับสน
		 */
		public static function getInternalPageData($projectId, $rvsUsrId, $projectPageId = null)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$resInternalPage = DaoFactory::ProjectPage()->findInternalPageDataByProjectIdAndProjectPageId($rvsUsrId, $projectId, $projectPageId, 'getall');
			if (isset($resInternalPage)) {
				return $resInternalPage;
			}
		}

		/**
		 * Get data of project and template by project id
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param string $projectId
		 *
		 * @return obj
		 *      ->project_id
		 *      ->project_info_id
		 *      ->rvs_usr_id
		 *      ->project_name
		 *      ->project_directory
		 *      ->template_item_id
		 *      ->font_id
		 *      ->navigator_id
		 *      ->rvs_category_id
		 *      ->charset_id
		 *      ->project_company
		 *      ->project_slogan
		 *      ->project_logo
		 *      ->project_title
		 *      ->project_keyword
		 *      ->project_description
		 *      ->project_domain
		 *      ->check_step
		 *      ->effect_site_enter
		 *      ->duration_site_enter
		 *      ->last_update
		 *      ->layout_template_id
		 *      ->i_pathway
		 *      ->i_mail
		 *      ->i_print
		 *      ->i_favorite
		 *      ->no_slogan
		 *      ->no_company_name
		 *      ->navigator_name_id
		 */
		public static function getDataProjectInfoByProjectId($projectId)
		{
			/// Allow field to return :: BooM
			$_allowed_field = array(
            'project_id'
            , 'project_info_id'
            , 'rvs_usr_id'
            , 'project_name'
            , 'project_directory'
			, 'project_footer'
            , 'template_item_id'
            , 'font_id'
            , 'navigator_id'
            , 'rvs_category_id'
            , 'charset_id'
            , 'project_company'
            , 'project_slogan'
            , 'project_logo'
            , 'project_title'
            , 'project_keyword'
            , 'project_description'
            , 'project_domain'
            , 'check_step'
            , 'effect_site_enter'
            , 'duration_site_enter'
            , 'last_update'
            , 'layout_template_id'
            , 'i_pathway'
            , 'i_mail'
            , 'i_print'
            , 'i_favorite'
            , 'no_slogan'
            , 'no_company_name'
            , 'navigator_name_id'
            );

            $aDataProjectInfo = new stdClass;
            /// Set default object/array wich value null
            foreach ($_allowed_field as $k) {
            	$aDataProjectInfo->{$k} = null;
            }

            /// Selete all project data from table 'rvs_project' and 'rvs_project_info' by project ID : BooM
            $aProjectInfoFromDB = DaoFactory::Project()
            	->findAllProjectsByProjectId($projectId, 'getall');

            $aProjectInfoFromDB = (isset($aProjectInfoFromDB[0]))
            	? $aProjectInfoFromDB[0] : $aProjectInfoFromDB; /// หมายเหตุ ไม่รู้ว่าทำไมจะต้องเรียกใช้ index 0 :: BooM

            if (is_object($aProjectInfoFromDB) === true) {
            	foreach ($aProjectInfoFromDB as $k => $v) {
            		if (in_array($k, $_allowed_field) === true) {
            			$aDataProjectInfo->{$k} = $v;
            		}
            	}
            }
            return $aDataProjectInfo;
		}

		public static function getProjectInfoData($projectId)
		{
			$aProjectInfoData = array();
			$templateItemId = '';
			if (empty($aProjectInfoData) && $projectId) {
			    //fixed PHPMD scan 30/06/2544
                //$arraydata = array();
				/// Selete all project data from table 'rvs_project' and 'rvs_project_info' by project ID : BooM
				$aProjectInfoData = DaoFactory::Project()->findAllProjectsByProjectId($projectId, 'getall');
				/// fix notice if empty array
				if (isset($aProjectInfoData[0]->template_item_id)) {
					$templateItemId = $aProjectInfoData[0]->template_item_id;
				}
				/// Selece template item data by template item id : BooM
				$data = DaoFactory::Template()->findTemplateItemByTemplateItemId($templateItemId, 'getrow');
				if (count($data) > 0) {
					foreach ($data as $prop => $val) {
						$aProjectInfoData[0]->$prop = $val;
					}
				}
				return $aProjectInfoData;
			}
		}
		/**
		 * This is similar to $oMain->getPageStructureData But not the same.
		 * There are more tables and information to query but the concept is the same
		 * ๏ฟฝ๏ฟฝ๏ฟฝอง๏ฟฝาก๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝรถ include file Main.php ๏ฟฝ Common.php ๏ฟฝ๏ฟฝ ๏ฟฝึง๏ฟฝ๏ฟฝอง copy file ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝในน๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ
		 */
		public static function getPageStructureData($projectId, $rvsUsrId, $rvsOwnerId=null, $usePageIdKey=false)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);//     RvsLibs_WysiwygPro::WysiwygPro();
			if (class_exists('Publish_Registry') === true) {
				$oRvsReg = Publish_Registry::singleton();
				$regKey = md5("getPageStructureData({$projectId}, {$rvsUsrId}, {$rvsOwnerId})");
				if (is_null($oRvsReg->extraget($regKey)) === false) {
					return $oRvsReg->extraget($regKey);
				}
			}
			$rvsOwnerId = (is_null($rvsOwnerId) || $rvsOwnerId == 0 )
				? RvsLibs_User::getOwnerId()
				: $rvsOwnerId;
			$aMainPage = RvsLibs_DB::getPageStructureDB($projectId, $rvsUsrId, $mainPage = 1);
			$aSubPage = RvsLibs_DB::getPageStructureDB($projectId, $rvsUsrId, $mainPage = 0);

			//START CompoDB
			if (class_exists('ComponentControl') === false) {
				require_once(SGL_MOD_DIR . '/sitebuilder/classes/ComponentControl.php');
			}
			$oCompo  = ComponentControl::singleton();
			$aDataAllComponentConf = $oCompo->getAllComponentConf();
			//END CompoDB

			$aPageExist = array();
			$aPageStructure = array();
			/* Merge $aMainPage and $aSubPage */
			$i = 1;
			foreach ($aMainPage as $key1 => $value1) {
			//unset componentAnduserFramework
            if (isset($value1->page_name) && $value1->page_name == 'ComponentAndUserFramework') {
            	unset($aMainPage[$key1]);
            	continue;
            }
            /*
				//START fix page_name exists
				if (in_array(RvsLibs_String::trim($value1->page_name), $aPageExist) && $value1->custom_page_name == '') {
					if(RvsLibs_Project::updateCustomPageIfPageNameExist($value1->project_page_id, RvsLibs_String::trim($value1->page_name), $projectId)) {
						$value1->custom_page_name = RvsLibs_String::trim($value1->page_name);
					}
				}
				$aPageExist[] = RvsLibs_String::trim($value1->page_name);
				//END fix page_name exists
			*/
				if (isset($value1->rvs_component_id) && $value1->rvs_component_id != 0 && $value1->rvs_component_id != '') {
					// remove page that contain component but admin disable function
					$aComponentData = RvsLibs_Component::getComponentData($value1->rvs_component_id, $rvsOwnerId);

					if (count($aComponentData) <= 0 || SGL::isError($aComponentData) === true) {
						//มี component id แต่ get componentdata ไม่ได้
						continue;
					}
					if (isset($aComponentData[$value1->rvs_component_id]->component_name)
					&& $aComponentData[$value1->rvs_component_id]->component_name != '') {

						$componentName = $aComponentData[$value1->rvs_component_id]->component_name;
					} else {
						continue;
					}
					if (isset($aComponentData[$value1->rvs_component_id]->component_value)) {
						$componentStatus = $aComponentData[$value1->rvs_component_id]->component_value;
					} else {
						$componentStatus = '0';
					}
					if ($componentStatus != '1') {
						continue;
					}

					if (isset($componentName) && $componentName == 'Newsletter') {
						continue;
					}

					//START CompoDB
					if (isset($aDataAllComponentConf[$componentName])) {
						$value1->component_name = $componentName;
						$value1->component_modules_name = $aDataAllComponentConf[$componentName]['scriptPath'];
						$value1->use_db = (isset($aDataAllComponentConf[$componentName]['use_db'])) ? $aDataAllComponentConf[$componentName]['use_db'] : 0;
					}
					if (isset($aDataAllComponentConf[$componentName]['show_pagestructure']) && !$aDataAllComponentConf[$componentName]['show_pagestructure'] ) {
						continue;
					}
					//END CompoDB
				}
				$value1->idx = $i;
				$value1->parent_idx = 0;
				$parentIdx = $value1->idx;
				$i++;
				if ($usePageIdKey == true) {
					$aPageStructure[$value1->project_page_id] = $value1;
				} else {
					$aPageStructure[] = $value1;
				}

				foreach ($aSubPage as $key2 => $value2) {
                //fix v5 pharadol
				//if ($aMainPage[$key1]->project_page_id ==  $aSubPage[$key2]->parent_project_page_id) {
				/*
						//START fix page_name exists
						//echo $value2->page_name."<br>";
						if (in_array(RvsLibs_String::trim($value2->page_name), $aPageExist) && $value2->custom_page_name == '') {
							if (RvsLibs_Project::updateCustomPageIfPageNameExist($value2->project_page_id, RvsLibs_String::trim($value2->page_name), $projectId)) {
								$value2->custom_page_name = RvsLibs_String::trim($value2->page_name);
							}
						}
						$aPageExist[] = RvsLibs_String::trim($value2->page_name);
						//END fix page_name exists
				*/
						if (isset($value2->rvs_component_id) && $value2->rvs_component_id != 0 && $value2->rvs_component_id != '') {
							// remove page that contain component but admin disable function
							$aComponentData = RvsLibs_Component::getComponentData($value2->rvs_component_id, $rvsOwnerId);
							if (count($aComponentData) <= 0 || SGL::isError($aComponentData) === true) {
								//มี component id แต่ get componentdata ไม่ได้
								continue;
							}
							$componentName = $aComponentData[$value2->rvs_component_id]->component_name;
							if ($aComponentData[$value2->rvs_component_id]->component_value != '1') {
								continue;
							}
							//START CompoDB
							if (isset($aDataAllComponentConf[$componentName])) {
								$value2->component_name = $componentName;
								$value2->component_modules_name = $aDataAllComponentConf[$componentName]['scriptPath'];
								$value2->use_db = (isset($aDataAllComponentConf[$componentName]['use_db'])) ? $aDataAllComponentConf[$componentName]['use_db'] : 0;
							}
							if (isset($aDataAllComponentConf[$componentName]['show_pagestructure']) && !$aDataAllComponentConf[$componentName]['show_pagestructure'] ) {
								continue;
							}
							//END CompoDB
						}
						$value2->idx = $i;
						$i++;
						$value2->parent_idx = $parentIdx;
						if ($usePageIdKey == true) {
							$aPageStructure[$value2->project_page_id] = $value2;
						} else {
							$aPageStructure[] = $value2;
						}
					}
				//}
			}
			if (class_exists('Publish_Registry') === true) {
				$oRvsReg = Publish_Registry::singleton();
				$oRvsReg->extraset($regKey, $aPageStructure);
			}
			$aPageStructure['aPageName'] = $aPageExist;
			return $aPageStructure;
		}

		/**
		 * กรณี gen nav mobile ไม่ต้อง check action ให้ check ตาม config เลย
		 *
		 * @param array $aPageStructure
		 * @param string $mobile
		 */
		public static function getNavigationDetectHideSubMenu($aPageStructure = array(), $mobile = false)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$oPublishReg = Publish_Registry::singleton();
			$action = $oPublishReg->get('action');
			$action = ($mobile == true) ? 1 : $action;

			$projectId  = RvsLibs_Project::getProjectId();
			$fileOptionTable = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $projectId, 'setOptionTableTop.ini'));
			$aShowHideMarkSub = (is_file($fileOptionTable) == true) ? RvsLibs_Config::parse_ini_file($fileOptionTable , true) : false;

			if ($action != 0 && isset($aShowHideMarkSub['showHideMarkSub']['status'])
				&& $aShowHideMarkSub['showHideMarkSub']['status'] == 'hideMask') {
				foreach ($aPageStructure as $pageId => $v) {
					if (isset($v->level1) && count($v->level1)) {
						$aPageStructure[$pageId]->level1 = array();
					}
				}
			}
			return $aPageStructure;
		}

		/**
		rvsitebuilder v5
		 * get aMainPage and aSubPage
		 * build new array to level1 and level2
		 *
		 * @param $input
		 * @return unknown_type
		 */
		public static function getPageStructureLevel2($aPageStructure)
		{
			$projectId = SGL_Session::get('rvs_project_id');
			$usrId = RvsLibs_User::getUserId();
			$aMainPage = DaoFactory::ProjectPage()->findProjectPageDataByProjectIdAndUsrId($projectId, $usrId, true, 'getassoc');
			$aSubPage = DaoFactory::ProjectPage()->findProjectPageDataByProjectIdAndUsrId($projectId, $usrId, false, 'getassoc');

			//gen level2 the first
			foreach ($aSubPage as $k => $v) {

				if (isset($aPageStructure[$k])) {
				    $aSubPage[$k] = (object)(array_merge((array)$v,(array)$aPageStructure[$k]));
				}
				//fix array sub page lavel ,1,2,3 v5 pharadol
				$pid = $v->parent_project_page_id;
				if ($pid && isset($aSubPage[$pid])) {
					if (isset($aPageStructure[$k])) {
						$aSubPage[$pid]->level2[$k] = (object)(array_merge((array)$v,(array)$aPageStructure[$k]));
					}
				}
			}

			//gen level1 the second
			foreach ($aSubPage as $k => $v) {

				if (isset($aPageStructure[$k])) {
					$aSubPage[$k] = (object)(array_merge((array)$v,(array)$aPageStructure[$k]));
				}

				$pid = $v->parent_project_page_id;
				if ($pid && isset($aMainPage[$pid])) {
					$aMainPage[$pid]->level1[$k] = $v;
				}
			}

			//merge MainPage level0
			require_once SGL_MOD_DIR .'/sitebuilder/classes/ComponentControl.php';
			$oCompo  = ComponentControl::singleton();
			$aDefaultComponent = $oCompo->getAllComponentConf();
			$ownerId = RvsLibs_User::getOwnerId();
			//get All component by owner
			$res = DaoFactory::Component()->fineAllComponentByComponentID(null, $ownerId);
			//merge MainPage level0
			foreach ($aMainPage as $k => $v) {
				if (isset($aPageStructure[$k])) {
					$aMainPage[$k] = (object)(array_merge((array)$v,(array)$aPageStructure[$k]));
				}
				if ($v->rvs_component_id && isset($res[$v->rvs_component_id])) {
					$component_name = $res[$v->rvs_component_id]->component_name;
					if (RvsLibs_Util::validateTrue($aDefaultComponent[$component_name]['show_pagestructure']) === false) {
						unset($aMainPage[$k]);
					}
					if (RvsLibs_Component::isNonePageContent($component_name, $aDefaultComponent)) {
						//unset component none page content(Newsletter)
						unset($aMainPage[$k]);
					}

				}
			}
			return $aMainPage;
		}
		/**
		 * Enter description here...
		 *
		 * @param unknown_type $projectId
		 * @return unknown
		 */
		public static function getInternalPageDataByProjectId($projectId)
		{
			/// Find internel page data by project id :: BooM
			return DaoFactory::InternalPage()
				->findInternalPageDataByProjectId($projectId, 'getassoc');
		}

		public static function getProjectDBCharset($projectId)
		{
			if ($projectId) {
				$res = DaoFactory::Charset()->findCharsetLangByProjectId($projectId, 'getrow');
				$xmlCharset = (isset($res['xml_lang']) && isset($res['charset_value']))
											? $res['xml_lang'] . '-' . $res['charset_value']
											: false;
              // echo"test::". RvsLibs_DB::isDatabaseUtf8();
				$lang = (RvsLibs_DB::isDatabaseUtf8() === true)
								? $res['xml_lang'] . '-utf-8'
								: $xmlCharset;

				$projectDbCharset = (isset($GLOBALS['_SGL']['LANGUAGE'][$lang][6])) ? $GLOBALS['_SGL']['LANGUAGE'][$lang][6] : false;
				return $projectDbCharset;
			} else {
				return SGL::raiseError(
				RvsLibs_String::translate(
                    'donot have project Id'
                    )
                    );
			}
		}

		public static function getProjectCheckStep($projectId)
		{
			$oProjectData = RvsLibs_Project::getDataProjectInfoByProjectId($projectId);
			return $oProjectData->check_step;
		}

		/**
		 * get all page id
		 * main_page + sub_page + internal page by project_id
		 * @param unknown_type $projectId
		 * @return multitype:
		 */
		public static function getAllPageIdByProjectId($projectId = null)
		{
            SGL::logMessage("project_id:" . $projectId, PEAR_LOG_DEBUG);
			$aProjectPageId = array();
			if (!is_null($projectId)) {
				/// Get $aProjectPageId From rvs_project_layout_page by project_id
				$aProjectPageId = DaoFactory::ProjectLayoutPage()->findProjectLayoutPage($projectId, 'getassoc');
				/// Get $aProjectPageId From internal page
				$aInternalPage = DaoFactory::InternalPage()->findInternalProjectPageIdByProjectId($projectId, 'getassoc', $aResultFields = array('project_page_id'));
				$aProjectPageId = array_merge($aProjectPageId, $aInternalPage);
			}
			return $aProjectPageId;
		}

	//fix v5 pharadol
		public static function getAllPageStructureData($projectId, $usrId, $internalPage = 0, $showSubpage = 1, $getAll = 'getall')
		{
			$resInternalPage = array();
			if (($internalPage == 1) || ($internalPage == 2)) {
				/// Find internel page data by project id :: BooM
				$resInternalPage = DaoFactory::InternalPage()->findInternalPageDataByProjectId($projectId, 'getassoc');
				if ($internalPage == 2) {
					return $resInternalPage;
				}
				//$aPageStructure = array_merge($aPageStructure, $resInternalPage);
				//$aPageStructure = array_merge((array)$aPageStructure, (array)$resInternalPage);
			}
			$aPageStructure = RvsLibs_Project::getPageStructureDataWithOutInternalPage($projectId, $usrId, $showSubpage, 'getassoc');
			if (count($resInternalPage)) {
				$aPageStructure = array_merge((array)$aPageStructure, (array)$resInternalPage);
			}

			//find layout_template_user_id
			//find layout_template_name
			foreach ($aPageStructure as $pageId => $oValue) {
				$res = DaoFactory::ProjectLayoutPage()->findLayoutTemplateUser($projectId ,$pageId,'getrow');
				$aPageStructure[$pageId]->layout_template_user_id = (isset($res['layout_template_user_id'])) ? $res['layout_template_user_id'] : '';
				$aPageStructure[$pageId]->layout_template_name = (isset($res['layout_template_name'])) ? $res['layout_template_name'] : '';
			}

			return $aPageStructure;

		}

		public static function getPageStructureDataWithOutInternalPage($projectId, $usrId, $showSubpage = 1, $fetchMode = 'getall')
		{
			$aPageStructure = array();
			$aMainPage = array();
			$aSubPage = array();
			/* get Main Page Data */
			/// Fix Dao :: BooM
			SGL::logMessage('findProjectPageDataByProjectIdAndUsrId', PEAR_LOG_DEBUG);
			$aMainPage = DaoFactory::ProjectPage()->findProjectPageDataByProjectIdAndUsrId($projectId, $usrId, true, $fetchMode);
			/* get Sub Page Data */
			$aSubPage = DaoFactory::ProjectPage()->findProjectPageDataByProjectIdAndUsrId($projectId, $usrId, false, $fetchMode);

			if ($showSubpage) {
				$aMainPageValues = RvsLibs_Project::_MainPageValues($aMainPage);
				$aSubPageValues = RvsLibs_Project::_SubPageValues($aSubPage);
			} else {
				$aMainPageValues = $aMainPage;
				$aSubPageValues = $aSubPage;
			}

            //fix subpage v5 pharadol
			$aSub = array();
			foreach ($aSubPageValues as $k => $v) {
				$aSub[$v->project_page_id] = $v->project_page_id;
			}

			/* Merge $aMainPage and $aSubPage */
			foreach ($aMainPageValues as $key1=>$value1) {
				//main page
				if (in_array($value1, $aPageStructure)) {
					continue;
				}

				$mainOutSuggesId = RvsLibs_Project::getOutsuggestionIdByProjectPageId($value1->project_page_id);
				$value1->out_suggestion_id = ($mainOutSuggesId) ? $mainOutSuggesId : "";
				$value1->aMetacontent = DaoFactory::ProjectPage()->findCustomMetatagByProjectPageIdAndUsrId($value1->project_page_id, $usrId, 'getall');
				$aPageStructure[$value1->project_page_id] = $value1;

				foreach ($aSubPageValues as $key2=>$value2) {
					if (isset($value2->project_page_id) === false) {
						continue;
					}
					$pid = $value2->project_page_id;
					$parentId = $value2->parent_project_page_id;
					$aMainPageValues[$key1]->isMasterPage = false;


					if (($aMainPageValues[$key1]->project_page_id == $aSubPageValues[$key2]->parent_project_page_id)) {
						$aMainPageValues[$key1]->isMasterPage = true;
						//sub page level 1 , level 2 v5 pharadol
						if (in_array($value2, $aPageStructure)) {
							continue;
						}
						$subOutSuggesId = RvsLibs_Project::getOutsuggestionIdByProjectPageId($pid);
						$value2->out_suggestion_id = ($subOutSuggesId) ? $subOutSuggesId : "";
						$aPageStructure[$pid] = $value2;
					} elseif (in_array($parentId, $aSub)) {
						$aSubPageValues[$parentId]->isMasterPage = true;
						//sub page level 2 v5 pharadol
						if (in_array($value2, $aPageStructure)) {
							continue;
						}
						$subOutSuggesId = RvsLibs_Project::getOutsuggestionIdByProjectPageId($pid);
						$value2->out_suggestion_id = ($subOutSuggesId) ? $subOutSuggesId : "";
						$aPageStructure[$pid] = $value2;
					}
				}
			}
			if (isset($aPageStructure)) {
				return $aPageStructure;
			}
		}

		public static function getOutsuggestionIdByProjectPageId($projectPageId=null)
		{
            $oMgr = SGL_Manager::singleton();
			$oComRegis = RvsLibs_ComponentRegistry::singleton();
            $OutSuggetstion = $oComRegis->getOne($projectPageId);
            if (count($OutSuggetstion) <= 1) {
            	if (isset($oMgr->conf['table']['rvs_project_page_out_seggestion'])
            	&& isset($oMgr->conf['table']['rvs_out_seggestion_layout_template'])) {
            		/// Find out suggestion id by project page id :: BooM
            		$OutSuggetstion = DaoFactory::OutSuggestion()->findOutSuggestionIdByProjectPageId($projectPageId, 'getone');
            		$oComRegis->setOne($OutSuggetstion, $projectPageId);
            	}
            }
            	return $OutSuggetstion;
		}

		protected static function _MainPageValues($aMainPage)
		{
			foreach ($aMainPage as $mKey=>$mValue) {
				$suggesTionID = (isset($aMainPage[$mKey]->out_suggestion_id)) ? '|' . $aMainPage[$mKey]->out_suggestion_id : '';
				if ($aMainPage[$mKey]->rvs_component_id) {
					$oCompanent = RvsLibs_Component::getComponentName($aMainPage[$mKey]->rvs_component_id);
					if (count($oCompanent)) {
						if ($oCompanent->component_name == 'Tryout') {
							$aMainPage[$mKey]->value = $aMainPage[$mKey]->project_page_id . '@@' . $oCompanent->component_name . $suggesTionID . '^' . $aMainPage[$mKey]->page_name . '^0'. $aMainPage[$mKey]->page_type;
						} else {
							$aMainPage[$mKey]->value = $aMainPage[$mKey]->project_page_id . '@@' . $oCompanent->component_name . $suggesTionID . '^' . $aMainPage[$mKey]->page_name . '^0';
						}
						$aMainPage[$mKey]->page_name = $aMainPage[$mKey]->page_name;
					} else {
						$aMainPage[$mKey]->value = $aMainPage[$mKey]->project_page_id . $suggesTionID . '^' . $aMainPage[$mKey]->page_name . '^0';
					}
				} else {
					$aMainPage[$mKey]->value = $aMainPage[$mKey]->project_page_id . $suggesTionID . '^' . $aMainPage[$mKey]->page_name . '^0';
				}
			}
			return $aMainPage;
		}

		protected static function _SubPageValues($aSubPage)
		{
			foreach ($aSubPage as $sKey=>$sValue) {
				if ($aSubPage[$sKey]->rvs_component_id) {
					$companent[$sKey] = RvsLibs_Component::getComponentName($aSubPage[$sKey]->rvs_component_id);

					if ($companent[$sKey]->component_name == 'Tryout') {
						$aSubPage[$sKey]->value = $aSubPage[$sKey]->project_page_id . '@@' . $companent[$sKey]->component_name . '^' . $aSubPage[$sKey]->page_name . '^1'. $aSubPage[$sKey]->page_type;
					} else {
						$aSubPage[$sKey]->value = $aSubPage[$sKey]->project_page_id . '@@' . $companent[$sKey]->component_name . '^' . $aSubPage[$sKey]->page_name . '^1';
					}
					$aSubPage[$sKey]->page_name = $aSubPage[$sKey]->page_name;
				} else {
					$aSubPage[$sKey]->value = $aSubPage[$sKey]->project_page_id . '^' . $aSubPage[$sKey]->page_name . '^1';
				}
				$aSubPage[$sKey]->page_name = '>>' . $aSubPage[$sKey]->page_name;
			}
			return $aSubPage;
		}

		public static function getRvsLayoutTag($pageBody)
		{
			// Find <table >
			$regExpTable = '/<\s*table.*?>/i';
			preg_match_all($regExpTable, $pageBody, $aResultMatchTable );
			$aTableTag = $aResultMatchTable[0];
			// Find <table> with ' id=rv_template_layout'
			foreach ($aTableTag as $key=>$value) {
				$regExpId = '/.*?id\s*=\s*["|\']rv_template_layout["|\'].*?>/i';
				preg_match_all($regExpId, $value, $resultMatchId);
				if (count($resultMatchId[0]) == 0) {
					unset($aTableTag[$key]);
				}
			}
			// Find <table> Fixed Width
			foreach ($aTableTag as $key=>$value) {
				$regExpFixedWidth = '/width\s*=\s*["|\'][0-9]{1,}["|\']/i';
				preg_match_all($regExpFixedWidth, $value, $resultMatchFixedWidth);
				if (count($resultMatchFixedWidth[0]) == 0) {
					unset($aTableTag[$key]);
				}
			}
			return $aTableTag;
		}

		public static function getProjectLayoutId($projectInfoId)
		{
			/// Find layout template id by project info id :: BooM
			$res = DaoFactory::LayoutTemplate()->findLayoutTemplateIdByProjectInfoId($projectInfoId , 'getrow');
			return isset($res['layout_template_id']) ? $res['layout_template_id'] : null;
		}

		public static function getLayoutData($input, $mode = 'insert')
		{
			require_once RvsLibs_File::buildPath(
			array(SGL_MOD_DIR, 'sitebuilder', 'classes', 'Common.php')
			);
			// Set Default Layout Template Id
			if (!$input->layout_template_id) {
				$input->layout_template_id = 1;
			}
			/// Find layout template header and layout template data by layout template id :: BooM
			$res = DaoFactory::LayoutTemplate()->findLayoutTemplateHeaderAndDataByLayoutTemplateId($input->layout_template_id , 'getrow');
			$layoutHTML['head'] = $data = isset($res['layout_template_head']) ? $res['layout_template_head']: '';
			$resLayout['layout_template_data'] = isset($res['layout_template_data']) ? $res['layout_template_data'] : '';
			// Get Path Layout  index.htm
			$aProjectInfoData = RvsLibs_Project::getProjectInfoData($input->rvs_project_id);
			$aTemplateData = RvsLibs_Template::getTemplatesData($input->rvs_project_id, true);
			$aProjectInfoData[0]->template_item_folder = (isset($aProjectInfoData[0]->template_item_folder) && $aProjectInfoData[0]->template_item_folder)
			                                             ? $aProjectInfoData[0]->template_item_folder
			                                             : null;
			$templateItemFolder = $aProjectInfoData[0]->template_item_folder;
			$aTemplateData->templatePath = (isset($aTemplateData->templatePath) && $aTemplateData->templatePath)
			                                     ? $aTemplateData->templatePath
			                                     : null;
            $fileTemplateIndex = $aTemplateData->templatePath . '/' . $templateItemFolder . '/index.htm';

			// Get Width Option
			if ($mode == 'insert') {
				if ($input->layout_width == 1 ) {
					$widthOption = 'CustomSize';
				} else {
					$widthOption = 'AutoSize';
				}
			} elseif ($mode == 'autoLayout') {
				$fileLayoutWidth = RVS_USER_HOME . '/.rvsitebuilder/rvsbTemplateLayoutWidth.txt';
				if (file_exists($fileLayoutWidth)) {
					$widthOption = 'CustomSize';
				} else {
					$widthOption = 'AutoSize';
				}
			}
			// Get Replace Width
			if ($widthOption == 'CustomSize') {
				$replaceWidth = RvsLibs_Template::GetLayoutReplaceWidth($fileTemplateIndex);
			} else {
				$replaceWidth = '100%';
			}

			// Get Relative Publish Image Url :: For WYSIWYG do not clean image path
			$relativePubImgUrl = RvsLibs_String::preg_replace("#^(.*)\:208[2|3]\/3rdparty#", "/3rdparty" ,   PUBLIC_IMG_URL);
			$relativePubImgUrl = RvsLibs_String::preg_replace("#^(.*)\/\/cpanel\.(.*)\/3rdparty#", "/3rdparty" ,   PUBLIC_IMG_URL);

			// Replace layout template id fodler
			require_once SGL_MOD_DIR . '/sitebuilder/classes/LayoutInsertDataMgr.php';
			$resLayout['layout_template_data'] = LayoutInsertDataMgr::replaceHeadData($resLayout['layout_template_data'], $input->layout_template_id);
			$resLayout['layout_template_data'] = LayoutInsertDataMgr::replaceLayoutData($resLayout['layout_template_data'], $input->layout_template_id);

			// Replace Layout Data
			$data = $resLayout['layout_template_data'];
			$data = RvsLibs_String::str_replace("\"images/", "\"" . $relativePubImgUrl . "/", $data);
			$data = RvsLibs_String::str_replace('[IMG_PATH]', PUBLIC_IMG_URL, $data);
			$data = RvsLibs_String::str_replace('{rvs_width}', $replaceWidth , $data);
			$data = RvsLibs_String::str_replace("url(images/", "url(" . $relativePubImgUrl . "/", $data);
			$data = RvsLibs_String::removeCssFullURLWithPort($data);

			$layoutHTML['body'] = $data;
			// Replace Layout Head
			$headData = $layoutHTML['head'];
			$headData = RvsLibs_String::str_replace("url(images/", "url(" . $relativePubImgUrl . "/", $headData);
			$layoutHTML['head'] = $headData;
			return  $layoutHTML;
		}

		public static function getColorGroupID($colorId)
		{
			if (isset($GLOBALS['_SGL']['rvsCache']['Main']['getColorGroupID']) === true &&  $GLOBALS['_SGL']['rvsCache']['Main']['getColorGroupID']['colorId'] == $colorId) {
				$arraydata = $GLOBALS['_SGL']['rvsCache']['Main']['getColorGroupID']['arraydata'];
				return $arraydata;
			} else {
				$arraydata = array();
				/// Select color group data by color id :: BooM
				$arraydata = DaoFactory::Color()->findColorGroupByColorId($colorId, 'getall');
				if (SGL::isError($arraydata)) {
					SGL_Error::pop();
					$arraydata = array();
				} elseif (count($arraydata)) {
					$GLOBALS['_SGL']['rvsCache']['Main']['getColorGroupID']['colorId'] = $colorId;
					$GLOBALS['_SGL']['rvsCache']['Main']['getColorGroupID']['arraydata'] = $arraydata;
				}
				return $arraydata;
			}
		}

		/**
		 * get category_name by id
		 *
		 * @param string $rvsCategoryId
		 * @return string category_name
		 */
		public static function getCategoryNameById($rvsCategoryId)
		{
			/// Find category name by category id :: BooM
			$res = DaoFactory::Category()->findCategoryNameByCategoryId($rvsCategoryId, 'getrowobj');
			return isset($res->category_name) ? $res->category_name : null;
		}

		/**
		 * Get online form ID in page data
		 *
		 * @package rvsitebuilder
		 * @author parinya
		 *
		 * @param string $pagedata
		 */
		public static function getOnlineFormID($pageData = '')
		{
			$aOnlineFormID = array();
			if (isset($pageData)) {
				if (preg_match_all('/id*=*["|\']onlineform_(.*?)[\'|"]/i', $pageData, $match)) {
					array_push($aOnlineFormID,$match[1][0]);
				}
			}
			return $aOnlineFormID;
		}

		/* �ѧ���� �ʴ� Category */
		public static function listCategory($categoryId)
		{
			/// Select all category data :: BooM
			$aCategory = DaoFactory::Category()->findAllCategoryData('getvalue');
			$aCustomCategory = array();
			//case tryout
			$aCustomCategory = DaoFactory::Category()->findCustomCategoryOrderByCategoryId('getall');
			if ($aCategory) {
				foreach ($aCategory as $key=>$value) {
					$globalTran = (isset($GLOBALS['_SGL']['TRANSLATION'][$value])) ? $GLOBALS['_SGL']['TRANSLATION'][$value] : $value;
					if (isset($globalTran) && !empty($globalTran)) {
						$aCategory[$key] = RvsLibs_String::translate($value);
					}
				}
				$userId = RvsLibs_User::getOwnerId();
				foreach ($aCustomCategory as $key) {
					if ($key->custom_category_user == $userId) {
						$aCustom[$key->custom_category_id] = $key->custom_category_name;
						$aCategory = RvsLibs_Project::arrayMerge($aCategory, $aCustom);
					} elseif ($key->custom_category_user == $userId) {
						$aCustom[$key->custom_category_id] = $key->custom_category_name;
						$aCategory = RvsLibs_Project::arrayMerge($aCategory, $aCustom);
					}
				}
				// optimize :nipaporn
				return SGL_Output::generateSelect($aCategory, $categoryId);
			}
		}

	/**
     * ยังไม่มี category นี้
    [1] => Art and Gallery
    [2] => Beauty & Fashion
    [3] => Book Stores
    [4] => Computer and Technology
    [5] => Family
    [6] => Restaurant and Bar
    [7] => Travel and Leisure
    [8] => Gifts and Collectibles
    [9] => Sports & Recreation
    [10] => Health and Medical
    [11] => Home and Garden
    [12] => Hotels
    [13] => Internet Services
    [14] => Jobs and Career
    [15] => Musicians
    [16] => Pets
    [17] => Business
    [18] => Industrial & Maintenance
    [19] => Hosting
    [21] => Blog
    [22] => Plain Template

    v6
    [24] => Photography
    [25] => Technology & Electronics
    [26] => Weddings
    [27] => Restaurants
    [28] => Travel
    [29] => Gift Shops
    [30] => Health
    [31] => Real Estate
    [32] => Online Service
    [33] => Portfolios
    [34] => Pets & Animals
    [35] => IT & Apps
     *
     * @param array $aCategory
     * @return unknown
     */
    public static function unsetCategory($aCategory = array())
    {
    	$isV6 = SGL_Output::isV6Session();
    	if ($isV6 == true) {
    		//v6 add default All Categories
    		$aCategory[0] = 'All Categories';
    	}

    	$aAllow = array(0,24,33,21,26,2,29,3,17,25,35,32,30,9,28,31,12,18,27,15,34);
		foreach ( $aCategory as $catId => $cateName ) {
			//v6 กำหนดมาเอาไรบ้าง
			if ($isV6 == true && in_array($catId, $aAllow) == false) {
				unset($aCategory[$catId]);
			}
			//v5 เอาแค่ category 1-22 นอกนั้นตัดทิ้ง
			if ($isV6 == false && $catId >= 23) {
				unset($aCategory[$catId]);
			}
		}
		/*
		 *
    	echo '<pre>';
    	ksort($aCategory);
    	print_r($aCategory); exit;
		 */
    	return $aCategory;
    }

		public static function arrayMerge($aDefult=array(), $aMerge=array())
		{
			if (count($aDefult) > 0  && count($aMerge) > 0) {
				foreach($aMerge as $k => $v) {
					$aDefult[$k] = $v;
				}
			}
			return $aDefult;
		}
		/**
		 * get ProjectPage is component_id missing in rvs_component, rvs_component_config by project_id, rvs_usr_id, rvs_owner_usr_id
		 * sql support MySQL 5 only
		 * SELECT
		 pp.project_page_id
		 , pp.page_name
		 , pp.rvs_usr_id
		 , pp.rvs_component_id
		 , pp.form_template_id
		 , pp.page_data
		 FROM
		 rvs_project_layout_page as lp
		 ,rvs_project_page as pp
		 WHERE
		 lp.project_page_id = pp.project_page_id
		 AND lp.project_id = '$projectId'
		 AND pp.rvs_usr_id = '$rvsUsrId'
		 AND pp.rvs_component_id != '0'
		 AND pp.rvs_component_id
		 NOT IN
		 (SELECT cp.rvs_component_id
		 FROM rvs_component_config as cc, rvs_component as cp
		 WHERE cc.rvs_component_id = cp.rvs_component_id
		 AND cp.rvs_owner_usr_id = '$ownerUsrId')
		 *
		 * @param string $projectId
		 * @param string $rvsUsrId
		 * @param string $ownerUsrId
		 * @return array object $aProjectPage
		 */
		public static function getProjectPageIsComponentIdMissing($projectId, $rvsUsrId, $ownerUsrId)
		{
			SGL::logMessage( sprintf("*** projectId: %s rvsUsrId: %s ownerUsrId: %s", $projectId, $rvsUsrId, $ownerUsrId), PEAR_LOG_DEBUG);
			$aInternalPage = RvsLibs_Project::getAllPageStructureData($projectId, $rvsUsrId, $internalPage = 2);
			$aComponentIdMissing = array();
			$aPage = RvsLibs_Project::getProjectPageIsComponent($projectId, $rvsUsrId);

			$aAllComponentId = RvsLibs_Component::getAllComponentData($ownerUsrId);
            //mainPage
			if (count($aPage)) {
				foreach ($aPage as $key => $val) {
					if ($val->rvs_component_id != '' && $val->rvs_component_id != '0'
                       && !isset($aAllComponentId[$val->rvs_component_id])) {
						$aComponentIdMissing[$key] = $val;
					}
				}
			}
			//internalPage
			if (count($aInternalPage)) {
				foreach ($aInternalPage as $key => $val) {
					if ($val->rvs_component_id != '' && $val->rvs_component_id != '0'
					   && !isset($aAllComponentId[$val->rvs_component_id])) {
						$aComponentIdMissing[$key] = $val;
					}
				}
			}

			if (count($aComponentIdMissing)) {
				return $aComponentIdMissing;
			}
		}

		/**
		 * get ProjectPage is component by project_id, rvs_usr_id
		 *
		 * @param string $projectId
		 * @param string $rvsUsrId
		 * @return array object $aProjectPage
		 */
		public static function getProjectPageIsComponent($projectId, $rvsUsrId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aProjectPage = DaoFactory::ProjectLayoutPage()->findProjectPageIsComponentByUsrIdAndProjectId($rvsUsrId, $projectId,  'getassoc');
			if (count($aProjectPage)) {
				return $aProjectPage;
			}
		}

		public static function getProjectInfo($projectId, $rvsUsrId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aProjectInfoData = DaoFactory::Project()->findProjectInfoDataByProjectIdAndUsrId($projectId, $rvsUsrId, 'getrowobj');
			if (SGL::isError($aProjectInfoData) === true) {
			    return $aProjectInfoData;
			}  else {
			    $res = RvsLibs_Project::getProjectInfoData($projectId);
			    if (SGL::isError($res) === true) {
			        SGL_Error::pop();
			    }
			    $aProjectInfoData->navigator_id = (isset($res[0]->navigator_id))
			        ? $res[0]->navigator_id
			        : isset($aProjectInfoData->navigator_id)
			            ? $aProjectInfoData->navigator_id
			            : '';
			}
			return $aProjectInfoData;
		}

		public static function getCustomMetatagByProjectPage($projectPageId, $usrId)
		{
			//query custom metatag
			$aCustomMetatag = DaoFactory::ProjectPage()->findCustomMetatagByProjectPageIdAndUsrId($projectPageId, $usrId, 'getassoc');
			return count($aCustomMetatag) ? $aCustomMetatag : array();
		}

		public static function getCustomMetatagByProjectInfo($projectInfoId, $usrId)
		{
			$aCustomMetatag = DaoFactory::ProjectPage()->findCustomMetatagByProjectInfoIdAndUsrId($projectInfoId, $usrId, 'getassoc');
			return count($aCustomMetatag) ? $aCustomMetatag : array();
		}

		public static function getProjectPageData($projectId, $rvsUsrId, $projectPageId = null)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			if (is_null($projectPageId)) {
				$aPageData = DaoFactory::ProjectPage()->findProjectPageAndProjectLayoutPageByProjectIdProjectPageIdAndUsrIdOrderByPriority($projectId,  $rvsUsrId, 'getall');
			} else {
				$aPageData = DaoFactory::ProjectPage()->findProjectPageAndProjectLayoutPageByProjectIdProjectPageIdAndUsrIdOrderByPriority($projectId,  $rvsUsrId, 'getall', $projectPageId);
			}
			return $aPageData;

		}

		//project
		public static function getDefProjectPageId($projectId, $rvsUsrId, $projectPageId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aDefProjectPageId = DaoFactory::ProjectPage()->findProjectPageAndProjectLayoutPageByProjectIdProjectPageIdAndUsrId($projectId,  $rvsUsrId, 'getrowobj', $projectPageId);
			if (isset($aDefProjectPageId)) {
				return $aDefProjectPageId;
			}
		}

		/**
		 * get project_page_id ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝหน๏ฟฝ๏ฟฝ home ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝีค๏ฟฝ๏ฟฝ priority ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝยท๏ฟฝ๏ฟฝ๏ฟฝุด
		 *
		 * @param string $projectId
		 * @return string $project_page_id
		 */
		public static function getLessPriority($projectId, $usrId = null)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$usrId = (is_null($usrId)) ? RvsLibs_User::getUserId() : $usrId;
			$HomePageID = DaoFactory::ProjectPage()->findHomePageByProjectId($projectId, 'getone');
			if (SGL::isError($HomePageID)) {
				SGL_Error::pop();
				$HomePageID = '';
			}
			if (empty($HomePageID)) {
				$aLessPriority = DaoFactory::ProjectPage()->findProjectPagePriorityByProjectId($projectId, $usrId, 'getrowobj');
				$HomePageID = (isset($aLessPriority->project_page_id))
					? $aLessPriority->project_page_id
					: '';
			}
			return $HomePageID;
		}

		//project
		public static function getFontData($fontId=null)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aFontData = RvsLibs_Util::getFonts();
			if (!is_null($fontId)) {
				if (isset($aFontData[$fontId])) {
					return $aFontData[$fontId];
				} else {
					$fileFontIni =  RvsLibs_File::buildPath(
							array(RVS_USER_HOME, '.rvsitebuilder', 'customfont', 'fontname.ini.php')
					);
					if (is_file($fileFontIni)) {
						require_once $fileFontIni;
					}
					if (isset($aFontCustom[$fontId])) {
						return $aFontCustom[$fontId];
					}
				}
			} else {
				$fileFontIni =  RvsLibs_File::buildPath(
						array(RVS_USER_HOME, '.rvsitebuilder', 'customfont', 'fontname.ini.php')
				);
				if (is_file($fileFontIni)) {
					require_once $fileFontIni;
				}
				if (isset($aFontCustom) && count($aFontCustom)) {
					foreach ($aFontCustom as $key => $val) {
						$aFontData[$key] = $val;
					}
				}
			}
			return $aFontData;
		}

    public static function getCustomCssPath($projectId, $templateItemFolder)
    {
    	//get custom path for new project and edit old poject (version 5.2+)
    	return RvsLibs_File::buildPath(array(
    		REAL_PROJECT_PATH, $projectId, 'customcss', $templateItemFolder
    	));
    }

    public static function getCustomCssUrl($projectId, $templateItemFolder)
    {
    	//get custom path for new project and edit old poject (version 5.2+)
    	return RvsLibs_File::buildPath(array(
    			PROJECT_URL, $projectId, 'customcss', $templateItemFolder
    	));
    }

    /**
     * find jotform id case email setting not set
     *
     * @param string $projectId
     * @param string $usrId
     * @return unknown[index] = jotform id (array)
     */
    public static function getInvalidJotformEmailSetting($projectId, $usrId)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$aErrorForm = array();
    	$aPageData = RvsLibs_Project::getProjectPageData($projectId, $usrId);
    	foreach ($aPageData as $key=>$value) {
    		if ($aPageData[$key]->page_data != "") {
    			$isJotformInPageData = (RvsLibs_String::preg_match_all("/id\s*=\s*\"DragAndDropForm_(.*?)\"/", $aPageData[$key]->page_data, $aPageOnlineformID)) ? true : false;
    			$aFormId = ($isJotformInPageData == true) ? $aPageOnlineformID[1] : array();

    			foreach ($aFormId as $key2 => $value2) {
    				$formId = $aFormId[$key2];

    				$chkEmailForm = false;
					$aJotFormProp = DaoFactory::Jotform()->findJotFormQuestionPropertiesByFormIdAndProp( $formId, 'email_addr', 'getrowobj' );
					if (trim($aJotFormProp->value) == 'admin@yourdomain.com' || $aJotFormProp->value == '') {
						$aWidget = DaoFactory::widget()->findWidgetByWidgetId($formId , 'getrowobj');
						$aErrorForm[$formId] = (isset($aWidget->widget_name) && $aWidget->widget_name)
												? $aWidget->widget_name
												: 'Contact Us';
					}
				}
    		}
    	}
    	return $aErrorForm;
    }


	}
}

if (class_exists('RvsLibs_Project_Validate') === false) {
	class RvsLibs_Project_Validate extends RvsLibs_Project_Get
	{
		public static function isEnableBlockLogin($projectId)
		{
			$fileBlogLoginConf = RvsLibs_File::buildPath(array(
				REAL_PROJECT_PATH,
				$projectId,
				'enableBlockLogin.txt'
			));
			if (is_file($fileBlogLoginConf)) {
				return true;
			}

			//if responsive template enable block login
			//ใช้เหมือน normal
            /*
			$aTemplate = RvsLibs_Template::getTemplatesData($projectId, true);
			$templateItemFolder = $aTemplate->templatePath . '/' . $aTemplate->template_item_folder;
			if (RvsLibs_Template::isResponsiveTemplate($templateItemFolder) === true) {
				return true;
			}*/
			return false;
		}
		/**
		 * Validate "Project Id" of "User Id"
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param string $rvsUsrId
		 * @param string $projectId
		 *
		 * @return bool ; True if "user id" is owner of "project id", false if "user id" isnot owner of "project id"
		 */
		public static function isProjectIdOfUsersId($rvsUsrId, $projectId)
		{
			$res = DaoFactory::Project()->findProjectsByUserIdAndProjectId($rvsUsrId, $projectId, 'getrow');
			return (count($res) <= 0) ? false : true;
		}

		/**
		 * check Sql command not Security
		 *
		 * @param $string $path = REAL_PROJECT_PATH . '/rvsproject/rvsDbBackup.sql
		 *      or  commond line : INSER, CREATE TABLE, DROP, ALTER
		 * @param string $value = 'file'  for part
		 *              or $value = 'commond'
		 * @return bool
		 *  if have error return raise error
		 */
		public static function isSqlCommandNotSecurity($path, $value = null)
		{
			//check $value = file
			if(is_null($value) ===false
			&& $value == 'file') {
				if (is_file($path)) {
					$aLine =RvsLibs_File::file($path);

					if(SGL::isError($aLine) === true) {
						return SGL::raiseError(
						RvsLibs_String::translate(
                             'cannot open file. Because %MESSAGE'
                             , 'vprintf'
                             , array('MESSAGE' => $aLine->getMessage()
                             )
                             )
                             );
					}
				}

				foreach ($aLine as $line) {
					if (!RvsLibs_String::preg_match("/^(REPLACE|INSERT) INTO/i", $line)) {
						return true;
					}
				}
			} else {
				if (!RvsLibs_String::preg_match("/^(REPLACE|INSERT) INTO/i", $path)) {
					return true;
				}
			}
			return false;
		}

		public static function isUpdateDBCharsetToUTF8($projectId)
		{
			$bool = false;
			$aRes = DaoFactory::Project()->findProjectByProjectId($projectId, 'getassoc');
			if (SGL::isError($aRes) === true) {
				return SGL::raiseError(
				RvsLibs_String::translate(
                    'Can not find project data because %ERROR'
                    , 'vprinf'
                    , array('ERROR' => $aRes->getMessage())
                    )
                    );
			}
			if (isset($aRes[$projectId]->utf8format) && $aRes[$projectId]->utf8format == '1') {
				$bool = true;
			}
			return $bool;
		}

		/**
		 * Validate project missing or valid project id
		 *
		 * @param String $projectId
		 * @param String $rvsUsrId
		 * @return TRUE on valid project or PEAR error on invalid project
		 */
		public static function validateProjectId($projectId, $rvsUsrId = null)
		{
			SGL::logMessage("Session rvs_project_id=" . $projectId, PEAR_LOG_DEBUG);
			if (is_null($rvsUsrId) === true) {
				$rvsUsrId  = RvsLibs_User::getUserId();
			}
			/// Select all prohect data by user id and project name :: BooM
			$res = DaoFactory::Project()->findProjectsByUserIdAndProjectId($rvsUsrId, $projectId, 'getrow');
			$projectPath = RvsLibs_File::buildPath(array(PROJECT_PATH, $projectId));
			if ($res) {
				if (is_dir($projectPath) === false) {

					//SGL::raiseError แปลให้แล้วดังนั้นไม่ต้องแปล
					return SGL::raiseError(
					RvsLibs_String::translate(
            			'Project folder %PROJECTPATH is missing!'
            			, 'vprintf'
            			, array('PROJECTPATH' => $projectPath)
            			)
            			, null,null,false);
				}
			} else {
				return SGL::raiseError('Invalid project ID');
			}
			return true;
		}


		//project
		public static function isPublishCompoDB($project_id = null)
		{
			if (class_exists('Publish_Registry') == false) {
				$project_id = (is_null($project_id) === true)
					? SGL_Session::get('rvs_project_id')
					: $project_id;
				return RvsLibs_Component::isComponentDB($project_id);
			} else {
				$oReg = Publish_Registry::singleton();
				if (is_null($oReg->get('isComponentDB')) === true) {
					$project_id = (is_null($project_id) === true)
						? SGL_Session::get('rvs_project_id')
						: $project_id;
					$isComponentDB = RvsLibs_Component::isComponentDB($project_id);
					$oReg->set('isComponentDB', $isComponentDB);
				}
				return $oReg->get('isComponentDB');
			}
		}

		/**
		 * validate rvsitebuilder current version go to process replace variable {IMAGE_URL} , etc
		 *
		 * @param string $pathTarget
		 * @return boolean
		 */
		protected static function _isCheckUpdateReplaceUrl($pathTarget = null)
		{
			$rvsPath = RvsLibs_File::buildPath(array(SGL_PATH, 'rvsitebuilderversion.txt'));
			if (is_file($rvsPath) && is_file($pathTarget)) {
				$version = file_get_contents($rvsPath);
				$version = RvsLibs_String::preg_replace('/\n/i', '', $version);
				$versionChk = file_get_contents($pathTarget);
                $versionChk = RvsLibs_String::preg_replace('/\n/i', '', $versionChk);
                if ($version != $versionChk) {
                	$handle = RvsLibs_File::fopen($pathTarget, "w+");
                	if (SGL::isError($handle) === true) {
                		return $handle;
                	}
               		RvsLibs_File::fwrite($handle, $version);
                   	RvsLibs_File::fclose($handle);
                    return true;
                }
			}
			return false;
		}

		public static function validateCustomCssPath($projectId, $templateItemFolder)
		{
			//get custom path for new project and edit old poject (version 5.2+)
			$customCssPath = RvsLibs_File::buildPath(array(
				REAL_PROJECT_PATH, $projectId, 'customcss', $templateItemFolder
			));
			if (!is_dir($customCssPath)) {
				//get custom path for old project (version 5.0.xx-)
				$customCssPath = RvsLibs_File::buildPath(array(
					REAL_PROJECT_PATH, $projectId, 'customcss'
				));
			}
			return $customCssPath;
		}
	}
}

if (class_exists('RvsLibs_Project') === false) {
	class RvsLibs_Project extends RvsLibs_Project_Validate
	{
		public static function suspendTryoutPublishFolder($suspend, $reseller = '')
		{
			// Get Reseller
			if ($reseller != '') {
				if (is_array($reseller)) {
					$aResellerList = $reseller;
				} else {
					$aResellerList = array(0 => $reseller);
				}
			} else {
			   /* modify CpHandle by nipaporn*/
				$aResellerList = array();
				$oCp = CpHandle::factory();
				if(SGL::isError($oCp) === true) {
					SGL_Error::pop();
				    return array();
				}
				$aResellerList = $oCp->getResellers();
			}
			// Foreach Reseller
			foreach ($aResellerList as $key=>$reseller) {
				$tryoutPublishFolder = '/home/' . $reseller . '/public_html/tryout/users';
				if ($suspend == true) {
					// move reseller .htaccess
					if (file_exists($tryoutPublishFolder . '/.htaccess') && !file_exists($tryoutPublishFolder . '/.htaccessSuspend')) {
						rename($tryoutPublishFolder . '/.htaccess', $tryoutPublishFolder . '/.htaccessSuspend');
					}
					// write .htacces
					if (is_writable($tryoutPublishFolder)) {
						$handle = fopen($tryoutPublishFolder . '/.htaccess' , 'w');
						$deny = "  Order deny,allow \n     Deny from all";
						fwrite($handle , $deny);
					}
					// write .htaccessSuspend
					if (!file_exists($tryoutPublishFolder . '/.htaccessSuspend') && is_writable($tryoutPublishFolder)) {
						$handle = fopen($tryoutPublishFolder . '/.htaccessSuspend' , 'w');
						$content = "";
						fwrite($handle , $content);
					}
				} else {
					// delete .htaccess
					if (file_exists($tryoutPublishFolder . '/.htaccessSuspend')) {
						unlink($tryoutPublishFolder . '/.htaccess');
					}
					// revert reseller .htaccess
					if (file_exists($tryoutPublishFolder . '/.htaccessSuspend')) {
						rename($tryoutPublishFolder . '/.htaccessSuspend', $tryoutPublishFolder . '/.htaccess');
					}
				}
			}
		}

		/**
		 * return script include file js / css / php
		 *
		 * @param string $action 0=wysiwyg step5 , 1=preview, 2=publish
		 * @param string $data
		 * @param string $publishPath
		 * @param string $publishUrl
		 * @param string $fileName
		 * @param string $fileExtention (js/css/php)
		 * @return string script include
		 */
		public static function projectIncludeFile($action, $data , $publishPath, $publishUrl , $fileName , $fileExtention)
		{
			require_once SGL_LIB_PEAR_DIR . '/System.php';
			if (file_exists($publishPath . '/rvsincludefile') === false) {
				RvsLibs_System::mkDir(array('-p', '-m', 0755, $publishPath . '/rvsincludefile'));
				SGL::logMessage("*******" . $publishPath . '/rvsincludefile', PEAR_LOG_DEBUG);
			}
			RvsLibs_System::chmod($publishPath . '/rvsincludefile', '0755');
			$filePath = $publishPath . '/rvsincludefile/' . $fileName . '.' . $fileExtention;
			$fileUrl = $publishUrl . '/rvsincludefile/' . $fileName . '.' . $fileExtention;

			if(is_writable($publishPath . '/rvsincludefile')) {
				$handle = fopen($filePath,'w+');
				if (SGL::isError($handle) === true) {
					return $handle;
				}
				fwrite($handle,$data);
				fclose($handle);
			}

			SGL::logMessage("***** project include: " . $filePath, PEAR_LOG_DEBUG);
			$scriptInclude = "";
			if (RvsLibs_String::strtolower($fileExtention) == 'php' && is_file($filePath)) {
				$scriptInclude = "\n" . "<?php include('" . $filePath . "'); ?>" . "\n";
			} elseif (RvsLibs_String::strtolower($fileExtention) == 'css' && is_file($filePath)) {
				$scriptInclude = "\n" . '<link rel="stylesheet" href="' . $fileUrl . '" type="text/css" />' . "\n";
			} elseif (RvsLibs_String::strtolower($fileExtention) == 'js') {
				$scriptInclude = (is_file($filePath) && $action != 0)
				? "\n" . '<script  type="text/javascript" src="' . $fileUrl . '"></script>' . "\n"
				: "\n" . '<script> ' . "\n" . $data . "\n" . '</script>' . "\n";
			}
			return $scriptInclude;
		}


		public static function writeHtaccess($fileHtaccess)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$htaccessData = <<< EOF
Options -Indexes

<IfModule mod_rewrite.c>
RewriteEngine On
</IfModule>
EOF;
            $handle = RvsLibs_File::fopen($fileHtaccess,'w+');
            if (SGL::isError($handle) === true) {
            	return $handle;
            }
           	RvsLibs_File::fwrite($handle, $htaccessData);
           	RvsLibs_File::fclose($handle);
		}

		public static function createUserProjectFolder($projectId, $projectPath = PROJECT_PATH, $realProjectPath = REAL_PROJECT_PATH)
		{
			SGL::logMessage('createUserProjectFolder path='.$path, PEAR_LOG_DEBUG);
			$path = RvsLibs_File::buildPath(array($projectPath, $projectId));
			$target = RvsLibs_File::buildPath(array($realProjectPath, $projectId));
			if (is_dir($projectPath) === false) {
				RvsLibs_System::mkdir(array($projectPath));
			}
			if (is_dir($target) === false) {
				RvsLibs_System::mkdir(array('-p',$target));
			}

			if (!is_link($path)) {
				return (symlink($target, $path)) ? true: false;
			}
		}

		/**
		 * check ถ้า ยังไม่มี link project ให้ทำ link ให้
		 * @param $projectId
		 * @param $projectPath
		 * @param $realProjectPath
		 * @return unknown_type
		 */
		public static function validateLinkProject($projectId, $projectPath = PROJECT_PATH, $realProjectPath = REAL_PROJECT_PATH)
		{
			$oCp = CpHandle::factory();
			if(SGL::isError($oCp) === true) {
				return SGL::raiseError(RvsLibs_String::translate('CpWaring %MESSAGE', 'vprintf', array('MESSAGE' => $oCp->getMessage())));
			}
			$linkProjectPath = RvsLibs_File::buildPath(array($projectPath, $projectId));
			$linkRealProjectPath = RvsLibs_File::buildPath(array($realProjectPath, $projectId));

			SGL::logMessage('===linkProjectPath== ' . $linkProjectPath, PEAR_LOG_DEBUG);
			SGL::logMessage('===linkRealProjectPath== ' . $linkRealProjectPath, PEAR_LOG_DEBUG);

			//if symlink project is wrong!! remove auto
			if (is_link($linkProjectPath) && file_exists($linkRealProjectPath) ) {
				$projectUserPath = RvsLibs_String::preg_replace('/\/$/', '', readlink($linkProjectPath));
				SGL::logMessage('===readlink==projectUserPath== ' . $projectUserPath, PEAR_LOG_DEBUG);
				if ($projectUserPath != $linkRealProjectPath) {
					SGL::logMessage('===delete==linkProjectPath== ' . $linkProjectPath, PEAR_LOG_DEBUG);
					RvsLibs_System::unlink($linkProjectPath);
				}
			}
			if ( !is_link($linkProjectPath) && file_exists($linkRealProjectPath) ) {
				$resSecure = ($oCp->isValidCreateProject() === true)
				? RvsLibs_Project::createUserProjectFolder($projectId)
				: $oCp->secureCommandMakeLinkProjectId($projectId);

				if (SGL::isError($resSecure) === true ) {
					$aErrors['cannot create symlink'] = RvsLibs_String::translate('Cannot create project folder symlink');
					SGL_Error::pop();
				}

				if (!RvsLibs_System::function_exists('symlink')) {
					$aErrors['cannot create symlink2'] = RvsLibs_String::translate('Please contact your provider enable php function symlink in php.ini');
				}
			}
		}

		/**
		 * wysi design sytle data zone block add by darawan 19/01/2553
		 *
		 * @param string $pageData
		 * @return string $codeDataPage
		 */
		public static function bodyPageDataZone($aPageData = ''){
			SGL::logMessage('rvdebug: ===== ' , PEAR_LOG_DEBUG);
			$oPublishReg = Publish_Registry::singleton();
			$isUikit = $oPublishReg->get('isUikit');
			$codeDataPage = '';
			$rvsLayoutId = ($aPageData->rvs_layout_id) ? $aPageData->rvs_layout_id : 1;
			//$rvsLayoutId = $aPageData->rvs_layout_id;
			if ( isset($rvsLayoutId) && $rvsLayoutId != '' && $rvsLayoutId != '0' ) {
				$aLayoutPage = Daofactory::ProjectLayoutPage()->findRvsListLayout($rvsLayoutId, 'getarray');
				if (isset($aLayoutPage[0])) {
					$numOfZone = $aLayoutPage[0]['num_of_zone'];
					$codeDataPage =  $aLayoutPage[0]['layout_data'];
					$codeDataPage = preg_replace('/display\s*:\s*\s*none\s*;*/i', '', $codeDataPage);// replace ลบ display:none  ออกจาก layout
					$numOfColumn = $aLayoutPage[0]['num_of_colums'];
					for ( $i=1; $i <= $numOfZone; $i++){
						switch($i){
							case 2 : $pageDataZone = $aPageData->page_data_zone_2;break;
							case 3 : $pageDataZone = $aPageData->page_data_zone_3;break;
							case 4 : $pageDataZone = $aPageData->page_data_zone_4;break;
							default : $pageDataZone = $aPageData->page_data;break;
						}
						// === replace Data Zone , style='display:none;' =======
						$blockId = rand(1, 77); //5
						SGL::logMessage("get filename: blockID:" . $blockId, PEAR_LOG_DEBUG);
						$aBlockContent = Daofactory::ProjectLayoutPage()->findRvsBlockByrvsBlockId($blockId);
						$defaultData = $aBlockContent[$blockId]->block_data;
						$defaultData = self::_findLayoutImages($defaultData);
						//check is show layout set default zone data
						$defaultData = (RvsLibs_Config::isNoLayoutTemplste() === true)
						               ? ''
						               : $defaultData;
						$pageDataZone = (isset($pageDataZone) && $pageDataZone != '') ? $pageDataZone : $defaultData;
						$pageDataZone = str_replace('$', '\$', $pageDataZone);
						$codeDataPage = preg_replace('/DataZone'.$i.'/i', $pageDataZone, $codeDataPage);// วาง page_data ให้แต่ละ zone
					}
					// === replace width column =======
					$aPattentCol = array('/\$colum_width_1/i','/\$colum_width_2/i','/\$colum_width_3/i');
					$aCol = array($aPageData->colume_width_1.'%',$aPageData->colume_width_2.'%',$aPageData->colume_width_3.'%');
					$codeDataPage = RvsLibs_String::preg_replace($aPattentCol, $aCol, $codeDataPage);
					if ($isUikit == true) {
						//UIKit ใช้ ajax get data by id="layout_zone1"
						if (preg_match_all('/wysiwyg get data cannot delete/ims', $aPageData->page_data, $aMatch) == false) {
							$codeDataPage = RvsLibs_Template::getContainer($aPageData->page_data, $isUikit);
							$codeDataPage = '<div id="layout_zone1"><!-- wysiwyg get data cannot delete id=layout_zone1 -->' . "\n" . $codeDataPage . "\n</div>";
						} else {
							$codeDataPage = '<div id="layout_zone1">' . "\n" . $aPageData->page_data . "\n</div>";
						}
					}
				}
				SGL::logMessage('Complete ', PEAR_LOG_DEBUG);
				return (isset($codeDataPage) && $codeDataPage != '') ? $codeDataPage : $aPageData->page_data;
			} else {
				return  $aPageData->page_data;
			}
		}

		/**
		 * TODO มีปัญหาา error บ่อย
		 * @param unknown_type $codeDataPage
		 * @return mixed
		 */
		protected static function _findLayoutImages($codeDataPage)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$oPublishReg = Publish_Registry::singleton();
			$publishUrl = $oPublishReg->get('publishUrl');
			$publishPath = $oPublishReg->get('publishPath');
			$projectId = $oPublishReg->get('project_id');
			$projectId = (is_null($projectId) === true)
			              ? SGL_Session::get('rvs_project_id')
			              : $projectId;


			//********************** new function input codeData
			if (class_exists('TemplateList') === false) {
				include_once(SGL_MOD_DIR . '/sitebuilder/classes/TemplateList.php');
			}
			$configBlockDesign = parse_ini_file(SGL_MOD_DIR . "/sitebuilder/data/rvs_blockdesign.ini", true);
			$oTemplateList = TemplateList::singleton();
			$aCate = $oTemplateList->_getRefCategoryId($projectId);
			$aCategory = $oTemplateList->getCategoryList();
			$cateName = (isset($aCategory[$aCate['rvs_category_id']])) ? $aCategory[$aCate['rvs_category_id']] : '';

			preg_match_all('/<img\s*src\=\"(.*?)\"\s*alt=""\s*width=\"(.*?)\"\s*height=\"(.*?)\".*>/si', $codeDataPage, $aMatch);

			$aPatern = array();
			$aReplace = array();
			if (isset($aMatch[2]) && count($aMatch[2])) {

				foreach ($aMatch[2] as $k => $v) {
					$folder = $v . 'x' . $aMatch[3][$k];
					//ย้ายไปทำทีเดียวตอนก่อน copy file
					//$path = $publishPath . '/rvs_library/' . $folder;
					//RvsLibs_System::mkDir(array('-p', 755, $path));
					$aImages = (isset($configBlockDesign[$cateName][$folder])) ? $configBlockDesign[$cateName][$folder] : array();
					$rand_keys = (count($aImages)) ? array_rand($aImages, 1) : 1;
					$randImageName = (isset($aImages[$rand_keys])) ? $aImages[$rand_keys] : 'blank';
					$aReplace[$k] = 'rvs_library/' . $folder . '/' . $randImageName . '.jpg" alt="" width="' . $v . '" height="' . $aMatch[3][$k] . '"';
				}
			}
			if (isset($aMatch[1]) && count($aMatch[1])) {
				foreach ($aMatch[1] as $k => $v) {
					$w = $aMatch[2][$k];
					$h = $aMatch[3][$k];
					/// fix bug lost data page data
					$p = RvsLibs_Template::_registerPatturn($v) . '"' . '\s*alt=""\s*width="'. $w .'"\s*height="'. $h .'"';
					$aPatern[$k] = "/" . $p . "/";
				}
			}
			if (count($aPatern) && count($aReplace)) {
				$codeDataPage = RvsLibs_String::preg_replace($aPatern, $aReplace, $codeDataPage);
			}
			return $codeDataPage;
		}

		public static function checkProjectPagePerms($projectId , $rvsUsrId, $projectPageId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aPageData = RvsLibs_Project::getProjectPageData($projectId , $rvsUsrId, $projectPageId);
			if (empty($aPageData)) {
				$aPageData = RvsLibs_Project::getInternalPageData($projectId , $rvsUsrId, $projectPageId);
			}
			if (empty($aPageData)) {
				RvsLibs_String::translate(SGL::raiseError('Permission denied.', SGL_ERROR_INVALIDFILEPERMS, PEAR_ERROR_DIE));
			}
			return $aPageData;
		}

		public static function replaceHead($aHead)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			/* Head */
			// optimize : nipaporn
			return $aHead;
		}

		//project
		public static function makeProjectConfigFile($projectId, $aValue)
		{
			SGL::logMessage(" proejct_ID:: " . $projectId, PEAR_LOG_DEBUG);
			$projectConfPath = RVS_USER_HOME . '/.rvsitebuilder/websitepublish/' . $projectId .'/var';
			if (!is_dir($projectConfPath)) {
				RvsLibs_System::mkDir(array('-p', $projectConfPath));
				RvsLibs_System::chmod($projectConfPath, '0755');
			}
			$result = RvsLibs_Config::writeConfigToIniFile($aValue, $projectConfPath . '/rvstemplateconf.ini.php');
			RvsLibs_File::makeIniUnreadable($projectConfPath);
            // optimize :nipaporn
			return ($result) ? true : false;
		}

		public static function registOnlineFormSession($pageId, $pageData)
		{
			if ( preg_match_all("/id\s*=\s*\"onlineForm/i", $pageData, $aMatchForm)
			&& !SGL_Session::get("onlineform_" . $pageId)) {
				//SGL_Session::remove("onlineform_" . $pageId);
				SGL_Session::set("onlineform_" . $pageId, true);
			}
			return true;
		}

		/**
		 * validate is noSlogan return null
		 *
		 * @param boolean $noSloganConf : 0 ,1
		 * @param String $slogan
		 * @return String Slogan
		 */
		public static function noSlogan($noSloganConf, $slogan)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			// optimize :nipaporn
			return($noSloganConf != 1) ? $slogan : "";
		}

		/**
		 * validate is noCompanyName return null
		 *
		 * @param boolean $noCompanyConf : 0 , 1
		 * @param String $companyName
		 * @return String $companyName
		 */
		public static function noCompanyName($noCompanyConf,$companyName)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			// optimize :nipaporn
			return ($noCompanyConf != 1) ?  $companyName : "";
		}

		//project
		public static function fixedHtaccessFile($publishFolder, $backupHtaccessFile=null)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			if (is_null($backupHtaccessFile) === true) {
				$fileHtaccess = RvsLibs_File::buildPath(array($publishFolder, '.htaccess'));
			} else {
				$fileHtaccess = RvsLibs_File::buildPath(array($publishFolder, $backupHtaccessFile));
			}
			if (is_file($fileHtaccess)) {
				if (is_writable($fileHtaccess)) {
					// Read .htaccess
					$readHandle = fopen($fileHtaccess, "r");
					if (SGL::isError($readHandle) === true) {
						return $readHandle;
					}
					$htaccess = fread($readHandle, filesize($fileHtaccess));
					fclose($readHandle);

					// Change the directory index.
					$regExp = "/DirectoryIndex\s*.*?\.(html|htm|php)/i";
					$replaceBy = 'DirectoryIndex index.php';
					$fixed = RvsLibs_String::preg_replace($regExp, $replaceBy, $htaccess);

					// Write .htaccess
					if ($fixed != $htaccess) {
						$writeHandle = fopen($fileHtaccess, "w");
						if (SGL::isError($writeHandle) === true) {
							return $writeHandle;
						}
						fwrite($writeHandle, $fixed);
						fclose($writeHandle);
					}
				} else {
					$msg = "There is the .htaccess file on your web space. Please make sure you need it.";
					RvsLibs_String::translate(SGL::raiseMsg($msg));
				}
			}
			return true;
		}

    //optimaiz
		public static function pageNameMapping($aPageData,$homePageId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aBuffer = array();
			foreach ($aPageData as $k=>$v) {
				$cusTomPageName = RvsLibs_String::trim($v->custom_page_name);
				if ($cusTomPageName != '') {
					$pageName = $cusTomPageName;
				} else {
					$pageName = $v->page_name;
				}
				$pageName = RvsLibs_String::trim($pageName);
				$pageName =  RvsLibs_String::preg_replace('/\/|\?|\[\[BR\]\]|\s/' , '-', $pageName);
				$pageName =  RvsLibs_String::preg_replace('/&/' , '-and-', $pageName);
				$pageName =  RvsLibs_String::str_replace('.' , '-', $pageName);
				$pageName =  RvsLibs_Url::url_encode($pageName);
				$aBuffer[$v->project_page_id] =     $pageName;
				$aPageData[$k]->project_real_page_id = $v->project_page_id;
			}
			//  replace internal page
			foreach ($aPageData as $k => $v) {
				if (isset($aPageData[$k]->page_data)) {
					if (preg_match_all('/href=[\"|\']([0-9a-z]+)\.(html+|php+)[\"|\']/i', $aPageData[$k]->page_data , $aElement)) {
						foreach ($aElement[0] as $k2=>$v2) {
							$patternReplace = $aElement[1][$k2] . '\.' .  $aElement[2][$k2];
							$projectPageId = $aElement[1][$k2];
							if ($aElement[1][$k2] != $homePageId) {
								$replaceValue = $aBuffer[$projectPageId] . '.' . $aElement[2][$k2];
							} else {
								$replaceValue = 'index.' . $aElement[2][$k2];
							}
							$aPageData[$k]->page_data = RvsLibs_String::preg_replace("#$patternReplace#si", $replaceValue, $aPageData[$k]->page_data);
						}
					}
				}
			}
			// assign name
			foreach ($aPageData as $k=>$v) {
				if ($aPageData[$k]->project_page_id != $homePageId) {
					$customPageName = RvsLibs_String::trim($aPageData[$k]->custom_page_name);
					if ($customPageName != '') {
						$pageName = $customPageName;
					} else {
						$pageName = $aPageData[$k]->page_name;
					}
					$aPageData[$k]->project_page_id = RvsLibs_String::trim($pageName);
					$aPageData[$k]->project_page_id =  RvsLibs_String::preg_replace('/\/|\?|\[\[BR\]\]|\s/' , '-', $aPageData[$k]->project_page_id);
					$aPageData[$k]->project_page_id =  RvsLibs_String::preg_replace('/&/' , '-and-', $aPageData[$k]->project_page_id);
					$aPageData[$k]->project_page_id =  RvsLibs_String::str_replace('.','-',$aPageData[$k]->project_page_id);
					$aPageData[$k]->project_page_id =  RvsLibs_Url::url_encode($aPageData[$k]->project_page_id);
				} else {
					$aPageData[$k]->project_page_id = 'index';
				}
			}
			// add number if redunce
			$abuff = array();
			foreach ($aPageData as $k=>$v) {
				$name = $aPageData[$k]->project_page_id;
				if (array_key_exists($name, $abuff)) {
					foreach ($abuff as $val) {
						$abuff[$name]++;
						$aPageData[$k]->project_page_id = $name . $abuff[$name];
						if (!array_key_exists($aPageData[$k]->project_page_id, $abuff)) {
							break;
						}
					}
				} else {
					$abuff[$name] = 1;
				}
			}
			return $aPageData;
		}

		/**
		 * mapping page name
		 *
		 * @param $pageName
		 * @param $pageId
		 * @param $aCustomPage array('{pageId}'=>'{custom_page_name}')
		 * @param $aPageBuffer array('{pageName}'=>{countPage})
		 */
		public static function pageNameMappingV5($pageName, $pageId, $aCustomPage, &$aPageBuffer)
		{
			//SGL::logMessage(null, PEAR_LOG_DEBUG);
			$pageName = RvsLibs_Project::getShotFileName($pageName);
			if (isset($aCustomPage[$pageId])) {
				if (!isset($aPageBuffer[$pageName]) || $pageName == $aCustomPage[$pageId]) {
					$aPageBuffer[$pageName] = 1;
				} else {
					$pageName = RvsLibs_Project::_getPageMaping($pageName, $aPageBuffer, $aCustomPage);
				}
			} else {
				$pageName = RvsLibs_Project::_getPageMaping($pageName, $aPageBuffer, $aCustomPage);
			}
			return $pageName;
		}

		protected static function _getPageMaping($pageName, &$aPageBuffer, $aCustomPage)
		{
			$count = isset($aPageBuffer[$pageName]) ? $aPageBuffer[$pageName] : 1;
			$buffPage = $pageName;
			while (in_array($buffPage, $aCustomPage) || isset($aPageBuffer[$buffPage])) {
				$count += 1;
				$buffPage = $pageName . $count;
			}
			$aPageBuffer[$pageName] = $count;
			if ($buffPage != $pageName) {
				$aPageBuffer[$buffPage] = 1;
				$pageName = $buffPage;
			}
			return $pageName;
		}

		public static function getShotFileName($pageName) {
			$pageName = RvsLibs_String::trim($pageName);
			$pageName =  RvsLibs_String::preg_replace('/\/|\?|\[\[BR\]\]|\s|\*|\(|\)/' , '-', $pageName);
			$pageName =  RvsLibs_String::preg_replace('/&/' , '-and-', $pageName);
			$pageName =  RvsLibs_String::str_replace('.', '-', $pageName);
			$pageName =  RvsLibs_String::str_replace('#', '_', $pageName);
			if (RvsLibs_String::strlen($pageName, 'utf-8') > 80) {
				$pageName = RvsLibs_String::dbeSubstr($pageName, 0, 80);
			}
			return $pageName;
		}

		public static function getHomePageId($projectId=null, $usrId=null){
			if (is_null($projectId)) {
				$projectId = RvsLibs_Project::getProjectId();
			}
			if (is_null($usrId)) {
				$usrId = RvsLibs_User::getUserId();
			}
			$home_page_id = RvsLibs_Project::getLessPriority($projectId, $usrId);
			if (SGL::isError($home_page_id)) {
				SGL_Error::pop();
				$home_page_id = '';
			}

			return $home_page_id;
		}


		public static function replaceValueOnPageData($rvsUserID, $ProjectId)
		{
			//replace value page data v5 pharadol
			$pathReplace = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $ProjectId, 'replaceValue'));
			$fileReplace = RvsLibs_File::buildPath(array($pathReplace, '/pageData.txt'));
			if (!is_dir($pathReplace)) {
				RvsLibs_System::mkdir(array('-p', '-m', 0755, $pathReplace));
			}
		    //open file
            if (!is_file($fileReplace)) {
                $handle = RvsLibs_File::fopen($fileReplace, "w+");
                if (SGL::isError($handle) === true) {
                	return $handle;
                }
                RvsLibs_File::fclose($handle);
            }
			//ถ้าไม่มีไฟล์ให้ replace
			if (self::_isCheckUpdateReplaceUrl($fileReplace) === true) {
				SGL::logMessage("replace var ===> replaceValueOnPageData", PEAR_LOG_DEBUG);
				$aPageData = DaoFactory::ProjectPage()->findProjectPageAndProjectLayoutPageByProjectIdProjectPageIdAndUsrIdOrderByPriority($ProjectId, $rvsUserID, 'getall');
				RvsLibs_Project::_updateDataToVariable($aPageData, $rvsUserID, $ProjectId);
			}
		}

		public static function replaceValueOnInternalPage($rvsUserID, $ProjectId)
		{
			//replace value page data v5 pharadol
			$pathReplace = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $ProjectId, 'replaceValue'));
			$fileReplace = RvsLibs_File::buildPath(array($pathReplace, '/internalPage.txt'));
			if (!is_dir($pathReplace)) {
				RvsLibs_System::mkdir(array('-p', '-m', 0755, $pathReplace));
			}
			//open file
			if (!is_file($fileReplace)) {
				$handle = RvsLibs_File::fopen($fileReplace, "w+");
				if (SGL::isError($handle) === true) {
					return $handle;
				}
				RvsLibs_File::fclose($handle);
			}
			//ถ้าไม่มีไฟล์ให้ replace
			if (self::_isCheckUpdateReplaceUrl($fileReplace) === true) {
				SGL::logMessage("replace var ===> replaceValueOnInternalPage", PEAR_LOG_DEBUG);
				$aInternalPage = DaoFactory::ProjectPage()->findInternalPageDataByProjectIdAndProjectPageId($rvsUserID, $ProjectId, null, 'getall');
				RvsLibs_Project::_updateDataToVariable($aInternalPage, $rvsUserID, $ProjectId);
			}
		}

		public static function replaceValueOnEmbed($rvsUserID, $ProjectId)
		{
			//replace value page data v5 pharadol
			$pathReplace = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $ProjectId, 'replaceValue'));
			$fileReplace = RvsLibs_File::buildPath(array($pathReplace, '/emBed.txt'));
			if (!is_dir($pathReplace)) {
				RvsLibs_System::mkdir(array('-p', '-m', 0755, $pathReplace));
			}
			//open file
			if (!is_file($fileReplace)) {
				$handle = RvsLibs_File::fopen($fileReplace, "w+");
				if (SGL::isError($handle) === true) {
					return $handle;
				}
				RvsLibs_File::fclose($handle);
			}
			//ถ้าไม่มีไฟล์ให้ replace
			if (self::_isCheckUpdateReplaceUrl($fileReplace) === true) {
				SGL::logMessage("replace var ===> replaceValueOnEmbed", PEAR_LOG_DEBUG);
				$aSide = DaoFactory::Side()->findsideConfigAndsideValue($ProjectId, 'getarray');
				if (count($aSide)) {
					foreach ($aSide as $key => $val) {
						if ($ProjectId != '') {
							$sideValue = RvsLibs_Project::replaceUrlToValue($val['side_value'], $ProjectId);
						}
						DaoFactory::Side()->updateSideValueByProjectIdAndUserId($sideValue, $rvsUserID, $ProjectId, $val['side_config']);
					}
				}
			}
		}

		protected static function _updateDataToVariable($aPage, $rvsUserID, $ProjectId)
		{
			if (count($aPage)) {
				foreach ($aPage as $key => $val) {
					$pageData = RvsLibs_Project::replaceUrlToValue($val->page_data, $ProjectId);
					$pageZone2 = RvsLibs_Project::replaceUrlToValue($val->page_data_zone_2, $ProjectId);
                    $pageZone3 = RvsLibs_Project::replaceUrlToValue($val->page_data_zone_3, $ProjectId);
                    $pageZone4 = RvsLibs_Project::replaceUrlToValue($val->page_data_zone_4, $ProjectId);

                    DaoFactory::ProjectPage()->updatePagedataByProjectIdAndUserId(
                    	$val->project_page_id
                    	, $rvsUserID
                    	, $pageData
						, $pageZone2
						, $pageZone3
                    	, $pageZone4
					);

					if ($val->rvs_component_id) {
						$aHeaderFooter = DaoFactory::Component()->findComponentHeaderFooterByProjectPageId($val->project_page_id, 'getassoc');
						if (isset($aHeaderFooter[$val->project_page_id]->header)) {
							$pageHeader = RvsLibs_Project::replaceUrlToValue($aHeaderFooter[$val->project_page_id]->header, $ProjectId);
							DaoFactory::Component()->updateHeaderByUsrIdAndProjectIdAndProjectPageId($pageHeader, $rvsUserID, $ProjectId, $val->project_page_id);
						}

						if (isset($aHeaderFooter[$val->project_page_id]->footer)) {
							$pageFooter = RvsLibs_Project::replaceUrlToValue($aHeaderFooter[$val->project_page_id]->footer, $ProjectId);
							DaoFactory::Component()->updateFooterByProjectIdAndUsrIdAndProjectPageId($pageFooter, $ProjectId, $rvsUserID, $val->project_page_id);
						}
					}
				}
			}
		}

	public static function updateFlashIndex($projectId)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        require_once RvsLibs_File::buildPath(
            array(SGL_MOD_DIR, 'sitebuilder', 'classes', 'CreateProjectMgr.php')
        );

        $oCreate = new CreateProjectMgr();
        /* Update flash index.php */
        $projectDir = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $projectId));
        $aDirIgnore = array(
            'scripts','documents', 'images', 'media', 'tmp', 'rvsUtf8Config'
            , 'rvsUtf8Backup', 'RvSitebuilderPreview', '_temp'
        );
        $afolder = RvsLibs_System::ls(array($projectDir), $aDirIgnore);
        if (isset($afolder['dirs']) && is_array($afolder['dirs'])) {
            foreach ($afolder['dirs'] as $dir) {
            	if (empty($dir) || is_string($dir) === false) {
            		continue;
            	}
                $fileIndex = RvsLibs_File::buildPath(array($dir, 'index.php'));

                if (is_dir($dir) === true && RvsLibs_String::preg_match("#flash_#si", $dir, $aMatch)
                && is_file($fileIndex)
                ) {

                    $flashData = join('', RvsLibs_File::file($fileIndex));

                    $flashData = RvsLibs_Project::_replaceIndexFlash($flashData);

                    $flashData = $oCreate->updataTryoutData2CPdata($flashData);

                    $headen = RvsLibs_File::fopen($fileIndex, "w");
                    if (SGL::isError($headen) === true) {
                        return $headen;
                    }
                    RvsLibs_File::fwrite($headen, $flashData);
                    RvsLibs_File::fclose($headen);
                }
            }
        }
    }

	    //เหลือ replace custom special variable
        public static function replaceUrlToValue($codeBody, $projectId)
        {
            $imageUrl = '{IMAGE_URL}';
            $documentUrl = '{DOCUMENT_URL}';
            $mediaUrl = '{MEDIA_URL}';
            $websiteUrl = '{WEBSITE_URL}';
            $rvsLibrary = '{LIBRARY_URL}';
            $rvsMediaLibrary = '{LIBRARY_MEDIA_URL}';
            //images ducument
            $codeBody = preg_replace('/src\s*=\s*\"[^"]*\/' . $projectId . '\/documents\//i', 'src="' . $documentUrl . '/', $codeBody);
            $codeBody = preg_replace('/src\s*=\s*\"[^http|^https][0-9a-zA-Z\/\.:_]+\/documents\//i', 'src="' . $documentUrl . '/', $codeBody);
            $codeBody = preg_replace('/href\s*=\s*\"[^"]*\/' . $projectId . '\/documents\//', 'href="' . $documentUrl . '/', $codeBody);
            //$codeBody = preg_replace('/href\s*=\s*\"(|\/).*?/\//i', 'href="' . $documentUrl . '/', $codeBody);
            $codeBody = preg_replace('/src\s*=\s*\"(|\/).*?wysiwygpro\//i', 'src="' . $websiteUrl . '/', $codeBody);
            //images upload
            $codeBody = preg_replace('/src\s*=\s*\"[^"]*\/' . $projectId . '\/images\//i', 'src="' . $imageUrl . '/', $codeBody);
            $codeBody = preg_replace('/src\s*=\s*\"[^http|^https][0-9a-zA-Z\/\.:_]+\/images\//i', 'src="' . $imageUrl . '/', $codeBody);
            //images link
            $codeBody = preg_replace('/href\s*=\s*\"[^"]*\/' . $projectId . '\/images\//', 'href="' . $imageUrl . '/', $codeBody);

            //images rvs_librarys
            $codeBody = preg_replace('/(src|href)\s*=\s*\"[^"]*\/rvs_library\//i','$1="' . $rvsLibrary . '/', $codeBody);

            //rvs_media_library
            $codeBody = preg_replace('/src\s*=\s*\"[^"]*\/rvs_media_library\//i', 'src="' . $rvsMediaLibrary . '/', $codeBody);
            $codeBody = preg_replace('/(data|value|href)\s*=\s*\"[^"]*\/rvs_media_library\//i', '$1="' . $rvsMediaLibrary . '/', $codeBody);

            //media mp3
            $codeBody = preg_replace('/value\s*=\s*\"file=(|\/).*?\/media\//i', 'value="file=' . $mediaUrl . '/', $codeBody);
            $codeBody = preg_replace('/<embed\s*[id|name|]+\s*=\s*\"(.*?)\"\s*(.*?)\s*src\s*=\s*\"(.*?)\/media\//i', '<embed id="$1" $2 src="' . $mediaUrl . '/',$codeBody);
            $codeBody = preg_replace('/value\s*=\s*\"\/.*?\/media\//i', 'value="' . $mediaUrl . '/', $codeBody);
            $codeBody = preg_replace('/value\s*=\s*\"\{WYSIWYG_URL\}\/media\//ims', 'value="' . $mediaUrl . '/', $codeBody);
            $codeBody = preg_replace('/(src|filename|value)\s*=\s*"[^"]*\/' . $projectId . '\/media\//i','$1="' . $mediaUrl . '/', $codeBody);
            //media flash .swf
            $codeBody = preg_replace('/quality\s*=\s*\"high\"\s*src\s*=\s*\"(|\/)(http:|https:)\/\/.*?\/' . $projectId . '\/media\//i','src="' . $mediaUrl . '/', $codeBody);

            //image background and image layout template
            $codeBody = preg_replace('/background\s*=\s*\"[^http|https].*?\/images\//i', 'background="' . $websiteUrl . '/', $codeBody);
            $codeBody = preg_replace('/url\((\/|\')(.*?)\/images\//i', 'url(' . $websiteUrl . '/', $codeBody);
            //echo $codeBody;exit;
            return $codeBody;
        }

        public static function fixBrokenSpaceImageUrl($data)
        {
        	//SGL::logMessage(null, PEAR_LOG_DEBUG);
        	$data = preg_replace('/src\s*=\s*"[^"]*?sitebuilder\/images5\/spacer.gif"/ims', 'src="' . PUBLIC_IMG_V5_URL . '/spacer.gif"', $data);
        	$data = preg_replace('/src\s*=\s*"[^"]*?sitebuilder\/images\/spacer.gif"/ims', 'src="' . PUBLIC_IMG_URL . '/spacer.gif"', $data);
        	$data = preg_replace('/src\s*=\s*"[^"]*?sitebuilder\/images\/space.gif"/ims', 'src="' . PUBLIC_IMG_URL . '/space.gif"', $data);
        	$data = preg_replace('/src\s*=\s*"[^"]*?sitebuilder\/images\/\/thumb\-vdo\.jpg"/ims', 'src="' . PUBLIC_IMG_URL . '/thumb-vdo.jpg"', $data);
        	$data = preg_replace('/src\s*=\s*"\{IMAGE_URL\}\/space.gif"/ims', 'src="' . PUBLIC_IMG_URL . '/space.gif"', $data);

        	return $data;
        }

        public static function replaceValueToUrl($codeBody, $publishUrl, $themeUrl)
        {
       		##replace wysiwyg/media
        	$codeBody = preg_replace('/value\s*=\s*\"\/.*?\/wysiwyg\/media\//i', 'value="{MEDIA_URL}/', $codeBody);
        	$codeBody = preg_replace('/src\s*=\s*\"\/.*?\/wysiwyg\/media\//i', 'src="{MEDIA_URL}/', $codeBody);

        	//LIBRARY_URL
        	$codeBody = preg_replace('/(href|src)\s*=\s*\"{LIBRARY_URL}\//i', '$1="' . $themeUrl. '/rvs_library/',  $codeBody);

        	//LIBRARY_MEDIA_URL
        	$codeBody = preg_replace('/(href|src|value|data)\s*=\s*\"{LIBRARY_MEDIA_URL}\//i', '$1="' . $themeUrl . '/rvs_media_library/', $codeBody);

        	// Fix: Counter
        	if (preg_match('/src\s*=\s*"{IMAGE_URL}\/counter02\.gif"/', $codeBody)) {
        		$codeBody = preg_replace('/src="{IMAGE_URL}\/counter02\.gif"/i', 'src="' . $themeUrl . '/themes/default/sitebuilder/images/counter02.gif"', $codeBody);
        	}

        	//image {IMAGE_URL}
        	$codeBody = preg_replace('/src\s*=\s*\"{IMAGE_URL}\//i', 'src="' . $publishUrl . '/images/', $codeBody);
        	$codeBody = preg_replace('/src\s*=\s*\"{IMAGE_URL}\//i', 'src="' . $publishUrl . '/themes/default/sitebuilder/images/', $codeBody);
        	$codeBody = preg_replace('/href\s*=\s*\"{IMAGE_URL}\//i', 'href="' . $publishUrl . '/images/', $codeBody);
        	$codeBody = preg_replace('/url\({IMAGE_URL}(\/\/|\/)/im', 'url(' . $publishUrl . '/images/', $codeBody);

        	//image {DOCUMENT_URL}
        	$codeBody = preg_replace('/src\s*=\s*\"({DOCUMENT_URL}|{DOCUTMENT_URL})\//i', 'src="' . $publishUrl . '/documents/', $codeBody);
        	$codeBody = preg_replace('/href\s*=\s*\"({DOCUMENT_URL}|{DOCUTMENT_URL})\//i', 'href="' . $publishUrl . '/documents/', $codeBody);
        	//wysiwyg
        	$codeBody = preg_replace('/src\s*=\s*\"{WYSIWYG_URL}\//i', 'src="' . $publishUrl . '/wysiwyg/', $codeBody);

        	//replace media
        	$codeBody = preg_replace('/src\s*=\s*\"[0-9a-zA-Z\/\.:_]+(?:%7B|\{)IMAGE_URL(?:%7D|\})\//i', 'src="' . $publishUrl . '/images/', $codeBody);
        	$codeBody = preg_replace('/href\s*=\s*\"[0-9a-zA-Z\/\.:_]+(?:%7B|\{)IMAGE_URL(?:%7D|\})\//i', 'href="' . $publishUrl . '/images/', $codeBody);
        	$codeBody = preg_replace('/value\s*=\s*\"file={MEDIA_URL}\//i', 'value="file=' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/flashvars\"\s*value\s*=\s*\"{MEDIA_URL}\//i','flashvars" value="' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/value\s*=\s*\"{MEDIA_URL}\//i','value="' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/src\s*=\s*\"{MEDIA_URL}\//i','src="' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/src\s*=\s*"{MEDIA_URL}\//i','src="' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/href\s*=\s*\"{MEDIA_URL}\//i', 'href="' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/filename\s*=\s*"{MEDIA_URL}\//i','filename="' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/flashvars\s*file={MEDIA_URL}\//i', 'flashvars file=' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/flashvars\s*=\s*"file={MEDIA_URL}\//i', 'flashvars="file=' . $publishUrl . '/media/', $codeBody);
        	$codeBody = preg_replace('/background\s*=\s*\"{WEBSITE_URL}\//i', 'background="' . $publishUrl . '/images/', $codeBody);
        	$codeBody = preg_replace('/background\s*=\s*\"{IMAGE_URL}\//i', 'background="' . $publishUrl . '/images/', $codeBody);
        	//replace image laouttemplate
        	$codeBody = preg_replace('/src\s*=\s*"{WEBSITE_URL}\//i', 'src="'. $publishUrl .'/wysiwygpro/', $codeBody);
        	$codeBody = preg_replace('/{WEBSITE_URL}\//i', $publishUrl . "/images/", $codeBody);
        	//replace image
        	$codeBody = preg_replace('/url\({WEBSITE_URL}\//i', "url('" . $publishUrl . "/images/", $codeBody);

        	return $codeBody;
        }

        protected static function _replaceIndexFlash($FlashProject)
        {
	         $projectUrl = '{BASE_URL}';
	         //online flash
	         $FlashProject = RvsLibs_String::preg_replace('/(src|value)\s*=\s*\"(.*?)\/_temp\//i', '$1="' . $projectUrl . '/_temp/', $FlashProject);

	         return $FlashProject;
        }

		public static function replaceCpanelUrlToNobase($line)
		{
			$line = preg_replace('/"(|\/)[0-9a-z]*\/3rdparty\/rvsitebuilder\/project\//im', '"' . PROJECT_URL . '/', $line);
			$line = preg_replace('/"(|\/)[0-9a-z]*\/3rdparty\/rvsitebuilder\//im', '"' . RVSNOBASE_URL_WWW . '/', $line);
		    return $line;
		}

		public static function replaceDaToNobase($line)
		{
			$line = str_replace('"/CMD_PLUGINS/rvsitebuilder/images/', '"' . RVSNOBASE_URL_WWW . '/', $line);
			$line = preg_replace('/"http(|s):\/\/[0-9a-zA-Z._-]*\/\.rvsitebuilderHome\/projects\//i', '"' . PROJECT_URL . '/', $line);
			return $line;
		}

		public static function replaceNocpToNobase($line)
		{
			//$line = preg_replace('/src\s*=\s*\\\"(|\/)rvsitebuilder\/www\/wysiwyg\//i', 'src="' . RVSNOBASE_URL_WWW . '/wysiwyg/', $line);
			//$line = preg_replace('/value\s*=\s*\\\"(|\/)rvsitebuilder\/www\/wysiwyg\//i', 'value="' . RVSNOBASE_URL_WWW . '/wysiwyg/', $line);
			//$line = preg_replace('/src\s*=\s*\\\"(|\/)rvsitebuilder\/www\/rvs_library\//', 'src="' . RVSNOBASE_URL_WWW . '/rvs_library/', $line);
			//$line = preg_replace('/src\s*=\s*\\\"(|\/)rvsitebuilder\/www\/rvs_media_library\//i', 'src="' . RVSNOBASE_URL_WWW . '/rvs_media_library/', $line);
			//$line = preg_replace('/value\s*=\s*\\\"(|\/)rvsitebuilder\/www\/rvs_media_library\//i', 'value="' . RVSNOBASE_URL_WWW . '/rvs_media_library/', $line);

			$line = preg_replace('/(src|value)\s*=\s*\\\"(|\/)rvsitebuilder\/www\/(wysiwyg|rvs_library|rvs_media_library)\//i', '$1="' . RVSNOBASE_URL_WWW . '/$3/', $line);


			//$line = preg_replace('/src\s*=\s*\\\"(|\/)rvsitebuilder\/www\/project\//i', 'src="' . PROJECT_URL . '/', $line);
			//$line = preg_replace('/href\s*=\s*\\\"(|\/)rvsitebuilder\/www\/project\//i', 'href="' . PROJECT_URL . '/', $line);
			//$line = preg_replace('/value\s*=\s*\\\"(|\/)rvsitebuilder\/www\/project\//i', 'value="' . PROJECT_URL . '/', $line);

			$line = preg_replace('/(src|value|href)\s*=\s*\\\"(|\/)rvsitebuilder\/www\/project\//i', '$1="' . PROJECT_URL . '/', $line);
			//$line = preg_replace('/flashvars\s*=\s*\\\"file=(|\/)rvsitebuilder\/www\/project\//i', 'flashvars="file=' . PROJECT_URL . '/', $line);
			//$line = preg_replace('/value\s*=\s*\\\"file=(|\/)rvsitebuilder\/www\/project\//i', 'value="file=' . PROJECT_URL . '/', $line);
			$line = preg_replace('/(value|flashvars)\s*=\s*\\\"file=(|\/)rvsitebuilder\/www\/project\//i', '$1="file=' . PROJECT_URL . '/', $line);

			return $line;
		}

		public static function getSitebuilderDistLang($currentModule , $currentLang, $sitebuilder_v5 = false)
		{
			$globalLang = $GLOBALS['_SGL']['LANGUAGE'][$currentLang][1];
			$lang = ($sitebuilder_v5 == true) ? 'langv5' : 'lang';
			
			$distLangFile = RvsLibs_File::buildPath(array(SGL_PATH, 'modules', $currentModule, $lang, $globalLang . '.php'));
			//SGL::logMessage('langFile: ' . $distLangFile, PEAR_LOG_DEBUG);
			
			if (file_exists($distLangFile)) {
				require $distLangFile;
				$aDistLang = $words;
				unset($words);
			} else {
				$aDistLang = array();
			}
			return $aDistLang;
		}


		public static function replaceUrlToDirectAdmin($codeBody)
		{
			$codeBody = preg_replace('/src\s*=\s*\"(http:|https:).*?{IMAGE_URL}\//i', 'src="{IMAGE_URL}/',  $codeBody);
			$codeBody = preg_replace('/src\s*=\s*\"(http:|https:).*?{LIBRARY_MEDIA_URL}\//i', 'src="{LIBRARY_MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/value\s*=\s*\"(http:|https:).*?{LIBRARY_MEDIA_URL}\//i', 'value="{LIBRARY_MEDIA_URL}/', $codeBody);
			//image
			$codeBody = preg_replace('/href\s*=\s*\"(http:|https:).*?{IMAGE_URL}\//i', 'href="{IMAGE_URL}/', $codeBody);
			// $codeBody = preg_replace('/url\({IMAGE_URL}(\/\/|\/)/im', 'url(' . $publishURL . '/images/', $codeBody);

			//image ducument
			$codeBody = preg_replace('/src\s*=\s*\"(http:|https:).*?({DOCUMENT_URL}|{DOCUTMENT_URL})\//i', 'src="{DOCUMENT_URL}/', $codeBody);
			$codeBody = preg_replace('/href\s*=\s*\"(http:|https:).*?({DOCUMENT_URL}|{DOCUTMENT_URL})\//i', 'href="{DOCUMENT_URL}/', $codeBody);

			//End case directadmin
			$codeBody = preg_replace('/value\s*=\s*\"file=(http:|https:).*?{MEDIA_URL}\//i', 'value="file={MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/flashvars\"\s*value\s*=\s*\"(http:|https:).*?{MEDIA_URL}\//i','flashvars" value="{MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/value\s*=\s*\"(http:|https:).*?{MEDIA_URL}\//i','value="{MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/src\s*=\s*\"(http:|https:).*?{MEDIA_URL}\//i','src="{MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/href\s*=\s*\"(http:|https:).*?{MEDIA_URL}\//i', 'href="{MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/filename\s*=\s*"(http:|https:).*?{MEDIA_URL}\//i','filename="{MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/flashvars\s*file=(http:|https:).*?{MEDIA_URL}\//i', 'flashvars file={MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/flashvars\s*=\s*"file=(http:|https:).*?{MEDIA_URL}\//i', 'flashvars="file={MEDIA_URL}/', $codeBody);
			$codeBody = preg_replace('/background\s*=\s*\"(http:|https:).*?{WEBSITE_URL}\//i', 'background="{WEBSITE_URL}/', $codeBody);
			$codeBody = preg_replace('/background\s*=\s*\"(http:|https:).*?{IMAGE_URL}\//i', 'background="{IMAGE_URL}/', $codeBody);
			//replace image laouttemplate
			//$codeBody = preg_replace('/{WEBSITE_URL}\//i', $publishURL . "/images/", $codeBody);
			//replace image
			//$codeBody = preg_replace('/url\({WEBSITE_URL}\//i', "url('" . $publishURL . "/images/", $codeBody);
			return $codeBody;
		}

		/**
		 * if STEP 7 publish website check box forec update
		 * go to delete {PROJECT_ID}.conf.php
		 *         delete INSTALL_COMPLETE.php
		 *         delete rvsautosetup.ini.php
		 *
		 * @param <string> $projectId
		 * @return unknown_type
		 */
		public static function forceUpdateDb($forceUpdate,$projectId)
		{
			SGL::logMessage('L: ' . __LINE__ . 'forceUpdate: ' . $forceUpdate. ' projectId: ' . $projectId, PEAR_LOG_DEBUG);
			if ($forceUpdate == 1 && $projectId) {
				$pathFileConf = RvsLibs_String::sprintf('%s/.rvsitebuilder/websitepublish/%s/var/%s.conf.php', RVS_USER_HOME, $projectId, $projectId);
				$pathFileInstall = RvsLibs_String::sprintf('%s/.rvsitebuilder/websitepublish/%s/var/INSTALL_COMPLETE.php', RVS_USER_HOME, $projectId);
				$pathFileRvs = RvsLibs_String::sprintf('%s/.rvsitebuilder/websitepublish/%s/var/rvsautosetup.ini.php', RVS_USER_HOME, $projectId);
				if (is_file($pathFileConf)) {
					RvsLibs_System::unlink($pathFileConf);
				}
				if (is_file($pathFileInstall)) {
					RvsLibs_System::unlink($pathFileInstall);
				}
				if (is_file($pathFileRvs)) {
					 RvsLibs_System::unlink($pathFileRvs);
				}
			}
			return true;
		}

		/**
		* กรณี database name และ database user เคย save ไว้เกิน 8 character จะอัพเดทให้ auto
		*
		*/
		public function updateDbConfigToMinCharacter($projectId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			if ($projectId) {
				$fileCompoDBConf = RvsLibs_File::buildPath(
						array(REAL_PROJECT_PATH, $projectId, 'compoDBConnect.ini.php')
				);
				if (is_file($fileCompoDBConf)) {
					$aDBConfig = RvsLibs_Config::parse_ini_file($fileCompoDBConf,true);
				}

				if (isset($aDBConfig['DatabaseName']) && self::isOverDBCharater($aDBConfig['DatabaseName']) == true) {
					SGL::logMessage('==== over 8 character goto update', PEAR_LOG_DEBUG);
					$aDBConfig['DatabaseName'] = RvsLibs_DB::getMinCharacterName($aDBConfig['DatabaseName']);
					$aDBConfig['UserName'] = RvsLibs_DB::getMinCharacterName($aDBConfig['UserName']);

					SGL::logMessage('DatabaseName:' . $aDBConfig['DatabaseName'], PEAR_LOG_DEBUG);
					SGL::logMessage('UserName:' . $aDBConfig['UserName'], PEAR_LOG_DEBUG);
					$result = RvsLibs_Config::writeConfigToIniFile($aDBConfig, $fileCompoDBConf);
					if (SGL::isError($result) === true) {
						return SGL::raiseError($result->getMessage());
					}
					RvsLibs_File::makeIniUnreadable($fileCompoDBConf);
				}
			}
		}

		public function isOverDBCharater($name)
		{
			SGL::logMessage('string::' . $name, PEAR_LOG_DEBUG);
			$aName = RvsLibs_String::dbeExplode('_', $name);
			if (isset($aName[0]) && strlen($aName[0]) > 8 ) {
				return true;
			}
			return false;
		}

		/**
		 * in case cannot process is timeout of memory
		 * you can set maxmemory
		 *
		 * Ex.
		 *
		 $oldMemory = @ini_get('memory_limit');
		 $oldTimeOut = (int)@ini_get('max_execution_time');

		 * RvsLibs_Project::setMaximumMemory($oldMemory, $oldTimeOut);
		 * //.......
		 * // your process over memory
		 * //...........
		 * RvsLibs_Project::setRollbackMemory($oldTimeOut, $oldTimeOut);
		 *
		 * @var unknown_type
		 */
		function setMaximumMemory($oldMemory, $oldTimeOut)
		{
			$maxMemory = 512;
			$maxTimeOut = 180;
			SGL::logMessage("origi memory_limit ==".$oldMemory, PEAR_LOG_DEBUG);
			SGL::logMessage("origi max_execution_time ==".$oldTimeOut, PEAR_LOG_DEBUG);

			if ((int)$oldMemory < $maxMemory) {
				@ini_set('memory_limit', "$maxMemory" . "M");
			}
			if ($oldTimeOut < $maxTimeOut) {
				@ini_set('max_execution_time', $maxTimeOut);
			}
			$newMemory = @ini_get('memory_limit');
			$newTimeOut = (int)@ini_get('max_execution_time');
			SGL::logMessage("new memory_limit ==" . $newMemory, PEAR_LOG_DEBUG);
			SGL::logMessage("new max_execution_time ==" . $newTimeOut, PEAR_LOG_DEBUG);
		}

		/**
		 * set memory and max_execution_time to default
		 * @return unknown_type
		 */
		function setRollbackMemory($oldMemory, $oldTimeOut)
		{
			if ($oldMemory && $oldTimeOut) {
				@ini_set('memory_limit', $oldMemory);
				@ini_set('max_execution_time', $oldTimeOut);

				SGL::logMessage("old memory_limit ==". $oldMemory, PEAR_LOG_DEBUG);
				SGL::logMessage("old max_execution_time ==". $oldTimeOut, PEAR_LOG_DEBUG);
			}
		}

		public static function changeLayoutUpdatatoDb($projectId, $usrId)
		{
			SGL::logMessage("project: ". $projectId, PEAR_LOG_DEBUG);
			$oMgr = SGL_Manager::singleton();
			$aLayoutResponsive = DaoFactory::ProjectPage()->findProjectPageIdByUsrIdAndProjectId($usrId, $projectId,'getassoc');

			$aTemplateData = RvsLibs_Template::getTemplatesData($projectId, true, false);
			if(empty($aTemplateData)) {
				$aTemplateData = new stdClass();
			}
			$aTemplateData->templatePath = (isset($aTemplateData->templatePath)) ? $aTemplateData->templatePath : null;
			$aTemplateData->template_item_folder = (isset($aTemplateData->template_item_folder)) ? $aTemplateData->template_item_folder : null;

			$templateItemPath = $aTemplateData->templatePath . '/' . $aTemplateData->template_item_folder;
			$isResPonsive = (RvsLibs_Template::isResponsiveTemplate($templateItemPath) === true) ? true : false;

			if ($isResPonsive == true || count($aLayoutResponsive) == 0) {
				SGL::logMessage("is Responsive OR not have layout responsive not update", PEAR_LOG_DEBUG);
				return true;
			}

			$aPageSql = array();
			$filePageDataSql = REAL_PROJECT_PATH . '/' . $projectId . '/rvsPageData.sql';
			if (is_file($filePageDataSql)) {
				$aLine = file($filePageDataSql);
				if (count($aLine)) {
					foreach ($aLine as $line) {
						$aLineData = RvsLibs_Util::pasreSQLtoArray($line, $option = 'REPLACE');
						$table = $oMgr->conf['table']['rvs_project_page'];

						$pageId = (isset($aLineData[$table]['project_page_id']))
									? $aLineData[$table]['project_page_id']
									: '';
						$pageId = RvsLibs_String::trim(str_replace("'","", $pageId));

						$layoutId = (isset($aLineData[$table]['rvs_layout_id']))
								? $aLineData[$table]['rvs_layout_id']
								: '1';
						$layoutId = RvsLibs_String::trim(str_replace("'","", $layoutId));

						if ($pageId) {
							$aPageSql[$pageId] =  $layoutId;
						}
					}
				}
			} //End file


			//is Normal Template and have Layout responsive
			if ($isResPonsive == false && count($aLayoutResponsive)) {
				SGL::logMessage("isNotResponsive=1", PEAR_LOG_DEBUG);
				foreach ($aLayoutResponsive as $pageId => $layoutId) {
					//case: rvsPageData.sql
					if (isset($aPageSql[$pageId])) {
						$layoutId = $aPageSql[$pageId];
					} else {
						//case: no file rvsPageData.sql
						$layoutId = 1;
					}
					SGL::logMessage("Update pageid:" . $pageId . " layoutid:" . $layoutId, PEAR_LOG_DEBUG);
					DaoFactory::ProjectPage()->updateProjectPageDataByrvsLayoutId($layoutId, $pageId);
				}
			}
		}

	/**
	 * if v5
	 * return js/rvsitebuilderv5/*
	 *
	 * @param unknown $path
	 */
	public static function getJsCssPathV5($path, $type = 'js')
	{
		if (SGL_Output::isV6Session() == false && $type == 'js') {
			return str_replace('js/rvsitebuilder', 'js/rvsitebuilderv5', $path);
		} else if (SGL_Output::isV6Session() == false && $type == 'css') {
			return str_replace('themes/default/sitebuilder/', 'themes/default/sitebuilderv5/', $path);
		} else {
			return $path;
		}
	}

	} //End class RvsLibs_Project
}
?>